我刚开始学习 Python 并试图编写以下问题:
硬币翻转模拟 - 编写一些代码来模拟翻转单个硬币,无论用户决定多少次。代码应记录结果并计算正面和正面的数量。
以下是我的代码:
import random
def num_of_input():
while True:
try:
time_flip= int(input('how many times of flips do you want?'))
except:
print('please try again')
continue
else:
break
return time_flip
def random_flip():
return random.randint(0, 1)
def count_for_sides():
count_head=0
count_tail=0
times=num_of_input()
while True:
if count_head+count_tail==times
break
else:
if random_flip()==0:
count_head+=1
else:
count_tail+=1
print(count_head)
print(count_tail)
我现在遇到的问题是:如果我将输入作为 x(x 次翻转),那么我需要输入 X+1 次才能看到结果,如下所示:
count_for_sides()
how many times of flips do you want?4
how many times of flips do you want?4
how many times of flips do you want?4
how many times of flips do you want?4
how many times of flips do you want?4
0
4
我真的很困惑这种情况。我认为这意味着我的输入函数处于一个 while 循环中,因此它会继续检查条件,因为它会继续询问我的输入。