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
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. :)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加