Reputation: 11
I'm a beginner in Python and I started messing around with it. I have this simple code:
def guess_number(Name,Gender):
if Gender=='Male':
Title='Mr.'
else:
Title='Ms.'
number=int(raw_input("Hello " + Title + Name + ", guess what my favorite number is between 1-10"))
if number==4:
print number
print "That's my favorite number!"
else:
print number
print "Try Again!"
return number
choice_dict=dict([(1,0),(2,0),(3,0),(4,0),(5,0),(6,0),(7,0),(8,0),(9,0),(10,0)])
for i in range(10):
guess_number("Noam","Male")
choice_dict[number]=choice_dict[number]+1
print choice_dict[1], choice_dict[2], choice_dict[3], choice_dict[4], choice_dict[5], choice_dict[6], choice_dict[7], choice_dict[8], choice_dict[9], choice_dict[10]
It's a simple process where in a function called "guess_number" it asks a person for a certain number between 1-10. It repeats the function 10 times and for each number chosen it will add +1 to the number in a dictionary, at the end it prints how many times was each number chosen.
For some reason I don't understand it tells me that "number" is not defined even though I returned the variable "number" in the function "guess_number".
What is missing?
Upvotes: 0
Views: 175
Reputation: 880717
Change
guess_number("Noam","Male")
to
number = guess_number("Noam","Male")
number
is defined in the (local) scope of the guess_number
function, but not in the global scope. To reference number
in the global scope, number
first needs to be bound to a value accessible from the global scope, and (local variables from a function are not accessible. See the LEGB rules, below.)
Reference:
Upvotes: 1
Reputation: 1165
The variable "number" in your function "guess_number" is only local to that function. To fix your problem, you have to assign a variable "number" to the result from "guess_number". Thus, change
guess_number("Noam","Male")
to
number = guess_number("Noam","Male")
Upvotes: 0
Reputation: 198476
number
is a variable local to the function guess_number
. It does not exist outside of it. What you return is the value - not the variable itself, but its value - which you need to use, or assign to something. You can even assign it to a variable of the same name - as long as you understand it's another variable that just happens to have the same name:
number = guess_number("Noam", "Male")
Upvotes: 4