【发布时间】:2018-07-27 20:47:03
【问题描述】:
我刚开始学习 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 循环中,因此它会在继续询问我的输入时不断检查条件。
【问题讨论】:
-
您能否仔细检查此处显示的代码缩进?它在 Python 中很重要,而且看起来与您的代码中的不同。
-
建议:这里有很多用 Python 写的关于 SO 的硬币翻转,你可以用谷歌搜索它们并阅读代码。
-
请阅读ericlippert.com/2014/03/05/how-to-debug-small-programs 开始学习如何调试您的代码。
-
@AntonvBR:我相信我们应该能够告诉 OP 出了什么问题。
-
@usr2564301 假设他正确缩进了所有内容,该程序基本上可以工作。我没有遇到他遇到的问题。
标签: python coin-flipping