0

Here's something taken out of my code to check if the value is greater than 0 and if it's a number:

while(1):
        n = input("Type a number of rolls to do, to try and get 3 of the same sides in a row.")
        if n.isdigit() and int(n) > 0 == True:
            n = int(n)
            break
        else:
            print("Select a proper integer.")

For some reason if you enter a value that should stop the loop like 10, it's seen as a wrong integer. Why is that?

Socksonme
  • 25
  • 4
  • 2
    What input do you test it with? – inspectorG4dget Jan 05 '21 at 14:49
  • 2
    `0` doesn't equal `True`, hence the condition is always false. What you have there is a **chained comparison**. You should never explicitly do `== True`, as it's always superfluous and often introduces errors. – deceze Jan 05 '21 at 14:55
  • 2
    `int(n) > 0 == True` is equivalent to `int(n) > 0 and 0 == True`, not `(int(n) > 0) == True`, due to comparison chaining. – chepner Jan 05 '21 at 14:56
  • I completely forgot that you are not required to compare variables for an if statement (with a boolean like I did). Thanks for also explaining chained comparisons. – Socksonme Jan 05 '21 at 15:05

2 Answers2

5

Error aside, the "right" way to do this (specifically, without calling int(n) twice), is to simply catch an exception raised by int(n):

while True:
    n = input("Type a number...")
    try:
        n = int(n)
    except ValueError:
        continue

    if n > 0:
        break

    print("Select a positive integer")
    
chepner
  • 497,756
  • 71
  • 530
  • 681
2

Don't use ==:

while(1):
        n = input("Type a number of rolls to do, to try and get 3 of the same sides in a row.")
        if n.isdigit() and int(n) > 0:
            n = int(n)
            break
        else:
            print("Select a proper integer.")
dimay
  • 2,768
  • 1
  • 13
  • 22