2015-10-06 44 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

感謝戳,我從您的評論中瞭解到。我剛開始我的編程課,因爲我覺得它非常有趣,所以我一直在前進。所以,也許我很快就跳起了槍。感謝您打破代碼並解釋它。 –