-1

Hey I've got a very simple problem, however all the places i look to fix it don't seem to work. So for school we gotta do this thing where we save user input to an excel file and where i do Mylist.append(phone) i get an error saying phone is not defined. Any idea on how to fix this?

#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()
Z.Howells
  • 9
  • 4

2 Answers2

1

If code is exactly like posted then phone is really not defined where you need it. It is defined in the function's scope but is used outside - so there is no phone variable defined there:

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)

What you can do is return a value from start and then use it. Something like:

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

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

Read Short Description of Python Scoping Rules

Community
  • 1
  • 1
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
0

phone not defined outside the start() function.

Here: Mylist.append(phone)

You should fix it.

Optional fix:

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()
nivhanin
  • 1,688
  • 3
  • 19
  • 31