Home > OS >  If function error. Not equals to function not working
If function error. Not equals to function not working

Time:03-02

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:

  1. toss = input(...) returns a string, but you want to compare that value to ints. Try a type conversion: toss = int(toss) to transform your str from "1" to 1.

  2. You're checking if the number is in the list using if toss != acceptables: which will always be False because an int (or str at the moment) will never be equal to a list. You want to check if toss is in the list of acceptables. 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.

  • Related