Reputation: 3
I'm having a problem with some coding that I'm doing for a school assignment, the same thing happened and I managed to fix it but I did so without knowing how I did it.
def number():
num = input("please enter the number of people that would like play:")
try:
if int(num) >= 2:
if int(num) <=7:
return num
else:
print("number must be 7 or less")
number()
else:
print("number must be greater than 2")
number()
except:
print("that is not a valid number. number must be between 2 and 7")
number()
number = number()
print(number,"people are playing")
This is the code which is causing the problem. If I enter an invalid number it works fine, I can just re-enter a new number, but as you can see I have wanted to print out the "number of people playing" but it returns with "none people are playing" but this is only after I have entered an invalid number. What can I do?
Upvotes: 0
Views: 257
Reputation: 46759
You need to use a loop rather than calling your routine again which will not have the effect you are looking for (look into recursion). Something like the following approach would be better:
def number():
while True:
num = input("please enter the number of people that would like play: ")
try:
num = int(num)
if num > 7:
print("number must be 7 or less")
elif num <= 2:
print("number must be greater than 2")
else:
return num
except:
print("that is not a valid number. number must be between 2 and 7")
number = number()
print(number, "people are playing")
The reason you are seeing None
is that it is possible to reach the bottom of your function without a return
being used. In this case Python defaults the returned value to None
.
Upvotes: 0
Reputation: 387677
In the ideal case, without any errors, number()
returns the entered num
and all is well. However, in all other cases, you end the function with a recursive call to number()
without actually returning anything. So the function implicitly returns None
(i.e. nothing).
Just change every recursive call to return number()
and it should work.
Btw. you should avoid recursion for this; see this answer on how to best ask the user repeatedly for valid input.
Upvotes: 4