Why is name not defined?

Question:

I am trying to write inside of a excel file trying to make a new row with data but it just says name is not defined.

import openpyxl
import pandas as pd


wb = openpyxl.load_workbook("H:Grade10CsMir Hussain 12.04.00.xlsx")

sheet = wb.active

def New():
    choice = input("Would you like to add a new row?")
    if choice == 'Yes':
        Name = input("What is the name of that celebirty")
        Age = input("What is the age of the celebirty")
        Height = input('What is the height of the celebirty')
        DOB = input('What is the Date of birth of the celebirty')
    elif choice == 'No':
        exit
New()
data = [(Name,Age,Height,DOB)]

for row in data:
    sheet.append(row)

wb.save('H:Grade10CsMir Hussain 12.04.00.xlsx')

Asked By: HussainMir

||

Answers:

I think the issue is that you haven’t created the variables Name, Age, Height, and DOB before using them in your data variable. You need to create these variables and set them to the inputted values before using them in the data variable.

Answered By: YosDos

Name (and the other variables) are defined in the New function and thus are local to that scope. That means that those names are not defined outside of the function. What you should do is return those values to the caller:

def New():
    ...
    Name = ...
    Age = ...
    Height = ...
    DOB = ...
    return Name, Age, Height, DOB

Name, Age, Height, DOB = New()
Answered By: Daniel Walker

There are two problems:

  1. Name is defined as a local variable; it’s not defined after New returns.
  2. exit by itself does not exit your script, so even if choice != "Yes", New still returns and your script continues.

While you could declare New to be global, it would be far better to return the input values from the function.

def New():
    choice = input("Would you like to add a new row?")
    if choice != 'Yes':
        exit()

    Name = input("What is the name of that celebirty")
    Age = input("What is the age of the celebirty")
    Height = input('What is the height of the celebirty')
    DOB = input('What is the Date of birth of the celebirty')
    return Name, Age, Height, DOB

name, age, height, dob = New()
data = [(name, age, height, dob)]
Answered By: chepner
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.