Python keeps saying NameError: name 'name' is not defined - python

def main():
name = raw_input("What is your name?")
age = raw_input("How old are you?")
color = raw_input("What is your favorite color?")
print "Ah, so your name is %s, your quest is %s, " \
"and your favorite color is %s." % (name, age, color)
if __name__ == '__main__':
main()
I am trying to replicate the following code from Codeacademy:
name = raw_input("What is your name?")
quest = raw_input("What is your quest?")
color = raw_input("What is your favorite color?")
print "Ah, so your name is %s, your quest is %s, " \
"and your favorite color is %s." % (name, quest, color)

Print should be in the scope of the main function in order to acces its variables:
def main():
name = raw_input("What is your name?")
age = raw_input("How old are you?")
color = raw_input("What is your favorite color?")
print "Ah, so your name is %s, your quest is %s, " \
"and your favorite color is %s." % (name, age, color)
if __name__ == '__main__':
main()
This should do.

name, age, and color are all local to main. Thus, you cannot access them outside of the function.
I think the best solution here would be to indent that print line one level:
def main():
name = raw_input("What is your name?")
age = raw_input("How old are you?")
color = raw_input("What is your favorite color?")
print "Ah, so your name is %s, your quest is %s, " \
"and your favorite color is %s." % (name, age, color)
if __name__ == '__main__':
main()
Now, it is in the same scope as name, age, and color and can access them just fine.

The only time you set name is when you call the main function. The only time you call the main function is after you call the print function (because the print statement isn't part of main). Therefore, name is undefined.
If you intended to replicate the codeacademy code, you need to adjust the indentation of the print statement so that it is at the same level as the raw_input statements. This is because python uses the amount of indentation to know which block a line of code belongs to. You want the print statement to be in the same block as the input statements.
For example:
def main():
name = ...
age = ...
color = ...
print ...

Related

How do I use %s multiple times

import time
import sys
print ("Welcome to the annoying machine. Made by Bloody")
time.sleep(2)
print ("Here you will enjoy this annoying thingy.")
time.sleep(2)
print ("Have fun!")
time.sleep(2)
password = input("Enter new password:")
time.sleep(2)
print ("Your password is %s, remmeber this." % password)
name = input ("What is your name?")
time.sleep (1)
I have this and want to use %s for 2 things. How do I do this?
Pass a tuple as the argument after the % operator.
print("Your name and password are: %s, %s" % (name, password))
This is called (old) printf-style String Formatting, and it can get pretty fancy.

Regarding the string format in python, what does '[%s]' mean?

I saw a line of code:
re.compile('[%s]' % re.escape(string.punctuation))
But I have no idea about the function of [%s]
Could anyone help me please?
Thank You!
It is a string formatting syntax (which it borrows from C).
Example:
name = input("What is your name? ")
print("Hello %s, nice to meet you!" % name)
And this is what the program will look like:
What is your name? Johnny
Hello Johnny, nice to meet you!
You can also do this with string concentation...
name = input("What is your name? ")
print("Hello + name + ", nice to meet you!")
...However, the formatting is usually easier.
You can also use this with multiple strings.
name = input("What is your name? ")
age = input("How old are you? ")
gender = ("Are you a male or a female? ")
print("Is this correct?")
print("Your name is %s, you are %s years old, and you are %s." % name, age, gender)
Output:
What is your name? Johnny
How old are you? 37
Are you a male or a female? male
Is this correct?
Your name is Johnny, you are 37 years old, and you are male.
Now, please, before asking any more questions, see if they exist!

KeyError in String Formatting of Raw Input

name = raw_input("kemal ")
quest = raw_input("To learn python ")
color = raw_input("Blue i guess ")
print "Ah, so your name is {name}, your quest is {quest}, " \
"and your favorite color is {color}.".format(name, quest, color)
I can't find what's wrong with this code. Python says " KeyError: 'name' " when I run it.
You need to use named arguments to use their name in the template:
"...{name}....".format(name=name, quest=quest, color=color)
If you use positional arguments, then you need to use index in template:
"...{0}...".format(name, quest, color)
Documentation: https://docs.python.org/2/library/string.html#formatstrings
First of all you must edit your string formatting to this:
print "Ah, so your name is {}, your quest is {},"\
"and your favorite color is {}.".format(name, quest, color)
Secondly, you are using the raw_input incorrectly.
You shouldn't key in what the input is, you should ask it from the user. So the full correct code looks like this:
name = raw_input("Enter your name")
quest = raw_input("Enter your quest")
color = raw_input("Enter your color")
print "Ah, so your name is {}, your quest is {},"\
"and your favorite color is {}.".format(name, quest, color)
Key in your name, quest and color when prompted, it will print out correctly.

Passing a string variable between two functions in Python

I am having trouble passing a variable from one function to another:
def name():
first_name=input("What is your name? ")
if len(first_name)==0:
print("\nYou did not enter a name!")
return name()
else:
print("\nHello %s." % first_name)
return surname()
def surname():
last_name=input("\nCan you tell my your last name please?")
if len(last_name)==0:
print("\nYou did not enter a last name!")
return surname()
else:
print("Nice to meet you %s %s." % (first_name,last_name))
I want the last command to print the inputed first_name from def name() and last name from def surname()
I always get the error that first_name is not defined and I do not know how to import it from the first function. The error I get is:
print("Nice to meet you %s %s." % (first_name,last_name))
NameError: name 'first_name' is not defined
What am I doing wrong?
You need to pass the information in the function call:
def name():
first_name = input("What is your name? ")
if len(first_name) == 0:
print("\nYou did not enter a name!")
return name()
else:
print("\nHello %s." % first_name)
surname(first_name) # pass first_name on to the surname function
def surname(first_name): #first_name arrives here ready to be used in this function
last_name = input("\nCan you tell my your last name please?")
if len(last_name) == 0:
print("\nYou did not enter a last name!")
surname(first_name)
else:
print("Nice to meet you %s %s." % (first_name,last_name))
name()
def functionname(untypedparametername):
# do smth with untypedparametername which holds "Jim" for this example
name = "Jim"
functionname(name) # this will provide "Jim" to the function
You can see how they are used if you look at the examples in the documentation, f.e. here: https://docs.python.org/3/library/functions.html
Maybe you should read up on some of the tutorials for basics, you can find lots of them on the python main page: https://wiki.python.org/moin/BeginnersGuide
You can also use while loop to ask the names constantly until there is a valid input.
def name_find():
while True:
first_name=raw_input("What is your name? ")
if len(first_name)==0:
print("\nYou did not enter a name!")
return name_find()
else:
print("\nHello %s." % first_name)
return surname(first_name)
def surname(first_name):
while True:
last_name=raw_input("\nCan you tell me your last name please?")
if len(last_name)==0:
print("\nYou did not enter a last name!")
else:
print "Nice to meet you %s %s." % (first_name, last_name)
break

Python Modules, passing values to args

Im learning python and am currently trying to pass values from input to the args for a module I wrote but I have no idea how to start.
Can someone give me some advice?
This is the module im calling
#!/usr/bin/python
class Employee:
'Practice class'
empCount = 0
def __init__(self, salary):
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employees %d" % Employee.empCount
def displayEmployee(self):
print "Salary: ", self.salary
class Att(Employee):
'Defines attributes for Employees'
def __init__(self, Age, Name, Sex):
self.Age = Age
self.Name = Name
self.Sex = Sex
def display(self):
print "Name: ", self.Name + "\nAge: ", self.Age, "\nSex: ", self.Sex
This is the code im using to call and pass the values to the args in the above module
#!/usr/bin/python
import Employee
def Collection1():
while True:
Employee.Age = int(raw_input("How old are you? "))
if Employee.Age == str(Employee.Age):
print "You entered " + Employee.Age + " Please enter a number"
elif Employee.Age > 10:
break
elif Employee.Age > 100:
print "Please enter a sensible age"
else:
print "Please enter an age greater than 10"
return str(Employee.Age)
def Collection2():
Employee.Name = raw_input("What is your name? ")
return Employee.Name
def Collection3():
while True:
Employee.Sex = str(raw_input("Are you a man or a woman? "))
if Employee.Sex == "man":
Employee.Sex = "man"
return Employee.Sex
break
elif Employee.Sex == "woman":
Employee.Sex = "woman"
return Employee.Sex
break
else:
print "Please enter man or woman "
Attributes = Employee.Employee()
Collection1()
Collection2()
Collection3()
Attributes.displayEmployee()
Im guessing I need to take the input from the user and place it in the variables of the class. I tried that but im guessing im doing everything wrong??
Employee.Age = int(raw_input("How old are you? "))
There's no use to setting a variable in the module instead of using a local variable, and setting whatever you need to set outside the Collection1() function. Note that you are not setting the employee (object) atributes', but the module's - this is probably not what you want. Also, functions, by convention, should be named with initial lowercase.
Your inheritance model is a bit strange. Why are the employee attributes in a different (sub) class? Generally, the attributes go into the main class constructor. If you really want to use a separate class for the attributes, you shouldn't use a subclass at all in this case.
EDIT
Here's what I think you meant to do:
#!/usr/bin/python
class Employee:
def __init__(self, salary, age, name, sex):
self.salary = salary
self.age= age
self.name= name
self.sex= sex
#Employee.empCount += 1 #don't do this. you should count instances OUTSIDE
def __str__(self):
return "Employee<Name: {0}, Age: {1}, Sex: {2}, Salary: {3}>".format( self.name, self.age, self.sex, self.salary)
def getAge():
while True:
try:
s=raw_input("How old are you? ")
age = int(s)
if age > 100:
print "Please enter a sensible age"
elif age<=10:
print "Please enter an age greater than 10"
else:
return age
except ValueError:
print "You entered " + s + " Please enter a number"
def getName():
return raw_input("What is your name? ")
def getSex():
while True:
sex = str(raw_input("Are you a man or a woman? "))
if not sex in ("man", "woman"):
print "Please enter man or woman "
else:
return sex
age= getAge()
name= getName()
sex= getSex()
salary=100000
employee = Employee(salary, age, name, sex)
print employee
if you want the Employee in a different file (module), just put it there and from your main code run from Employee import Employee (the first is the module, the second is the class).

Categories