所以我需要为我的 Python 课程编写一个实验室来掷硬币。是的,以前有人问过,但特别是这个,我在我所做的任何搜索中都没有看到任何示例。该程序应该接受用户的输入,掷硬币多少次。然后它使用该输入来翻转硬币所述次数并记录有多少正面和反面。最后,它会打印翻转次数,以及有多少正面和反面。然后程序应该提示用户输入另一个翻转次数,但是对于我的程序,每次它都会接受第二个输入,但会跳过循环并结束程序。此外,输入 0 应该终止程序。这是我尝试过的两个示例:
import random
timesToFlip = input("Enter the number of times to flip the coin: ")
def coinFlipGame(timesToFlip):
coinHeads = 0
coinTails = 0
accumulator = 0
while timesToFlip > 0 and accumulator < timesToFlip:
coinFlip = random.randint(0,1)
if coinFlip == 1:
accumulator += 1
print "After", accumulator, "flip(s) of the coin, the result was heads!"
coinHeads += 1
raw_input("Press [ENTER] to continue...."); print
else:
accumulator += 1
print "After", accumulator, "flip(s) of the coin, the result was tails!"
coinTails +=1
raw_input("Press [ENTER] to continue...."); print
print "Heads =", coinHeads, "| Tails =", coinTails; print
if timesToFlip == 0:
print; print "You have chosen to end the game. Goodbye!"
timesToFlip = input("Enter the number of times to flip the coin: ")
coinFlipGame(timesToFlip); print
这是另一个版本:
import random
timesToFlip = input("Enter the number of times to flip the coin: ")
def coinFlipGame(timesToFlip):
coinHeads = 0
coinTails = 0
accumulator = 0
if timesToFlip == 0:
print "You have chosen to end the game. Goodbye!"
else:
while timesToFlip > 0 and accumulator < timesToFlip:
coinFlip = random.randint(0,1)
if coinFlip == 1:
accumulator += 1
coinHeads += 1
print accumulator, "coin flip(s) performed. Heads."
else:
accumulator += 1
coinTails += 1
print accumulator, "coin flip(s) performed. Tails."
print "Flips:", accumulator, "| Heads:", coinHeads, "| Tails:", coinTails
timesToFlip = input("Enter the number of times to flip the coin: ")
coinFlipGame(timesToFlip)
任何有关如何在模块中获取输入以重复循环的帮助将不胜感激!:D 是的,教授说,我们必须在程序中使用模块。