Dan the man 007
Dan the man 007

Reputation: 43

Editing an Integer from one def to another

Hello and apologies if a similar question has been answered, but I cannot find similar post. I am still rather new with python 3 and English is a little rough.

I start the program and it goes to character_start() where it ask for a name and sets a health variable to 10. It then calls the main() where it says the health again and it ask the user where they want to go. As for now the only option is 1 and that takes you to the trap() function. The user will be hit by 1 health and it should go back to main() where it will show them with 1 missing health.

I think the problem is it does not recognize the user_health as a global variable even when I write it outside of a def.

Thank you and here is my code.

import random

def character_start():
    user_name = input("Name: ")
    user_health = 10
    main()


def main():
    print("Health: ", user_health)
    print("Type 1 to walk into a trap.")
    main_choice = int(input("Choice: "))
    if (main_choice == 1): trap()


def trap():
    user_health = user_health - 1
    print("1 point of damage.")
    main()


character_start()

Upvotes: 4

Views: 99

Answers (1)

Jake Tae
Jake Tae

Reputation: 1741

Welcome to SO. This is a great community to learn and grow, so hope you can make the best out of it.

As you've pointed out yourself, main and trap have no knowledge of user_health, since the scope of user_health is confined to the limits of character_start. While the use of global variables is usually not recommended for a variety of reasons I won't elaborate here (for that, you can refer to this thread), but presented below is one possible implementation. Modified code segments have accompanying comments for reference.

import random

user_health = 10 # declare global var


def character_start():
    user_name = input("Name: ")
    main()


def main():
    print("Health: ", user_health) # main has access to user_health
    print("Type 1 to walk into a trap.")
    main_choice = int(input("Choice: "))
    if (main_choice == 1):
        trap()


def trap():
    global user_health # tell trap that user_health is a global var
    user_health = user_health - 1 # alter that global var
    print("1 point of damage.")
    main()


character_start()

The key takeaway here is that

  • Global variables are declared outside the scope of any function
  • If you want to modify a global variable, tell the function explicitly that a certain variable name refers to a global variable via the global keyword (as shown in the trap function)

Upvotes: 5

Related Questions