I am not doing anything particularly complicated I am simply messing with import random and having the user type roll to roll a six sided die. I have gotten this far.
import random
roll = random.randint(1,6)
input("Type roll to roll the dice!\n")
# This is where I have my issue pass this line I'm trying things out, unsuccessfully.
if (userInput) == (roll)
print("\n" + str(roll))
else:
input("\nPress enter to exit.")
I don't want the program to print the str(roll)
if the use presses enter, I'd rather it exit the program if no input is given. So how do I write the code to do particular thing based of user input when using the if statement. If user input is 'roll"
then print("str(roll))
?
答案 0 :(得分:2)
You need to capture the user input in a variable. Currently, the return value of input(…)
is being thrown away. Instead, store it in userInput
:
userInput = input("Type roll to roll the dice!\n")
The if
requires a colon at the end in order to start the block:
if someCondition:
# ^
If you want to compare the user input against the string 'roll'
, then you need to specify that as a string, and not as a (non-existent) variable:
if userInput == 'roll':
You also don’t need parentheses around the values
In order to check for just an enter press, check against the empty string:
elif userInput == '':
print('User pressed enter without entering stuff')
You should roll inside the condition, not before, so you don’t generate a random number although it’s not requested.
So in total, it could look like this:
import random
userInput = input('Type roll to roll the dice!\n')
if userInput == 'roll':
roll = random.randint(1,6)
print('You rolled: ', roll)
elif userInput == '':
print('Exit')