2017-05-09 211 views
1

內部變量我有一些麻煩我的代碼,它口口聲聲說定義功能

NameError: name 'km' is not defined 

我在函數定義此。 如果我使用選擇功能來做到這一點會更好嗎?

def userinput(): 
    while True: 
     try: 
      km = int(input("Enter the amount of kilometres you need (1 or 2)")) 
      break 
     except ValueError: 
      print ("Oops! That was no valid number. Try again...") 
    return 
userinput() 
if km >= 3: 
    userinput() 
if km <= 0: 
    userinput() 
if km == 1: 
    zone = 0.01862 
if km == 2: 
    zone = 0.02 
+1

變量僅在首次聲明的範圍內可見 – Alnitak

回答

1

嘗試以下操作:

def userinput(): 
    while True: 
     try: 
      km = int(input("Enter the amount of kilometres you need (1 or 2)")) 
      break 
     except ValueError: 
      print ("Oops! That was no valid number. Try again...") 
    return km 

km = userinput() 
if km >= 3: 
    km = userinput() 
if km <= 0: 
    km = userinput() 
if km == 1: 
    zone = 0.01862 
if km == 2: 
    zone = 0.02 

的原因是因爲參宿一說 -

變量只在它們首先聲明

範圍內可見

希望這會幫助你,Yahli。