我正在尝试在python中创建一个程序,当用户按下enter键时,计算机会显示一张随机卡。同一张卡不能打印两次。到目前为止我的代码是:
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
到目前为止,每次用户按下Enter键时,它只输出相同的卡片,当用户输入“结束”时,程序不会结束。任何人都可以找到错误吗?
答案 0 :(得分:2)
问题是你在while循环中分配
card = number, suit
但是number
和suit
在您进入循环之前被选中了一次,因此永远不会改变。每次循环时都需要重新分配number
和suit
。
此外,您正在迭代used
中的卡片,但最初没有卡片,因此循环将永远不会执行。由于card
used
添加到for
的唯一位置位于used
循环内,因此永远不会向Spree::Order.complete.where(
Spree::Order.arel_table[:completed_at].gteq(
Date.new(2015, 10, 1)
)
).joins(
line_items: :variant
).select(:sku).distinct.pluck(:sku)
添加任何内容。
答案 1 :(得分: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'
答案 2 :(得分:-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