运行特定次数后如何中断代码[[Python]

2024-05-16 07:14:32 发布

您现在位置:Python中文网/ 问答频道 /正文

import random

results= ['Heads','Tails']
answers= ['Y','y','YES','yes']
result= random.choice(results)
counter = 0

print("Welcome to coin flippin' Mania")
question1= input("Flip coin? ")
question2= int(input("How many times? "))

while question1 in answers:
    print("\n\nThe coin landed on: %s" % result)
    counter +=1
    if counter == question2:
        break

如你所见,我才刚开始写代码,你上面看到的代码不是很好。我想能够告诉电脑它应该“抛硬币”的次数,我试过一些方法,但找不到答案


Tags: 代码importinputcounterrandomresultresultsyes
1条回答
网友
1楼 · 发布于 2024-05-16 07:14:32

您的代码运行良好,而循环根据用户输入中断。我想这就是你要找的,把result放在while循环中,这样你就可以在每次翻转时得到随机选择

import random

results= ['Heads','Tails']
answers= ['Y','y','YES','yes']
counter = 0

print("Welcome to coin flippin' Mania")
question1= input("Flip coin? ")
question2= int(input("How many times? "))

while question1 in answers:
    result = random.choice(results)
    print("\n\nThe coin landed on: %s" % result)
    counter +=1
    if counter == question2:
        break

相关问题 更多 >