0

I'm trying to complete a school project where I create a maths quiz that randomly generates questions. You have to login with a name and classroom your in. All my code works apart from the section of code where I am trying to use a range for my class (Between class 1 and 3). It keeps popping up with an error saying:

TypeError: '<=' not supported between instances of 'int' and 'str'

while True:
  classCode=input("What class are you in? 1, 2, or 3? ")
  if 1 <= classCode <= 3:
    break
  else:
    print("That isn't a class. Please try again.")
    continue

Anyone know whats wrong with this code? This is my first question so if it's not in the right format I apologize.

Dan
  • 45,079
  • 17
  • 88
  • 157
Dylan
  • 25
  • 3
  • 2
    So the error message is clear, what type do you think `classCode` is? You need to cast it to an int `int(classCode)` – EdChum May 04 '18 at 15:40
  • as an aside, you could write `if classCode in list(range(1, 4)):` or `if classCode in [1, 2, 3]:` – William Perron May 04 '18 at 15:42
  • 1
    @WilliamPerron Things like `2 in range(1, 4)` work, the `list()` wrapper isn't required. But since the range is so small I'd use a literal tuple here. FWIW, the interpreter will actually convert a literal list like `[1, 2, 3]` into a tuple. – PM 2Ring May 04 '18 at 15:49
  • `classCode` is a `string`, and you need to convert it to an int. Look at [this question](https://stackoverflow.com/questions/1665511/python-equivalent-to-atoi-atof) on how to convert it to an `int` – Shark May 04 '18 at 18:13

1 Answers1

2

input() retrieves a string input from the user. You need to cast it to an int type. Something like:

classCodeStr=input("What class are you in? 1, 2, or 3? ")
classCode = int(classCodeStr)
platinum95
  • 378
  • 2
  • 11