This is my attempt at a simple dice game. when I run the program it asks me how many dice I want to roll when I enter 1, it just asks again and then closes the program.
I feel like at least one of my problems is that the input maybe isn't being read as an integer? I'm not really sure. In the mean time, I'm gonna stare at it for a while and maybe ill figure it out.
import random
def roll1Dice():
roll = random.randint(1,6)
print("You rolled a " + roll)
def roll2Dice():
roll1 = random.randint(1,6)
roll2 = random.randint(1,6)
print("You rolled a " + roll1)
print("You rolled a " + roll2)
def main():
input("roll 1 or 2 dice? ")
if input == 1:
roll1Dice()
elif input == 2:
roll2Dice()
else:
print("Please enter a 1 or a 2.")
main()
2 Answers 2
input is a function that returns a str. You need to capture this return and then compare it.
def main():
user_input = input("roll 1 or 2 dice? ")
if user_input == '1': # notice that I am comparing it to an str
roll1Dice()
elif user_input == '2':
roll2Dice()
else:
print("Please enter a 1 or a 2.")
main() # add this line to request input again
Alternatively, you could cast to an int:
def main():
user_input = int(input("roll 1 or 2 dice? "))
if user_input == 1: # notice that I am comparing it to an int here
roll1Dice()
elif user_input == 2:
roll2Dice()
else:
print("Please enter a 1 or a 2.")
main()
If you cast to an int, however, be aware that a non-int will cause an exception.
1 Comment
You weren't assigning the value of input to anything (input is the function that actually accepts user input) Also, your print statements were failing because they were trying to combine an int with a string, so I've replaced it using string formatting. The below code should help
import random
def roll1Dice():
roll = random.randint(1,6)
print("You rolled a %s" % roll)
def roll2Dice():
roll1 = random.randint(1,6)
roll2 = random.randint(1,6)
print("You rolled a %s" % roll1)
print("You rolled a %s" % roll2)
def main():
myinput = input("roll 1 or 2 dice? ")
if myinput == 1:
roll1Dice()
elif myinput == 2:
roll2Dice()
else:
print("Please enter a 1 or a 2.")
main()
value = int(input(...))and later usevalue == 1