以下代碼是用於猜數字遊戲。它沒有錯誤但沒有輸出。我怎樣才能進一步改進代碼?爲什麼這個號碼猜測程序不能通過這條線?
它一直工作到這條線print("Your Number has been Generated,Enter your guess Below")
,但沒有給出任何輸出。
#Guess the number
from random import randint
print("Welcome to Guess the Number Game:")
print("Press 'g' to Generate Number between 0 and 100:")
cmd=input("->")
if cmd=='g':
num=randint(0,100)
else:
print("Unknown Input")
def chk(x):
if int(x)==True:
chk=True
else:
chk=False
def diff(x,y):
diff=(x-y)
return diff
print("Your Number has been Generated,Enter your guess Below")
guess=input("->")
chk(guess)
while chk==True:
diff(num,guess)
if diff==0:
print("Congrats! correct Guess")
elif diff>10:
print("Oh! too high")
elif diff<5 and diff>0:
print("very close!Better Luck Next time")
else:
diff<0
print("Sorry!too Low")
你是對的,我用def chk(x)來檢查輸入是否是數字,我會記住縮進規則。感謝您的幫助 –
我在chk(x)中想的是,如果輸入是非數字的任何東西,即如果一個字符串,那麼int(字符串)將不可能,因此條件int(x)== true將假,現在我明白了。感謝您的洞察 –
@RohanDwivedi究竟發生了什麼,會拋出異常。 – Pureferret