我想創建一個存盤位置的函式,但函式中的位置變數變暗,運行時顯示:UnboundLocalError: local variable 'favPlayer2' referenced before assignment 我剛從函式開始,所以..謝謝你的幫助
def position():
if weight > 80 and height > 190:
position = 'Center'
print('Your position is: Center')
if weight > 80 and height < 190:
print('Your position is: Power Forward or Small Forward')
favPlayer = str.lower(input("Favorite player in the list (Lebron James, Jayson Tatum): "))
while favPlayer != 'lebron james' and favPlayer != 'jayson tatum':
favPlayer = str.lower(input('Please enter the name correctly: '))
if favPlayer == 'jayson tatum':
position = 'Small Forward'
print('Your position is Small Forward')
elif favPlayer == 'lebron james':
position = 'Power Forward'
print('Your position is Power Forward')
if weight < 80 and height < 190:
print('Your position is Point Guard or Shooting Guard')
favPlayer2 = str.lower(input("Favorite player in the list (Chris Paul, Klay Thompson): "))
while favPlayer2 != 'chris paul' and favPlayer2 != 'klay thompson':
favPlayer2 = str.lower(input('Please enter the name correctly: '))
if favPlayer2 == 'chris paul':
position = 'Point Guard'
print('Your position is Point Guard')
if favPlayer2 == 'klay thompson':
position = 'Shooting Guard'
print('Your position is Shooting Guard')
position()
uj5u.com熱心網友回復:
縮進一些 if 塊以確保定義了變數
您可以提供一個全域變數,或者從函式中傳遞回傳值。但是由于您并非一直都有位置,因此我將使用全域變數。
weight = int(input("Enter your weight: "))
height = int(input("Enter your height: "))
position = None
def get_position():
global position
if weight > 80 and height > 190:
position = 'Center'
print('Your position is: Center')
if weight > 80 and height < 190:
print('Your position is: Power Forward or Small Forward')
favPlayer = str.lower(input("Favorite player in the list (Lebron James, Jayson Tatum): "))
while favPlayer != 'lebron james' and favPlayer != 'jayson tatum':
favPlayer = str.lower(input('Please enter the name correctly: '))
# indented to make sure 'favPlayer' is defined before the if statement
if favPlayer == 'jayson tatum':
position = 'Small Forward'
print('Your position is Small Forward')
elif favPlayer == 'lebron james':
position = 'Power Forward'
print('Your position is Power Forward')
if weight < 80 and height < 190:
print('Your position is Point Guard or Shooting Guard')
favPlayer2 = str.lower(input("Favorite player in the list (Chris Paul, Klay Thompson): "))
while favPlayer2 != 'chris paul' and favPlayer2 != 'klay thompson':
favPlayer2 = str.lower(input('Please enter the name correctly: '))
if favPlayer2 == 'chris paul':
position = 'Point Guard'
print('Your position is Point Guard')
if favPlayer2 == 'klay thompson':
position = 'Shooting Guard'
print('Your position is Shooting Guard')
get_position()
print(position)
輸出:
Enter your weight: 10
Enter your height: 29
Your position is Point Guard or Shooting Guard
Favorite player in the list (Chris Paul, Klay Thompson): Chris Paul
Your position is Point Guard
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/468989.html
上一篇:如何檢查程式cout是否為空?
