我正在創建一個'猜數字'遊戲,並且在嘗試運行它時遇到問題。我得到的錯誤是如下:在Python中使用def函數時出現NameError
Traceback (most recent call last):
File "C:\Users\Troy\Desktop\guess.py", line 10, in
begin()
File "C:\Users\Troy\Desktop\guess.py", line 9, in begin
ask()
NameError: name 'ask' is not defined
在不同的「塊」我已經在定義腳本,那就是:
)這裏被定義爲開始(第一部分認爲的一個數字,並詢問告訴它被1和10
def begin():
import random
import sys
guessesRemaining = 3
randomNumber = random.randint(1,10)
print("I am thinking of a number between 1 and 10.")
ask()
begin()
思維之間的數的下一部分被定義爲詢問用戶(),並要求用戶輸入他們猜測的數字,只要他們有足夠的猜測。
def ask():
if guessesRemaining == 0:
print("Oh no! You've run out of guesses! I was thinking of the number " + str(randomNumber) + ".")
else:
print ("Take a guess.")
guess = input(">> ")
if int(guess) < randomNumber:
print("Your number is too small!")
global guessesRemaining
guessesRemaining -= int(1)
ask()
elif int(guess) > randomNumber:
print("Your number is too big!")
global guessesRemaining
guessesRemaining -= int(1)
ask()
elif int(guess) == randomNumber:
print("Well done! You got the right number!")
playAgain()
ask()
這最後一部分被定義爲playAgain(),它會詢問用戶是否要再次播放。
def playAgain():
print("Would you like to play again?")
again = input
if again == y or Y or yes or Yes:
print("Restarting game...")
begin()
if again == n or N or no or No:
print("Quitting game...")
sys.quit()
else:
print("Invalid response!")
playAgain()
playAgain()