我試圖讓我的猜數游戲正常作業,但我明白了,但當我將猜測輸入作為函式時,我只是不明白為什么它不起作用。這是不起作用的原始代碼
import random
targetMin = int(input("Enter your range's minimum number: "))
targetMax = int(input("Enter your range's maximum number: "))
targetNum = int(random.randint(targetMin, targetMax))
def takeGuess():
guess = int(input("Enter your guess: "))
return guess
def startGame():
guess = 0
while guess != targetNum:
takeGuess()
if guess > targetNum:
print("You guessed too high, guess again!")
elif guess < targetNum:
print("You guessed too low, guess again!")
elif guess == targetNum:
print("You win the game!")
break
startGame()
當我用猜測輸入代碼替換函式時takeGuess,該代碼完美運行。startGame
它在這里作業,但我很困惑為什么我的第一個版本不起作用。我做了一些研究,這可能是一個回傳問題,但我只是無法弄清楚語法。對不起。
import random
targetMin = int(input("Enter your range's minimum number: "))
targetMax = int(input("Enter your range's maximum number: "))
targetNum = int(random.randint(targetMin, targetMax))
def startGame():
guess = 0
while guess != targetNum:
guess = int(input("Enter your guess: "))
if guess > targetNum:
print("You guessed too high, guess again!")
elif guess < targetNum:
print("You guessed too low, guess again!")
elif guess == targetNum:
print("You win the game!")
break
startGame()
uj5u.com熱心網友回復:
您正在呼叫takeGuess(),并且takeGuess()正在回傳一個值,但您沒有對結果做任何事情。為了使其作業,您需要將結果存盤takeGuess()在guess. 像這樣:
import random
targetMin = int(input("Enter your range's minimum number: "))
targetMax = int(input("Enter your range's maximum number: "))
targetNum = int(random.randint(targetMin, targetMax))
def takeGuess():
guess = int(input("Enter your guess: "))
return guess
def startGame():
guess = 0
while guess != targetNum:
guess = takeGuess()
if guess > targetNum:
print("You guessed too high, guess again!")
elif guess < targetNum:
print("You guessed too low, guess again!")
elif guess == targetNum:
print("You win the game!")
break
startGame()
僅僅因為您回傳一個變數并不意味著呼叫者將能夠訪問它。我認為這就是讓你失望的原因。為簡單起見,您的takeGuess()函式可以重寫為:
def takeGuess():
return int(input("Enter your guess: "))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/528276.html
標籤:Python功能
上一篇:在mydict[變數]中使用函式。KeyError:<functionmyfunctionat0x7f6b65a0f7f0>
