[Tutor] elif statement doesn't work

Alan Gauld alan.gauld at yahoo.co.uk
Sun Feb 28 18:41:35 EST 2021


On 28/02/2021 21:04, hongerlapjes wrote:
> For school I have to make a simple roulette game.
> If the user inputs "STOP", the game starts. But I cant seem to make the 
> input STOP.  ValueError: invalid literal for int() with base 10: 'STOP'
> What am I doing wrong?

The error message says you are passing the string "STOP"
to the int() conversion function. int() does not know
how to convert "STOP" to an integer, so you get a ValueError.

This is a common problem when you mix input types.
You have to either test the type before converting
or catch the error and deal with it there.

The other option is not to convert the digits but
compare them with string numbers. But that really
only works for equality tests not for <>.

> def start ():
>      fiches = 10
>      print("Je hebt", fiches, "fiches!")
> 
>      while fiches > 0:
>          inzet=input("Op welk getal wil je inzetten?"'\n')
>          print(inzet)
> 
>          if int(inzet) >= 0 and int(inzet) <= 36 :
>              fiches -= 1
>              getallen.append(inzet)
>              print(getallen)
>              print("Je hebt nog", fiches, "fiches over.")
> 
>          elif str(inzet) == "STOP" :
>                  roulette()

Since "STOP" seems to be the only string you accept
the simple solution in this case is to move the test
for "STOP" before the conversion to int(). If inzet
is not "STOP" then you should be safe to convert it
to an integer.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list