-2

Here's the part of my code that's giving trouble:

    class_number = input("Before your score is saved ,are you in class 1, 2 or 3?")
    if class_number not in (1,2,3):
        sys.exit("That is not a valid class, unfortunately your score cannot be saved, please try again")
    else:
        filename = (class_number + "txt")

But when the program asks the user what class the user is, regardless of the input the program exits the system. This happens even if the user input is in (1,2,3).

Why isn't it working?

SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73
Ibrahim
  • 7
  • 5

2 Answers2

2

In Python3, input just returns a string, so when you call it to get the class_number variable you're getting a string instead of an int. You need to explicitly declare it as an int

class_number = int(input("Which classes scores would you like to see? Press 1 for class 1, 2 for class 2 or 3 for class 3"))

Alternatively, it might be safer to check the result against strings (since you don't need to perform arithmetic on the result)

if class_number not in ('1', '2', '3'):

This is safer because the previous method could call int() on a string that cannot be turned into a number and that will throw an exception. For example if the user enters "three" that will raise an exception. You'll have no such trouble if you just use a string.

SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73
1

Did you try this ?

class_number = int(input("..."))
if class_number not in (1, 2 ,3):
    sys.exit("...")

input in Python 3 is equivalent to raw_input in Python 2. It returns a string. If you want to compare a string to an int, you must convert one of the two. You can also do the following :

class_number = input("...")
if class_number not in ("1", "2" ,"3"):
    sys.exit("...")
FunkySayu
  • 7,641
  • 10
  • 38
  • 61