我想寫一個擲骰子的程序。現在,這是我所:Python中的骰子滾動模擬器
import random
print("You rolled",random.randint(1,6))
而且我也希望能夠做這樣的事情:
print("Do you want to roll again? Y/N")
,然後,如果我按Y鍵再次推出,如果我按NI退出應用程序。提前致謝!
我想寫一個擲骰子的程序。現在,這是我所:Python中的骰子滾動模擬器
import random
print("You rolled",random.randint(1,6))
而且我也希望能夠做這樣的事情:
print("Do you want to roll again? Y/N")
,然後,如果我按Y鍵再次推出,如果我按NI退出應用程序。提前致謝!
讓我們來看看這個過程: 你已經知道你需要什麼來產生隨機數。
import random
(或者你能更具體說from random import randint
,因爲我們只在這個程序需要randint
)print("You rolled",random.randint(1,6))
「擲骰子」。 但它只做了一次,所以你需要一個循環來重複它。 A while loop正在給我們打電話。Y
。你可以簡單地使用"Y" in input()
。 (好一點)代碼版本1.
import random
repeat = True
while repeat:
print("You rolled",random.randint(1,6))
print("Do you want to roll again? Y/N")
repeat = "Y" in input()
代碼版本1.1
from random import randint
repeat = True
while repeat:
print("You rolled",randint(1,6))
print("Do you want to roll again?")
repeat = ("y" or "yes") in input().lower()
在該代碼中,用戶可以自由地使用字符串像yEs
,y
,yes
, YES
和...繼續循環。
現在還記得,在1.1版本,因爲我用from random import randint
代替import random
,我不需要說random.randint(1, 6)
,只是radint(1,6)
將做的工作。
謝謝!這非常有用和簡單! –
import random
min = 1
max = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print "Rolling the dices..."
print "The values are...."
print random.randint(min, max)
print random.randint(min, max)
roll_again = raw_input("Roll the dices again?")
你應該添加一些解釋,因爲在這裏只考慮代碼的答案是低質量的。 –
的可能重複:http://stackoverflow.com/q/12608654/198633 – inspectorG4dget