嗨,我已經做了這個隨機骰子游戲,需要幫助創建一個循環,讓我當用戶輸入一個無效的數字我想他們再試一次。這裏是我的代碼請幫忙!骰子重複需要幫助
import random
dice = int(input("What sided dice do you want to use? (e.g. 4, 6 or 12): "))
if dice == 4:
random_number = int(random.randrange(1,4))
print ("You selected a 4 sided dice")
print ("Your dice has rolled ")
print (random_number)
elif dice == 6:
random_number2 = int(random.randrange(1,6))
print ("You selected a 6 sided dice")
print("Your dice has rolled ")
print (random_number2)
elif dice == 12:
random_number3 = int(random.randrange(1,12))
print ("You selected a 12 sided dice")
print("Your dice has rolled ")
print (random_number3)
else:
print(("You didn't select a valid sided dice, try again!"))*
注意'random.randrange'不包括端點,所以'randrange(1,4) '只會給你任何'[1,2,3]'。 –
這段代碼中有很多*重複;你可以使用'dice'變量來削減它的三分之二(例如'random.randrange(1,dice + 1')。 – jonrsharpe