2015-10-13 83 views
1

我想在python中製作一個程序,在這個程序中,當用戶按下回車鍵時,電腦會顯示一張隨機卡片。同一張卡不能打印兩次。到目前爲止我的代碼是:Python - 隨機卡

from random import * 

used = [] 

number = randint(1,13) 
if number == 11: 
    number = 'Jack' 
elif number == 12: 
    number = 'Queen' 
elif number == 13: 
    number = 'King' 

suit = randint(1,4) 
if suit == 1: 
    suit = 'Hearts' 
elif suit == 2: 
    suit = 'Spades' 
elif suit == 3: 
    suit = 'Diamonds' 
elif suit == 4: 
    suit = 'Clubs' 

end = False 

while end == False : 
    get = raw_input('Press enter to get a card') 
    if get == 'end': 
     end == True 
     continue 
    card = number , suit 
    for i in (used): 
     if card == i: 
      continue 
     used.append(card) 
    print card 

到目前爲止,它只在用戶每次按下回車時輸出相同的卡和程序沒有結束當用戶鍵入「結束」。任何人都可以找到錯誤嗎?

+0

好吧,你只產生一次卡。 –

+0

用戶在第53次按「Enter」時會發生什麼 –

+2

生成一個套牌會更好,使用'random.shuffle'對其進行洗牌並根據需要進行迭代。 –

回答

2

的問題是,在while循環分配

card = number, suit 

numbersuit是你進入循環前採摘一次,因此永遠不會改變。每次循環時,您需要重新分配numbersuit

此外,您正在迭代used中的卡片,但最初沒有卡片,因此循環將永遠不會執行。並且由於您添加cardused的唯一位置在for循環內,因此它永遠不會向used添加任何內容。

-1

只需將卡片選項放入while循環即可。正如摩根所說。像這樣:

from random import * 

used = [] 


end = False 

while end == False : 

    number = randint(1,13) 
    if number == 11: 
     number = 'Jack' 
    elif number == 12: 
     number = 'Queen' 
    elif number == 13: 
     number = 'King' 

    suit = randint(1,4) 
    if suit == 1: 
     suit = 'Hearts' 
    elif suit == 2: 
     suit = 'Spades' 
    elif suit == 3: 
     suit = 'Diamonds' 
    elif suit == 4: 
     suit = 'Clubs' 
    get = raw_input('Press enter to get a card') 
    if get == 'end': 
     end == True 
     continue 
    card = number , suit 
    for i in (used): 
     if card == i: 
      continue 
     used.append(card) 
    print card 
+0

這仍然允許重複:'按回車鍵以獲得卡 (9「俱樂部」) 按回車鍵以獲得卡 (8,「俱樂部」) 按回車鍵以獲得卡 (8,「俱樂部」 ) 按回車得到一張卡片 ('King','Clubs')' – Andy

2

其他人已經解釋了爲什麼你的代碼失敗。這是一種不同的方法。

就產生甲板,使用random.shuffle將它洗,並根據需要重複:

import random 

ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace'] 
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] 
deck = [rank, suit for rank in ranks for suit in suits] 
random.shuffle(deck) 

for card in deck: 
    if raw_input('Press <enter> to get a card') == '': # enter pressed 
     print card 
    else: 
     break 
else: # for loop not broken. 
    print 'all cards have been dealt'