[英]Python Random Generator
Basically i need some quick help. 基本上我需要一些快速帮助。 I'm making a program where I am using two random generators to generate numbers.
我正在编写一个程序,其中使用两个随机生成器来生成数字。
What the outcome of the generators should come to is the first generator generated a number 8 and the second generator generated the number 17. I then want it to translate this to read: "8 of Diamonds". 生成器的结果应该是第一个生成器生成数字8,第二个生成器生成数字17。然后,我希望它将其翻译为:“ 8颗钻石”。
Here is my code so far: 到目前为止,这是我的代码:
import random
Player1 = input("Enter Name Of Player1")
Card = random.randint(2, 14)
Suit = random.randint(15,18)
if Card == 11:
print("Jack")
elif Card == 12:
print("Queen")
elif Card == 13:
print("King")
elif Card == 14:
print("Ace")
else:
print(Card)
Try the following, using random.choice()
and string formats : 使用
random.choice()
和字符串格式尝试以下操作:
import random
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
numbers = [
'2', '3', '4', '5', '6', '7', '8', '9', '10',
'Jack', 'Queen', 'King', 'Ace']
print('{number} of {suit}'.format(
number=random.choice(numbers),
suit=random.choice(suits)))
>> Ace of Hearts
You could use some range
function to generate the numbers, but in this particular case, you can probably get away with hardcoding it. 您可以使用一些
range
函数来生成数字,但是在这种特殊情况下,您可以避免对其进行硬编码。 Note that strings are probably the better option as well because you're mixing that with 'Jack', 'Queen', 'King', and 'Ace'
. 请注意,字符串可能也是更好的选择,因为您将其与
'Jack', 'Queen', 'King', and 'Ace'
。
Another solution: 另一个解决方案:
import random
Player1 = raw_input("Enter Name Of Player1")
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
numbers = {2:'2', 3:'3', 4:'4', 5:'5', 6:'6', 7:'7', 8:'8', 9:'9', 10:'10', 11:'Jack', 12:'Queen', 13:'King', 14:'Ace'}
Card = random.randint(2, 14)
Suit = random.randint(0, 3)
print '{0} of {1}'.format(numbers[Card], suits[Suit])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.