Moose
Moose

Reputation: 45

"Try" and "Except" in my program (python)

while True:  #code should only allow integers to be inputed
        try: 
            rolls = int(input("Enter the number of rolls: "))
            break
        except:
            print("You did not enter a valid Integer")

output works for characters like "b" and "d" but when I put a zero in, I still get the ZeroDivisionError

I want the code to only allow an integer.

later on in the code I tried this

if rolls <= 0:
    print("You must enter at least one roll")
    print()

but it doesnt stop the code from running and the error still pops up.

Upvotes: 0

Views: 39

Answers (1)

user2864740
user2864740

Reputation: 61865

There is no division in the posted code and it will not throw a ZeroDivisionError.

The exception is likely thrown when xyz / rolls is done later (outside that try/catch), when rolls evaluates to 0.

Fix the logic so as to not even allow such invalid division to occur! Maybe "0" means to exit the game? Or maybe "0" means that the user should be asked for another roll?


FWIW, here is modified code to read input that won't accept "0":

while True:  #code should only allow integers to be inputed
    try: 
        rolls = int(input("Enter the number of rolls: "))
        if rolls > 0:
            break
    except:
        pass # don't do anything here, because we print below for
             # exceptions and when the if guarding the break failed.
    print("You must enter a valid roll (> 0)")

Upvotes: 1

Related Questions