2013-07-17 174 views
0

這個遊戲的這一點是翻轉一個硬幣100次,並記錄正面或反面。在100次翻轉結束時,程序應該打印它翻轉正面和反面的次數。當我運行程序時,程序只是打印頭,我覺得它是通過執行第一個elif子句而不是random.randint函數來完成的。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') 
+2

而不是編寫代碼從這裏開始縮進代碼... – Serial

+0

可以給出您期望的輸出示例嗎? – dansalmo

回答

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:作爲循環

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 
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') 

要計算的磁頭數,你可以有一個headstails變量來跟蹤:

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) 
+0

感謝您的幫助! – logicislaw

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 

嘗試了這一點