import random
level = input("Easy gets 10 attempt Hard getse 5 attempt choose a level --> ").lower()
number = random.choice(range(101))
attempt = 0
if level == "easy":
attempt = 10
else:
attempt = 5
def check_number(guess,num):
if guess == num:
return "Correct You Won :)"
win = True
elif guess > num:
return "Too high :("
elif guess < num:
return "Too low :("
win = False
while attempt > 0 and win == False:
guess = int(input("Guess the number "))
print(check_number(guess,number))
attempt -= 1
print(f"You have {attempt} attempt left")
if win == True:
print(f"GOOD JOB YOU HAVE {attempt} LEFT")
else:
print("NEXT T?ME :(")
當您猜到數字時它不會停止,仍然要求重新猜測。我找不到問題所在。我剛開始學習python。
uj5u.com熱心網友回復:
這完全避免了使用全域變數:
import random
level = input("Easy gets 10 attempt Hard getse 5 attempt choose a level --> ").lower()
number = random.choice(range(101))
attempt = 0
if level == "easy":
attempt = 10
else:
attempt = 5
def check_number(guess,num):
if guess > num:
return False, "Too high :("
elif guess < num:
return False, "Too low :("
return True, "Correct You Won :)"
win = False
while attempt > 0 and not win:
guess = int(input("Guess the number "))
win, msg = check_number(guess,number)
print(msg)
if not win:
attempt -= 1
print(f"You have {attempt} attempt left")
if win:
print(f"GOOD JOB YOU HAVE {attempt} LEFT")
else:
print("NEXT T?ME :(")
uj5u.com熱心網友回復:
您的代碼有兩個問題:
win回傳后分配,它不會運行win在函式內部,就像您win在函式內部定義一個新變數一樣,無法從外部訪問它
所以你可能想要這樣做:
import random
level = input("Easy gets 10 attempt Hard getse 5 attempt choose a level --> ").lower()
number = random.choice(range(101))
attempt = 0
if level == "easy":
attempt = 10
else:
attempt = 5
def check_number(guess,num):
if guess == num:
return 0
elif guess > num:
return 1
elif guess < num:
return -1
win = False
while attempt > 0 and win == False:
guess = int(input("Guess the number "))
state = check_number(guess,number)
if(state==0):
win = True
print("won")
elif(state==1):
print("is high")
elif(state==-1):
print("is low")
attempt -= 1
print(f"You have {attempt} attempt left")
if win == True:
print(f"GOOD JOB YOU HAVE {attempt} LEFT")
else:
print("NEXT T?ME :(")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/397239.html
上一篇:函式回傳第一個索引滿足條件
