Skip to content Skip to sidebar Skip to footer

Using A Variable Outside Of The Function (python)

so I've started learning python again and I'm currently making a mini movie-recommendator. I want my code to be a little bit more understandable so I'm always trying to use def to

Solution 1:

It's not best-practice to declare it as a global variable (as the other answers have recommended).

You should go to wherever welcome() is called and set a variable with the result (which you are returning inside welcome):

name = welcome()
print(f"This is the result of welcome: {name}")

Solution 2:

You can declare the variable name as global variable. Code -

defwelcome():
    global name
    print("""Welcome to the low budget film recommender!
             Here you can tell me what kind of movies do you like or what movie did you watch
             and I'll suggest you a movie from my database according to that.""")
    name = input("But first I need to learn your name:>> ").capitalize()
    print(f"Nice to meet you {name}")
    return name


defsecond_function():
    welcome()
    print(name) #prints the value of name in this function which was defined in the welcome()

second_function()

Solution 3:

I have modified your code a bit and by using the name variable as a global variable you can achieve what you want. Have a look at the code

#name as a global variable 
name = input("But first I need to learn your name:>> ").capitalize()

defwelcome():
    print("""Welcome to the low budget film recommender!
             Here you can tell me what kind of movies do you like or what movie did you watch
             and I'll suggest you a movie from my database according to that.""")
    # name = input("But first I need to learn your name:>> ").capitalize()print(f"Nice to meet you {name}")
    return name

print(welcome())

defmessage():
    return name

print(message())

Let me know if you still need any assistance

Post a Comment for "Using A Variable Outside Of The Function (python)"