Python硬币翻转程序while循环问题:随机结果始终单一
问题:硬币翻转程序随机函数未按预期工作
作为Python初学者,我写的硬币翻转程序有问题:random函数没达到预期效果。我希望计算机每次随机选head或tail,但运行结果要么全是head要么全是tail。以下是我的代码和运行结果,该怎么修改?
原代码
print("\n\tWelcome to the 'Flip a coin' program") import random input("\nPress the enter key to start playing!") flip_coin=random.randint(1,2) heads=0 tails=0 rolls=int(input("\nPlease, tell the computer how many rolls you want to do? ")) essai=0 while essai<rolls: essai+=1 if flip_coin==1: heads+=1 print("You've got a head") else: tails+=1 print("You've got a tail") print("\n\tThe job is done..") print("\n\tYou have a total of", heads,"heads and", tails,"tails")
运行结果
Welcome to the 'Flip a coin' program Press the enter key to start playing! Please, tell the computer how many rolls you want to do? 10 You've got a head You've got a head You've got a head You've got a head You've got a head You've got a head You've got a head You've got a head You've got a head You've got a head The job is done.. You have a total of 10 heads and 0 tails
问题原因与修改方案
问题根源
你只在循环外生成了一次随机数flip_coin=random.randint(1,2),之后循环里每次判断都用这个固定值,自然每次结果都一样。
修改方法
把生成随机数的代码移到while循环内部,让每次循环都重新生成一个1或2的随机数,这样每次翻转才会随机。
修改后的完整代码
print("\n\tWelcome to the 'Flip a coin' program") import random input("\nPress the enter key to start playing!") heads=0 tails=0 rolls=int(input("\nPlease, tell the computer how many rolls you want to do? ")) essai=0 while essai<rolls: essai+=1 # 每次循环重新生成随机数 flip_coin=random.randint(1,2) if flip_coin==1: heads+=1 print("You've got a head") else: tails+=1 print("You've got a tail") print("\n\tThe job is done..") print("\n\tYou have a total of", heads,"heads and", tails,"tails")
额外优化建议
可以用random.choice(['head', 'tail'])直接生成结果,代码更直观:
# 替换原判断部分 result = random.choice(['head', 'tail']) if result == 'head': heads +=1 print("You've got a head") else: tails +=1 print("You've got a tail")
内容的提问来源于stack exchange,提问作者A_heath
相关产品推荐
相关产品推荐

