我正在制作一个基本的硬币鳍状肢,出于某种原因,它总是在翻动heads
。
import random
def flip():
flip = random.randint(1,100)
if flip >= 48 & flip < 98:
print('heads')
elif flip <= 48:
print('tails')
else:
print('Whoa it landed on its side')
flip()
请帮助
在python中,&
是一个按位运算符,使用and
代替。
import random
def flip():
flip = random.randint(1,100)
if flip >= 48 and flip < 98:
print('heads')
elif flip <= 48:
print('tails')
else:
print('Whoa it landed on its side')
for _ in range(200):
flip()
您可以大量简化代码。
让我们从简单的版本开始:
import random
def flip():
"""Simulate the flip of a coin"""
coin_flip = random.randint(1,100)
# print('>> coin_flip = %s' % coin_flip) # uncomment if you want debug
print('Heads') if coin_flip % 2 == 0 else print('Tails')
结果是基于考虑50%概率的另一种方式:奇数和平均数。更容易管理。 coin_flip % 2
将随机数除以2并返回其余数字。如果== 0比数字是偶数。否则很奇怪。
这里使用的if只是更加扩展的紧凑版本
if coin_flip % 2 == 0:
print('Heads')
else:
print('Tails')
我们来介绍一下side effect
。我们可以使用参数来介绍它。
import random
def flip(side_effect=0):
"""Simulate the flip of a coin
:type side_effect: int
:param side_effect: The percentage for the side effect.
E.g. `1` means 1% of probability to get the coin landed on its side
"""
coin_flip = random.randint(1,100)
# print('>> coin_flip = %s' % coin_flip) # just for debug
if coin_flip <= side_effect:
print('Whoa it landed on its side')
return # end the program
print('Heads') if coin_flip % 2 == 0 else print('Tails')
此版本的函数添加了side_effect
参数,您可以根据需要更改名称。默认值为0表示未启用,但您可以尝试使用flip(side_effect=100)
运行该功能,这意味着所有翻盖都将在其侧面着陆。
玩得开心