2013-04-03 31 views
1

我知道類似的問題已經被問到,但請耐心等待。我正在幫助我的年輕表弟創建一個蟒蛇項目,在這個項目中,一枚硬幣翻轉了1000次,「玩家」可以猜測頭上出現了多少次。然後她想要檢查猜測是否在頭部出現次數的10次以內,並按照(你是(回答 - 猜測))還是(僅僅做得好(回答 - 猜測))。我習慣於使用UNIX,python似乎以一種完全不同的方式進行項目。這是代碼可能使用範圍以某種方式來檢查猜測是否在範圍內?如何檢查一個值是否在10以內使用python

#Guess how many times heads will occur when a coin is flipped 1000 time 
import random 
import time 

print('I will flip a coin 1000 times. Guess how many times it will come up heads.  (Press enter to begin)') 
int(guess) = input() 
flips = 0 
heads = 0 
while flips < 1000: 
    if random.randint(0, 1) == 1: 
     heads = heads + 1 
    flips = flips + 1 

    if flips == 900: 
     print('900 flips and there have been ' + str(heads) + ' heads.') 
     time.sleep(5) 
    if flips == 100: 
     print('At 100 tosses, heads has come up ' + str(heads) + ' times so far.') 
     time.sleep(2) 
    if flips == 500: 
     print('Half way done, and heads has come up ' + str(heads) + ' times.') 
     time.sleep(2) 

print() 
print('Out of 1000 coin tosses, heads came up ' + str(heads) + ' times!') 
time.sleep(2) 
print('Were you close?') 
int(answer) = input() 
+0

只是檢查,如果這兩個值之間的差值的絕對值小於10 – ApproachingDarknessFish

回答

5
if heads - 10 <= int(guess) <= heads + 10: 

或者

if abs(heads - int(guess)) <= 10: 
+0

謝謝您應發電子郵件直線距離不過我必須說,我不不懂2線(whats「abs」)? – user2239009

+0

abs()返回一個數字的絕對值(http://docs.python.org/2/library/functions.html#abs) – gonz

相關問題