我正在尝试编写一个程序,允许用户掷 2 个骰子并计算他们获得的总点数。
更新:非常感谢,我明白了:)
此解决方案有效:
import random
def roll_dice():
total = 0
while(True):
print ("Enter '1' to roll 2 dice, enter '2' to stop rolling")
user_input = input()
if user_input == '1':
d1 = random.randint(1,6)
d2 = random.randint(1,6)
print (d1, d2)
score = 0 # score this round
if d1 == d2:
score = 10
elif d1 == 6 or d2 == 6:
score = 4
elif d1 + d2 == 7:
score = 7
total += score # update total
print ("The score this round is ", score)
print ("The total number of points is", total)
elif user_input == '2':
print ("Thanks for playing!")
break
roll_dice()
请您参考如下方法:
每次掷两个骰子时,您的行
total = 0都会将total重置为零。尝试将total = 0放在while循环之外。subtotal = sum(both_dice)这个变量both_dice的用途是什么?为什么是列表?在您的代码中,它只能包含一个数字或根本不包含任何内容。
这个程序应该可以工作。请仔细逐行解释为什么这个程序有效。询问是否有任何不清楚的地方。
import random
def roll_dice():
total = 0
while(True):
print ("Enter '1' to roll 2 dice, enter '2' to stop rolling")
user_input = str(input()) # str() needed for Python 2
if user_input == '1':
d1 = random.randint(1,6)
d2 = random.randint(1,6)
print (d1, d2)
score = 0 # score this round
if d1 == d2:
score = 10
elif d1 == 6 or d2 == 6:
score = 4
elif d1 + d2 == 7:
score = 7
total += score # update total
print ("The score this round is ", score)
print ("The total number of points is", total)
elif user_input == '2':
print ("Thanks for playing!")
break
roll_dice()
