2016-07-26 74 views
0

我是嶄新的python,因爲我的新學校需要它。我習慣於C++,所以我仍然在學習繩索。我試圖做一個骰子滾動模擬器,我以爲我做的一切正確,但我的代碼不會工作。任何提示或指導,以幫助我學習將不勝感激。這裏是我的代碼:Python 3骰子模擬問題

import random 

def roll(sides=6): 
    num_rolled = random.randint(l,sides) 
    return num_rolled 

def main(): 
    sides = 6 
    rolling = True 
    while rolling: 
     roll_again = input("Ready to roll? ENTER=Roll. Q=Quit. ") 
    if roll_again.lower() != "q": 
     num_rolled = roll(sides) 
     print("You rolled a", num_rolled) 
    else: 
     rolling = False 

    print("Thanks for playing!") 

main() 

這是我的錯誤:

Traceback (most recent call last): File "C:\Users\nomor\AppData\Local\Programs\Python\Python35-32\DiceRollingSim.py", line 20, in main() File "C:\Users\nomor\AppData\Local\Programs\Python\Python35-32\DiceRollingSim.py", line 13, in main num_rolled = roll(sides) File "C:\Users\nomor\AppData\Local\Programs\Python\Python35-32\DiceRollingSim.py", line 4, in roll num_rolled = random.randint(l,sides) NameError: name 'l' is not defined

+0

有什麼問題嗎?什麼不行? – Pythonista

+0

我不知道,但這是我得到的錯誤:Traceback(最近調用最後一次): 文件「C:\ Users \ nomor \ AppData \ Local \ Programs \ Python \ Python35-32 \ DiceRollingSim.py」,行20,在 主() 文件 「C:\用戶\ nomor \應用程序數據\本地\程序\的Python \ Python35-32 \ DiceRollingSim.py」,線13,在主 num_rolled =輥(邊) 文件「 C:\ Users \ nomor \ AppData \ Local \ Programs \ Python \ Python35-32 \ DiceRollingSim.py「,第4行,卷 num_rolled = random.randint(l,sides) NameError:name'l'is not defined – BradeyBunch

回答

1

對於第一個問題...

num_rolled = random.randint(l,sides) 

l != 1。你把一個「l」而不是數字1. Python認爲這是一個你沒有定義的變量 - >你得到的錯誤。

documentation randint需要兩個整數作爲參數:

random.randint(a, b) Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).

接下來,看看在你的這幾行代碼。

while rolling: 
    roll_again = input("Ready to roll? ENTER=Roll. Q=Quit. ") 
if roll_again.lower() != "q": 
    num_rolled = roll(sides) 
    print("You rolled a", num_rolled) 
else: 
    rolling = False 

if-else部分需要while循環的內部縮進:

while rolling: 
    roll_again = input("Ready to roll? ENTER=Roll. Q=Quit. ") 
    if roll_again.lower() != "q": 
     num_rolled = roll(sides) 
     print("You rolled a", num_rolled) 
    else: 
     rolling = False 
+1

非常感謝。菜鳥錯了吧?這實際上幫了很大忙。 – BradeyBunch

+0

沒問題,很高興我可以幫忙!我們都在某些時候犯了新人的錯誤:D – Pythonista