我需要为python折腾问题添加到我的python代码中?

问题描述 投票:-2回答:1

编写一个名为coinToss的函数,模拟投掷硬币。当您调用该函数时,它应该生成1到2范围内的随机数。如果随机数为1,则该函数应显示“head”。如果随机数为2,则该函数应显示“tails”。在一个程序中演示该功能,该程序询问用户掷硬币的次数,然后模拟硬币抛掷次数。

import random #this imports random

flips = int(input("How many coin flips? ")) #this asks user how many coin flips to use

def tossCoin(flips): #this defines the function tossCoin
    result = random.randint(1,2) #this assigns a random number for the flip
    for amount in range(flips):
        if (result == 1): 
            return("Heads")
        else: 
            if(result == 2): 
                return("Tails")

print(tossCoin(flips)) #this prints tossCoin
python
1个回答
0
投票

返回"Heads""Tails"在第一次迭代期间停止for循环。

print("Heads")

print("Tails")

应该用来代替。

该行应位于for循环内,以便为每次翻转生成一个随机数。

result = random.randint(1,2)
© www.soinside.com 2019 - 2024. All rights reserved.