这个游戏的这一点是将硬币翻转100次并记录头部或尾部。在100翻转结束时,程序应打印出翻转头尾的次数。程序只是在我运行时打印头,我觉得它是通过执行第一个elif子句而不是random.randint函数来实现的。
任何人都可以帮忙完成这个程序吗?
import random
print ('Coin flip game')
start = input('Press enter to flip the coin')
coin_flip = random.randint(1, 2)
heads = int(1)
tails = int(2)
heads = int(heads)
tails - int(tails)
count = 0
while coin_flip:
count += 1
if count == 100:
break
elif coin_flip == 1:
print ('Heads')
elif coin_flip == 2:
print ('Tails')
答案 0 :(得分:0)
尝试这样的事情:
import random
print("Welcome to the coin flipper!")
start = input('Press enter to flip the coin')
count = 0
while True:
coin_flip = random.randint(1,2)
count+=1
if count >100:
break
if coin_flip == 1:
print('Heads')
elif coin_flip == 2:
print("Tails")
这样循环的每次迭代,数字都会因为它在循环内部而改变
您也不需要分配以后甚至不使用的所有变量
你应该使用while True:
作为循环
答案 1 :(得分:0)
您希望如何打印还不清楚。你可以这样做:
>>> import random
>>> print [['H', 'T'][random.randint(0, 1)] for _ in range(100)]
['T', 'T', 'T', 'H', 'T', 'T', 'H', 'H', 'H', 'H', 'T', 'H', 'T', 'H', 'T', 'H', 'H',
'H', 'H', 'H', 'T', 'T', 'H', 'T', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'T', 'T',
'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H',
'H', 'H', 'T', 'H', 'T', 'H', 'T', 'H', 'H', 'H', 'T', 'T', 'T', 'H', 'H', 'H', 'T',
'H', 'H', 'T', 'T', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'T', 'T', 'T', 'H', 'T', 'T',
'H', 'H', 'H', 'H', 'T', 'H', 'H', 'H', 'T', 'T', 'T', 'H', 'H', 'H', 'T',]
或:
>>> heads = sum(random.randint(0, 1) for _ in range(100))
>>> print "heads =", heads, ' tails =', 100 - heads
heads = 46 tails = 54
答案 2 :(得分:0)
您的问题在这里:
while coin_flip: # coin_flip is set to 1 or 2
...
由于coin_flip
设置为1或2,因此您的循环将是无限的,而重要的部分是coin_flip
不会更改(您不会更新它)。
要解决此问题,您应该通过在循环中为其分配一个随机数来更新coin_flip
:
while True:
count += 1
coin_flip = random.randint(1, 2) # you need to "flip" coin inside the loop
if count == 100:
break
elif coin_flip == 1:
print ('Heads')
elif coin_flip == 2:
print ('Tails')
要计算头数,您可以使用heads
和tails
变量来跟踪:
heads = 0
tails = 0
while True:
count += 1
coin_flip = random.randint(1, 2) # you need to "flip" coin inside the loop
if count == 100:
break
elif coin_flip == 1:
print ('Heads')
heads += 1
elif coin_flip == 2:
print ('Tails')
tails += 1
print "Number of heads: %s, Number of tails: %s" % (heads, tails)
答案 3 :(得分:0)
heads,tails,=0,0
import random
for i in range(100):
a=random.randint(1,2)
if(a%2==0):
tails+=1
else:
heads+=1
print 'no. of heads in 100 flips,',heads
print 'no. of tails in 100 flips,',tails
试试这个
答案 4 :(得分:0)
我知道这是几年前的事了,但我修正了Serials的代码来计算最后的正面和反面的总数:
import random
print("Welcome to the coin flipper!")
start = input('Press enter to flip the coin')
count = 0
heads = 0
tails = 0
while True:
coin_flip = random.randint(1,2)
count+=1
if count >100:
break
if coin_flip == 1:
print('Heads')
heads += 1
elif coin_flip == 2:
print("Tails")
tails += 1
print(f'''
Number of tails: {tails}
Number of times heads {heads}
''')