我决定在圣诞假期用我的锉刀学习python
。你知道吗
我正在运行Python 2.7
,在我正在进行的书中的一个练习中,我尝试编写一个抛硬币程序,将硬币抛100次,然后打印每次抛硬币的结果和头尾的总数。你知道吗
程序生成每次投掷的结果,并在100圈后停止。你知道吗
这是我一直坚持的计数。你知道吗
我的代码是:
import random
print ("Welcome to the coin toss simulator")
start = raw_input("Would you like to start: ")
if start == "y":
count = 0
while count <= 100:
outcome = random.randint(1, 2)
count +=1
if outcome == 1:
print("Heads")
else:
print("Tails")
print("You tossed: ", outcome.count(1), " Heads")
print("You tossed: ", outcome.count(2), " Tails")
input("\n\nPress the enter key to exit.")
我收到的错误消息是:
Traceback (most recent call last):
File "./coin_toss.py", line 23, in <module>
print("You tossed: ", outcome.count(1), " Heads")
AttributeError: 'int' object has no attribute 'count'
您得到的实际错误仅仅是因为
random.randint()
返回一个整数(因为那会做什么呢?)。然后,在最后的print
调用中,尝试调用这个整数的count()
方法,但是整数没有count()
方法。你知道吗我建议把头尾分开记录。例如:
您可以使用Python提供的高性能Counter数据容器:
outcome
是投币的结果。你找不到在1
中有多少1
;这没有意义。您必须将结果保存在某处,例如list
。然后可以计算其中每个数字的出现次数:相关问题 更多 >
编程相关推荐