我在Python3.3中写了一个程序,询问你想要多少张牌,然后从牌组中随机打印出这些牌。此外,你不能两次获得同一张卡。
所以我将变量y
设置为您想要的卡数。但我有一个问题。如果我试图打印52张卡片,它会给我以下错误:
Traceback (most recent call last):
File "C:\Users\Ali\Documents\Python\Suits2.py", line 28, in <module>
randomnumber = random.randint(0,52-t)
File "C:\Python33\lib\random.py", line 213, in randint
return self.randrange(a, b+1)
File "C:\Python33\lib\random.py", line 191, in randrange
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0,0, 0)
此错误是什么以及如何修复我的代码(如下所示)?
另外,我怎么能轻易地缩短它(我不擅长编程,除了我已经知道的东西之外什么都没有(在代码中)?
代码:
import random
t = 1
u = 0
v = 0
w = 0
x = 0
y = int(input("Please enter how many cards you want: "))
z = y
card = [""]
card2 = [""]
clubs = ["Clubs"]
hearts = ["Hearts"]
diamonds = ["Diamonds"]
spades = ["Spades"]
cards =["Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"]
while w<52:
card.append("")
card2.append("")
w+=1
while x<52:
card[x] = cards[u]+" of Clubs"
card[x+1] = cards[u]+" of Hearts"
card[x+2] = cards[u]+" of Diamonds"
card[x+3] = cards[u]+" of Spades"
x+=4
u+=1
while z>=0:
randomnumber = random.randint(0,52-t)
card2[y-z] = card[randomnumber]
card.remove(card[randomnumber])
z-=1
t+=1
while y>=1:
print(card2[y])
y-=1
答案 0 :(得分:0)
错误意味着你的random.randint()正在调用一个范围,其中stop是&lt;开始。所以如果我说random.randint(3,1),它会抛出这个异常。确保你的52-t永远不会低于0。
编码风格的额外提示: 将所有内容包含在main()函数中是正常的,如下所示:
def main():
#Your code here
然后像这样称呼它:
if __name__ == "__main__":
main()
其他建议:
只要我有时间,我就会以此为例编写此代码的改进版本。
这是我的版本(我认为)更“pythonic”:
#!/usr/bin/env python3
import random
def main():
suits = ["Clubs", "Hearts", "Diamonds", "Spades"]
ranks = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King']
numberOfCardsToGenerate = int(input("Please enter how many cards you want: "))
cards = []
for suit in suits:
for rank in ranks:
cards.append(rank + " of " + suit)
for i in range(numberOfCardsToGenerate):
chosenCard = random.choice(cards)
print(chosenCard)
cards.remove(chosenCard)
if __name__ == "__main__":
main()
随意询问是否有任何不明之处!
答案 1 :(得分:0)
您应该确保范围始终是有效范围。此外,当您打印正在打印1到51的值时,使用以下代码从0到51打印。
import random
t = 1
u = 0
v = 0
w = 0
x = 0
y = int(input("Please enter how many cards you want: "))
z = y
card = [""]
card2 = [""]
clubs = ["Clubs"]
hearts = ["Hearts"]
diamonds = ["Diamonds"]
spades = ["Spades"]
cards =["Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"]
while w<52:
card.append("")
card2.append("")
w+=1
while x<52:
card[x] = cards[u]+" of Clubs"
card[x+1] = cards[u]+" of Hearts"
card[x+2] = cards[u]+" of Diamonds"
card[x+3] = cards[u]+" of Spades"
x+=4
u+=1
while z>0:
randomnumber = random.randint(0,52-t)
card2[y-z] = card[randomnumber]
card.remove(card[randomnumber])
z-=1
t+=1
while y>=0:
print(card2[y])
y-=1
不是写很多东西,你可以尝试巧妙地追加:
u = v = w = x = 0
类似地,
card2 = card = ["" for x in range(52)]
一些小的建议,当你可以像这样用for循环替换while循环时,你可以避免额外的行:
for i in range(52):
print(card2[i])