im doing a little project for myself to understand the function, if statement in python. i want to call the "name" inside the user function and use it in jungle function.
def user():
global name
name = raw_input("Whats your name?")
def jungle():
print name, "Please, Select your Enemy"
print '\n'.join(jungle_enemy)
enemy = raw_input('> ')
if enemy == "1":
print "The Lion Will eat you alive."
game_over()
exit_countdown()
elif enemy == "2":
print "The Jaguar will tear you apart."
game_over()
exit_countdown()
elif enemy == "3":
print "The Snake will eat you whole."
game_over()
exit_countdown()
else:
try_again("Are You Noob? \nNone of the Choice!")
jungle()
when i run this code. it gives me an error. NameError : global name 'name' is not define.
Global variables are a bad idea in general. Better pass the variable to whoever needs it:
def user():
return raw_input("Whats your name?")
def jungle(name):
print name, "Please, Select your Enemy"
# etc.
and then call the functions like this
username = user()
jungle(username)
If you have to use global names, you need to use the global
statement in all the functions that use that variable - so you need to add global name
at the start of jungle()
. But don't do that. See where global variables have taken JavaScript - you don't want to do that in Python.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.