홈>
기본 코인 플리퍼를 만들고 있는데 어떤 이유로 든 항상
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()
pls 도움
- 답변 # 1
- 답변 # 2
코드를 많이 단순화 할 수 있습니다.
간단한 버전으로 시작합시다 :
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 % 확률을 고려하는 다른 방법 인 홀수 및 짝수를 기반으로합니다. 훨씬 쉽게 관리 할 수 있습니다. 와이즈 비즈 2의 난수를 나누고 나머지를 반환합니다. == 0이면 숫자보다 짝수입니다. 그렇지 않으면 이상합니다.
여기에 사용 된 경우 더 확장 된 것의 컴팩트 한 버전 일뿐입니다
coin_flip % 2
와이즈 비즈를 소개하자 . 매개 변수를 사용하여 소개 할 수 있습니다.
이 버전의 함수는if coin_flip % 2 == 0: print('Heads') else: print('Tails')
side effect
를 추가합니다. 매개 변수를 사용하여 원하는대로 이름을 변경할 수 있습니다. 기본값은 0으로 설정되어 있지는 않지만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
파이썬,
&
에서 비트 연산자입니다.and
를 사용하십시오. 대신