我的代码中出现名称错误

时间:2017-04-02 12:00:45

标签: python

嘿,我有一个非常简单的问题,但是我希望修复它的所有地方似乎都不起作用。所以对于学校我们必须做这件事我们将用户输入保存到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()

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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()

你应该修理它。

可选修复:

<form action="post.php">
  First name:<br>
  <input type="text" name="item" value="the item that you buy"><br>
  Last name:<br>
  <input type="text" name="adress" value="your adress"><br><br>
  <input type="submit" value="Submit">
</form>