How do I have python run (if statements) based on the users input.?

时间:2015-10-06 08:26:04

标签: python python-3.x

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))?

1 个答案:

答案 0 :(得分:2)

  1. 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")
    
  2. The if requires a colon at the end in order to start the block:

    if someCondition:
    #               ^
    
  3. 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

  4. In order to check for just an enter press, check against the empty string:

    elif userInput == '':
        print('User pressed enter without entering stuff')
    
  5. 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')