2015-10-06 57 views
-1

我没有做任何特别复杂的事情,我简直搞乱了导入随机和让用户类型滚动一个六面骰子。我已经得到了这个。如何根据用户输入有python运行(if语句)?

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.") 

我不想程序打印str(roll)如果用按下回车,我宁愿它退出程序,如果没有输入给出。那么在使用if语句时,如何根据用户输入编写代码来执行特定的操作。如果用户输入是'roll"那么print("str(roll))

+0

你似乎没有救'userInput'。这个'if'语句也没有冒号结束,这是一个语法错误。你的代码是否完全像这样? – TigerhawkT3

+0

你似乎还把保存的变量名'roll'与字符串'roll'混淆了。您可能会考虑先审阅您的课本或其他课程资料。 – TigerhawkT3

+0

是的。我需要阅读更多关于userInput的内容。我只是在尝试。良好的语法错误。我很抱歉。 –

回答

2
  1. 您需要捕获变量中的用户输入。目前,input(…)的返回值正在被抛弃。相反,它存储在userInput

    userInput = input("Type roll to roll the dice!\n") 
    
  2. if需要在为了年底冒号开始块:

    if someCondition: 
    #    ^
    
  3. 如果要用户输入比较对字符串'roll' ,那么您需要将其指定为字符串,而不是(不存在)变量:

    if userInput == 'roll': 
    

    Y OU也不需要大约值括号

  4. 为了检查只是一个进入新闻界,检查对空字符串:

    elif userInput == '': 
        print('User pressed enter without entering stuff') 
    
  5. 您应该推出的条件里面,没有过,所以尽管没有请求,你不会生成一个随机数。

因此,在总,它看起来是这样的:

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') 
+0

感谢戳,我从您的评论中了解到。我刚开始我的编程课,因为我觉得它非常有趣,所以我一直在前进。所以,也许我很快就跳起了枪。感谢您打破代码并解释它。 –