2017-04-02 60 views
-1

嘿,我有一個非常簡單的問題,但是我希望修復它的所有地方似乎都不起作用。所以對於學校我們必須做到這一點,我們將用戶輸入保存到excel文件中,並在其中執行Mylist.append(電話)時出現錯誤,說明電話未定義。任何想法如何解決這個問題?我的代碼中的名稱錯誤

#Zacharriah Task 3 
import csv 
from IPhone import* 
from Android import* 
import time 

def start(): 
    print('Hello Welcome to the Phone Trouble-Shooter') 
    time.sleep(2) 
    phone = input('Please input what brand of phone you have') 
    if "iphone" in phone: 
     print('Your phone has been identified as an Iphone') 
    elif "android" in phone: 
     print('Your phone has been identifies as an Android') 


file = open("Excel_Task_3.csv", "w", newline = "") 
fileWrite = csv.writer(file,delimiter = ",") 
Mylist = [] 

Mylist.append(phone) 

fileWriter.writerow(Mylist) 

file.close() 

回答

1

如果代碼與發佈完全相同,那麼phone確實沒有在您需要的地方定義。它在功能的範圍定義,但在室外使用 - 所以定義有沒有phone變量:

def start(): 
    # defined in the function's scope 
    phone = input('Please input what brand of phone you have') 
    # rest of code 


file = open("Excel_Task_3.csv", "w", newline = "") 
fileWrite = csv.writer(file,delimiter = ",") 
Mylist = [] 
# Used outside of the function's scope - it is unrecognized here 
Mylist.append(phone) 

你可以做的是從start返回一個值,然後使用它。喜歡的東西:

def start(): 
    phone = input('Please input what brand of phone you have') 
    # rest of code 
    return phone 

# rest of code 
Mylist = [] 
Mylist.append(start()) 

Short Description of Python Scoping Rules

+0

所以修復做我把高清手機下DEF開始? –

+0

查看更新。基本上你必須確保變量存在於你想要使用的範圍內。 –

+0

噢,謝謝它的工作:) –

0

phone不是start()功能之外定義。

這裏:Mylist.append(phone)

你應該修復它。

可選的解決辦法:

def start(): 
    print('Hello Welcome to the Phone Trouble-Shooter') 
    time.sleep(2) 
    phone = input('Please input what brand of phone you have') 
    if "iphone" in phone: 
     print('Your phone has been identified as an Iphone') 
    elif "android" in phone: 
     print('Your phone has been identifies as an Android') 
    return phone # Add this. 


file = open("Excel_Task_3.csv", "w", newline = "") 
fileWrite = csv.writer(file,delimiter = ",") 
Mylist = [] 
phone = start() # Add this. 
Mylist.append(phone) 

fileWriter.writerow(Mylist) 

file.close() 
+0

你只需要確保從你聲明的開始函數返回手機。 – nivhanin

+0

當你首先調用'start()'函數時,也一定要使用返回值(電話)。 – nivhanin