I am writing this program and it works fine, I leave it for sometime and the code stops working.
Please help me in this function; Here is the code:
acceptables = [1, 2, 3, 4, 5, 6, 10]
try :
toss = input("Toss a number from 1 to 6 (10 included): ")
except ValueError:
print("Invalid")
if toss != acceptables:
print("Illegal Numbers!")
time.sleep(2)
exit()
else:
pass
So what should happen is, the user will enter a number in toss and it will check if the number is from acceptables, if not it will quit the program.
But now, I entered number that is in acceptables and it still ends up showing "Illegal Number" and quits the program.
Is this a new python3 update or something that I missed out on? Please help
CodePudding user response:
You've got two problems:
toss = input(...)
returns a string, but you want to compare that value toint
s. Try a type conversion:toss = int(toss)
to transform yourstr
from"1"
to1
.You're checking if the number is in the list using
if toss != acceptables:
which will always beFalse
because anint
(orstr
at the moment) will never be equal to alist
. You want to check iftoss
is in the list ofacceptables
. Try this instead:if toss in acceptables:
CodePudding user response:
You have to cast toss
to int
, because python takes by Default string
in input
CodePudding user response:
There are a few issues. First, this line:
toss = input("Toss a number from 1 to 6 (10 included): ")
will store the string value of whatever you submit into toss
. You likely want this line to read:
toss = int(input("Toss a number from 1 to 6 (10 included): "))
to ensure you get an integer or a ValueError
in the case the user types a non-integer string.
Secondly, this line:
if toss != acceptables:
is checking if toss
, what would be an int, is not equal to a list, essentially doing this: if 5 != [1, 2, 3, 4, 5, 6, 10]
. You instead likely want this to read:
if toss not in acceptables:
To check if this number is in your list of acceptable numbers.