Your error is due to failing to catch the raised error when int()
cannot extract an int from the user's input.
If you're interacting with user input and you need a certain validation, I generally recommend moving that logic out to a function. You can modify collect_int
from here to work with the turtle prompt you're using.
import turtle
def collect_int(
heading,
message,
err_msg="Invalid number entered. Please try again."
):
while True:
try:
return int(turtle.textinput(heading, message))
except ValueError:
message = err_msg
def bet_currency(user_currency):
while True:
bet = collect_int('Bet money.', f'You have {user_currency}')
if bet <= 0:
print('User tried to bet a negative amount.')
elif bet <= user_currency:
print(f'User betted {bet}$')
break
else:
print("Users can't bet what they don't have!")
user_currency = 100
bet_currency(user_currency)
It's a little odd to use print
if you're trying to interact with the user through the turtle GUI. The user might not think to look in the console. Maybe these are non-user viewable logs in an in-progress program you're working on, but it seems worth mentioning.
Note I've also passed eg
(renamed user_currency
for clarity) to the bet_currency
function. It's not a good idea for functions to reach outside of themselves to grab data -- all variables a function accesses should go into parameters. If there are too many parameters or the function mutates properties on an object, use a class to group multiple relevant pieces of data in a narrow scope. This avoids bugs and makes the program easier to write in the long term.
I also removed recursion: if the prompts fail long enough (~1000 times), the program crashes. It's unlikely that this will matter for your program, and security and reliability are probably not your top priorities right now, but it's just as easy to use a while True:
loop and do it correctly from the start.
elif bet <= 0:
and the else
are never going to happen because the first two branches cover all possible cases.
This condition seems incorrect:
bet >= user_currency:
print("Users can't bet what they don't have!")
I'd expect you can bet all your money, so I'd make it bet > user_currency
. This can just be else
since the first branch covers the other possible case <=
.
elif bet <= 0:
can never happen unless eg
can be negative. I'd just make this the first option, or see this answer which offers somewhat more generalized prompts which let you pass in a validation function that can block negative numbers and handle these different scenarios a bit more elegantly.