-1

When I run this code I get a invalid literal error when a letter is typed into the textinput() since it's only meant to register int values not str values. I tried a few diffrent things but none seemed to work.

import turtle

eg = 100

def betcurrency():
    bettedc = turtle.textinput('Bet money.',
    f'You have {eg}')

    if int(bettedc) <= eg:
        print(f'User betted {bettedc}$')
    elif int(bettedc) >= eg:
        betcurrency()
        print("Users can't bet what they don't have!")
    elif int(bettedc) <= 0:
        betcurrency()
        print('User tried to bet a negative amount.')
    else:
        betcurrency()
        print('User betted invalid money.')

This is the error I get;

Traceback (most recent call last):
  File "e:\Visual Studio Code\Python\Finished\Turtle Race\main.py", line 145, in <module>
    setup()
  File "e:\Visual Studio Code\Python\Finished\Turtle Race\main.py", line 112, in setup
    betcurrency()
  File "e:\Visual Studio Code\Python\Finished\Turtle Race\main.py", line 41, in betcurrency
    if int(bettedc) <= eg:
ValueError: invalid literal for int() with base 10: 'TEXT' #This is the text I put in.
Lloyd
  • 95
  • 1
  • 8
  • 1
    The error tells all: try typing in a number instead of a word. `int(bettedc)` attempts to convert `"TEXT"` to a number which fails and raises an error. Use `try`-`except` if you want to handle this and maybe prompt the user to try again with a friendly message. Check out the handy `collect_int` function in [this answer](https://stackoverflow.com/a/66935301/6243352). – ggorlen Jul 06 '21 at 21:59
  • @ggorlen Ok! Thank you il check that out right now. – Lloyd Jul 06 '21 at 22:04
  • If you use it, you'll need to swap `input(prompt)` for `turtle.textinput(prompt)`. Also, using recursion is risky here -- if the user keeps missing the first branch of the conditions your program can crash with a stack overflow. Using `while True:` is safer. – ggorlen Jul 06 '21 at 22:06
  • @ggorlen I looked over it and I understand what it's trying to do but because I am relatively new to coding I am having trouble implementing this into my code. Could you help me out a little? – Lloyd Jul 06 '21 at 22:07
  • Sure, I'll add an answer in a minute. – ggorlen Jul 06 '21 at 22:07

3 Answers3

0
import turtle

eg = 100

def betcurrency():
 try:
    bettedc = turtle.textinput('Bet money.',
    f'You have {eg}')

    if int(bettedc) <= eg:
        print(f'User betted {bettedc}$')
    elif int(bettedc) >= eg:
        betcurrency()
        print("Users can't bet what they don't have!")
    elif int(bettedc) <= 0:
        betcurrency()
        print('User tried to bet a negative amount.')
    else:
        betcurrency()
        print('User betted invalid money.')
 except ValueError :
  print("user wrote word not number as amount") 
Bahae El Hmimdi
  • 364
  • 1
  • 5
0

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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
0

If your Python turtle library has textinput(), it likely also has it's companion, numinput() which might address your issues:

import turtle

stack = 100

def betcurrency():
    bet = turtle.numinput("Bet money.", f"You have {stack}", minval=1, maxval=stack)

    if bet:
        print(f"User bet ${bet:.2f}")
    else:
        print("User cancelled bet.")

This might be simpler than trying to handle the potential errors yourself.

cdlane
  • 40,441
  • 5
  • 32
  • 81