我正在使用Python,我正在嘗試編寫一個模擬岩石,紙張,剪刀遊戲的簡單程序。除了當我輸入一個無效的回覆(除岩石,紙張或剪刀以外的東西)時,一切都可以正常工作。Python岩石,紙,剪刀遊戲
Traceback (most recent call last):
File "C:/Users/home/Desktop/BAGARDNER/Python/rock_pape_scissors.py", line 88, in <module>
main()
File "C:/Users/home/Desktop/BAGARDNER/Python/rock_pape_scissors.py", line 14, in main
number = user_guess()
File "C:/Users/home/Desktop/BAGARDNER/Python/rock_pape_scissors.py", line 48, in user_guess
return number
UnboundLocalError: local variable 'number' referenced before assignment
我明白,這是告訴我,號碼不被引用,但是從我瞭解的代碼,它不應該需要一個號碼時限定符是假的。
#import random module
import random
#main function
def main():
#intro message
print("Let's play 'Rock, Paper, Scissors'!")
#call the user's guess function
number = user_guess()
#call the computer's number function
num = computer_number()
#call the results function
results(num, number)
#computer_number function
def computer_number():
#get a random number in the range of 1 through 3
num = random.randrange(1,4)
#if/elif statement
if num == 1:
print("Computer chooses rock")
elif num == 2:
print("Computer chooses paper")
elif num == 3:
print("Computer chooses scissors")
#return the number
return num
#user_guess function
def user_guess():
#get the user's guess
guess = input("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
#while guess == 'paper' or guess == 'rock' or guess == 'scissors':
if is_valid_guess(guess):
#if/elif statement
#assign 1 to rock
if guess == 'rock':
number = 1
#assign 2 to paper
elif guess == 'paper':
number = 2
#assign 3 to scissors
elif guess == 'scissors':
number = 3
return number
else:
print('That response is invalid.')
user_guess()
def is_valid_guess(guess):
if guess == 'rock' or 'paper' or 'scissors':
status = True
else:
status = False
return status
def restart():
answer = input("Would you like to play again? Enter 'y' for yes or \
'n' for no: ")
#if/elif statement
if answer == 'y':
main()
elif answer == 'n':
print("Goodbye!")
else:
print("Please enter only 'y' or 'n'!")
#call restart
restart()
#results function
def results(num, number):
#find the difference in the two numbers
difference = num - number
#if/elif statement
if difference == 0:
print("TIE!")
#call restart
restart()
elif difference % 3 == 1:
print("I'm sorry! You lost :(")
#call restart
restart()
elif difference % 3 == 2:
print("Congratulations! You won :)")
#call restart
restart()
main()
謝謝你的幫忙!
謝謝你的快速反應。這已經解決了我最初的問題。但是,現在我得到一個新的錯誤。回傳(最近呼叫最後): 文件「C:/Users/home/Desktop/BAGARDNER/Python/rock_paper_scissors.py」,第84行,在 main() 文件「 C:/Users/home/Desktop/BAGARDNER/Python/rock_paper_scissors.py「,第18行,在主 結果(編號,編號) 文件」C:/Users/home/Desktop/BAGARDNER/Python/rock_paper_scissors.py「 ,第70行,結果爲 difference = num - number TypeError:不支持的操作數類型爲 - :'int'和'NoneType' –
這發生在我以其他方式「修復」它之前。 –
@BryceGardner這是因爲'user_guess'中的一個錯誤。當發現無效響應時,再次調用'user_guess()',但不返回結果。因此,無論何時你最終輸入一個合法的猜測,這個結果都會被丟棄,'user_guess'返回'None'直到'main'函數。只需將'user_guess'的最後一行更改爲'return user_guess()'。 –