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:\Grade10\Cs\Mir 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:\Grade10\Cs\Mir Hussain 12.04.00.xlsx')
>Solution :
There are two problems:
Nameis defined as a local variable; it’s not defined afterNewreturns.exitby itself does not exit your script, so even ifchoice != "Yes",Newstill 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)]