My healthbar function is defined but when trying to add it to a string it is "Not defined"

Question:

I’m making a small adventure game and in advance I decided to try and figure out the def function because I have no clue how it works. This was my attempt after referencing some material and everything looks correct but when trying to string it in it is apparently not defined.

#Health test


print('Would you like to check your health?')
healthCheck = input()

if healthCheck == 'Y':
    print('Your current health is ' + str(healthBar) + '!')
    



def int(healthBar):
    healthBar == 100
    if healthBar == 0:
        print('You have died')

My initial plan was to do this:

print('Would you like to check your health?')
healthCheck = 100
answer = input()

if healthCheck == 0:
    print('You have died!')

if answer == 'Y':
    print('Your current health is ' + str(healthCheck) + '!')

But I figured def was a more efficient method.

Asked By: Virtx_x

||

Answers:

Functions are just "jump" instructions and are used to organize code into nice callable blocks. In your case, it seems like you want to organize the logic of checking whether a player has died into its own block. You can do something like this:

def check_health(healthBar, answer):
    if healthBar == 0:
        print('You have died!')

    if answer == 'Y':
        print('Your current health is ' + str(healthBar) + '!')

print('Would you like to check your health?')
answer = input()

healthCheck = 100
check_health(healthCheck, answer)

There are a couple issues with your code:

  1. You are using int as the function name. int is a keyword in Python so you should use a custom name.
  2. You never actually call the function after defining it. Notice how I define it with def (def means define) at the top. Then, I call it later on by doing check_health(healthCheck, answer)
  3. You are referencing a variable that is defined in the function. When you define healthBar inside the function, you cannot access it from outside the function. You can return values from your function in order to access them outside the function.

More information and examples of functions: https://www.programiz.com/python-programming/function

Answered By: Francis Godinho
healthbar = 100

def ask_for_health_check():
    answer = input("Whould you like to check your health?t")
    if answer.lower() in ('y', 'yes'):
        if healthbar == 0:
            print("You are dead...")
        else:
            print(f"Your current health is {healthbar}")

ask_for_health_check()
Answered By: lengthylyova

You need to define a function before you reference it, and you’re defining your function incorrectly.

Currently, you have defined a function called int (accepting a parameter called healthBar which is immediately overwritten in the function). Furthermore, functions are fundamentally used as a means of telling the program to do a certain thing (without you needing to write out that code every single time), but doesn’t encapsulate data.

However, for your use case, you might be better off defining a Health class instead, as that will allow you to store a hp value (within that class) and use the functionality for that health value within that class.

Something along these lines:

class Health():
    """class that holds functionality for health stuff"""
    
    def __init__(self, startHealth: int = 100):
        """
        creates this object, giving it startHealth health
        (100 health if startHealth not given)
        :param startHealth: how much HP to start with
        """
        self._hp: int = startHealth
        """ current HP """
        self._maxHP: int = startHealth
        """ maximum HP """
        
    def checkHealth(self) -> str:
        """
        this function checks current HP and
        returns string telling us what state
        this object is in
        """
        
        if (self._hp <= 0):
            return "You are dead!"
        else:
            return f"You have {self._hp} health!"
            
    def getHealth(self) -> int:
        """obtains current health
        :returns: current HP """
        return self._hp
        
        
    def adjustHealth(self, changeAmount: int, printHP: bool = True):
        """
        :param changeAmount: this will get added to current HP
        :param printHP: if true, we print our new HP
        """
        self.setHealth(self._hp + changeAmount, printHP)
        
    def setHealth(self, newHP: int, printHP: bool = True):
        """
        :param newHP: new current HP value
        :param printHP: if true, we print our new HP
        """
        self._hp = newHP
        if (self._hp < 0):
            self._hp = 0
        elif (self._hp > self._maxHP):
            self._hp = self._maxHP
        
        if (printHP):
            print(self.checkHealth())

and if you want to see it in action, here’s some code that will demonstrate its functionality:

helf: Health = Health(100)

print(f"initial health check: {helf.checkHealth()}")
print("> oh no a giant enemy crab just dealt 10 damage to you!")
helf.adjustHealth(-10)
print("> wow you found ye healing potion! regain 5 hp!")
helf.adjustHealth(5);
print("> giant enemy crab used 2018 humour on you! It's super effective! It just dealt 999 damage to you!")
helf.adjustHealth(-999);
print("> your corpse used life insurance! Revive with 50 HP!")
helf.setHealth(50);
print("> etc")

output:

initial health check: You have 100 health!
> oh no a giant enemy crab just dealt 10 damage to you!
You have 90 health!
> wow you found ye healing potion! regain 5 hp!
You have 95 health!
> giant enemy crab used 2018 humour on you! It's super effective! It just dealt 999 damage to you!
You are dead!
> your corpse used life insurance! Revive with 50 HP!
You have 50 health!
etc
Answered By: 11belowstudio
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.