Python 巨蟒抛硬币
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14882530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Coin Toss
提问by YeahScience
I am VERY new to Python and I have to create a game that simulates flipping a coin and ask the user to enter the number of times that a coin should be tossed. Based on that response the program has to choose a random number that is either 0 or 1 (and decide which represents “heads” and which represents “tails”) for that specified number of times. Count the number of “heads” and the number of “tails” produced, and present the following information to the user: a list consisting of the simulated coin tosses, and a summary of the number of heads and the number of tails produced. For example, if a user enters 5, the coin toss simulation may result in [‘heads', ‘tails', ‘tails', ‘heads', ‘heads']. The program should print something like the following: “ [‘heads', ‘tails', ‘tails', ‘heads', ‘heads']
我对 Python 非常陌生,我必须创建一个模拟抛硬币的游戏,并要求用户输入应该抛硬币的次数。根据该响应,程序必须为指定的次数选择一个 0 或 1 的随机数(并决定哪个代表“正面”,哪个代表“反面”)。计算产生的“正面”和“反面”的数量,并向用户展示以下信息:由模拟抛硬币组成的列表,以及产生的正面和反面数量的汇总。例如,如果用户输入 5,则抛硬币模拟可能会导致 ['heads', 'tails', 'tails', 'heads', 'heads']。程序应该打印如下内容:“ ['heads', 'tails', 'tails', 'heads', 'heads']
This is what I have so far, and it isn't working at all...
这是我到目前为止所拥有的,它根本不起作用......
import random
def coinToss():
number = input("Number of times to flip coin: ")
recordList = []
heads = 0
tails = 0
flip = random.randint(0, 1)
if (flip == 0):
print("Heads")
recordList.append("Heads")
else:
print("Tails")
recordList.append("Tails")
print(str(recordList))
print(str(recordList.count("Heads")) + str(recordList.count("Tails")))
回答by NPE
You are nearly there:
你快到了:
1) You need to call the function:
1)您需要调用该函数:
coinToss()
2) You need to set up a loop to call random.randint()repeatedly.
2)需要设置循环random.randint()重复调用。
回答by Rushy Panchal
You need a loopto do this. I suggest a forloop:
你需要一个loop来做到这一点。我建议一个for循环:
import random
def coinToss():
number = input("Number of times to flip coin: ")
recordList = []
heads = 0
tails = 0
for amount in range(number):
flip = random.randint(0, 1)
if (flip == 0):
print("Heads")
recordList.append("Heads")
else:
print("Tails")
recordList.append("Tails")
print(str(recordList))
print(str(recordList.count("Heads")) + str(recordList.count("Tails")))
I suggest you read this on forloops.
我建议你在forloops上阅读这个。
Also, you could pass numberas a parameter to the function:
import random
def coinToss(number):
recordList, heads, tails = [], 0, 0 # multiple assignment
for i in range(number): # do this 'number' amount of times
flip = random.randint(0, 1)
if (flip == 0):
print("Heads")
recordList.append("Heads")
else:
print("Tails")
recordList.append("Tails")
print(str(recordList))
print(str(recordList.count("Heads")) + str(recordList.count("Tails")))
Then, you need to call the function in the end: coinToss().
然后,您需要在最后调用该函数:coinToss()。
回答by Aitch
I'd go with something along the lines of:
我会采用以下方式:
from random import randint
num = input('Number of times to flip coin: ')
flips = [randint(0,1) for r in range(num)]
results = []
for object in flips:
if object == 0:
results.append('Heads')
elif object == 1:
results.append('Tails')
print results
回答by John Powell
This is possibly more pythonic, although not everyone likes list comprehensions.
这可能更像 Pythonic,虽然不是每个人都喜欢列表推导式。
import random
def tossCoin(numFlips):
flips= ['Heads' if x==1 else 'Tails' for x in [random.randint(0,1) for x in range(numflips)]]
heads=sum([x=='Heads' for x in flips])
tails=numFlips-heads
回答by BallisticZer0
import random
import time
flips = 0
heads = "Heads"
tails = "Tails"
heads_and_tails = [(heads),
(tails)]
while input("Do you want to coin flip? [y|n]") == 'y':
print(random.choice(heads_and_tails))
time.sleep(.5)
flips += 1
else:
print("You flipped the coin",flips,"times")
print("Good bye")
You could try this, i have it so it asks you if you want to flip the coin then when you say no or n it tells you how many times you flipped the coin. (this is in python 3.5)
你可以试试这个,我有它,所以它会问你是否想抛硬币,然后当你说“不”或“n”时,它会告诉你抛硬币的次数。(这是在python 3.5中)
回答by Abhishek Bahukhandi
Create a list with two elements head and tail, and use choice() from random to get the coin flip result. To get the count of how many times head or tail came, append the count to a list and then use Counter(list_name) from collections. Use uin() to call
创建一个包含两个元素 head 和 tail 的列表,并从 random 中使用 choice() 来获得硬币翻转结果。要获得 head 或 tail 出现的次数,请将计数附加到列表中,然后从集合中使用 Counter(list_name) 。使用 uin() 调用
##coin flip
import random
import collections
def tos():
a=['head','tail']
return(random.choice(a))
def uin():
y=[]
x=input("how many times you want to flip the coin: ")
for i in range(int(x)):
y.append(tos())
print(collections.Counter(y))
回答by Panagiotis Ntinis
import random
def coinToss(number):
heads = 0
tails = 0
for flip in range(number):
coinFlip = random.choice([1, 2])
if coinFlip == 1:
print("Heads")
recordList.append("Heads")
else:
print("Tails")
recordList.append("Tails")
number = input("Number of times to flip coin: ")
recordList = []
if type(number) == str and len(number)>0:
coinToss(int(number))
print("Heads:", str(recordList.count("Heads")) , "Tails:",str(recordList.count("Tails")))
回答by user12736398
Instead of all that, you can do like this:
而不是所有这些,你可以这样做:
import random
options = ['Heads' , 'Tails']
number = int(input('no.of times to flip a coin : ')
for amount in range(number):
heads_or_tails = random.choice(options)
print(f" it's {heads_or_tails}")
print()
print('end')

