MK2009
MK2009

Reputation: 59

Python: If...and... not working as expected

I'm trying to set up the below code to ask the user to enter two integers (num_sides & num_rolls). If the user doesn't enter an integer for either input, then the code should print the statement "Enter an integer".

I find this code only tests the num_sides but doesn't test if num_rolls is an integer. What's going on here?

Thanks in advance for your help!

def rolldice():
    while True:
        while True:
            num_sides = input("Enter number of sides for die: ")
            num_rolls = input("Enter number of rolls for die: ")
            try:
                if int(num_sides) != num_sides or int(num_rolls) != num_rolls:
                    break
                break
            except(ValueError):
                print("Enter an integer")
                True

Upvotes: 0

Views: 109

Answers (2)

user1823
user1823

Reputation: 1111

You can just cast int and check for a ValueError:

def rolldice():
    while True:
        try:
            num_sides = int(input("Enter number of sides for die: "))
            num_rolls = int(input("Enter number of rolls for die: "))
            break
        except ValueError:
            print("Enter an integer")

>>> rolldice()
Enter number of sides for die: 5
Enter number of rolls for die: foo
Enter an integer
Enter number of sides for die: foo 
Enter an integer
Enter number of sides for die: bar
Enter an integer
Enter number of sides for die: 1
Enter number of rolls for die: 2
>>> 

Upvotes: 0

jeromej
jeromej

Reputation: 11636

Why do you have a nested loop? (Two while True one inside the other one)

The following code is simpler and should work:

def rolldice():
    while True:
        num_sides = input("Enter number of sides for die: ")
        num_rolls = input("Enter number of rolls for die: ")
        try:
            int(num_sides)
            int(num_rolls)
            break
        except ValueError:
            print("Enter an integer")

If both int evaluate and do not crash then break is executed and you can leave the loop.

As it is a function, you might want to return (num_sides, num_rolls) at the end of the function so they aren't lost. (You could also replace the break with the return, which will effectively stop the function too at the same time)

Unless this is only the beginning of your code, then never mind what I just said. :)

Upvotes: 2

Related Questions