2017-04-02 39 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