KeyError in String Formatting of Raw Input - python

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.

Related

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!

Importing Variables from other functions

I've tried searching and trying suggestions people made for others but its not working for me, here is my code:
def CreateAccount():
FirstName = input('What is your first name?: ')
SecondName = input('What is your second name?: ')
Age = input('How old are you?: ')
AreaLive = input("What area do you live in?: ")
return FirstName, SecondName, Age, AreaLive
def DisplayAccountInfo(FirstName,SecondName,Age,AreaLive):
print("Your Firstname is",FirstName)
print("Your Secondname is",SecondName)
print("You are",Age," years old")
print("You live in the",AreaLive," area")
return
def ConfirmAccountF():
ConfirmAccount = input("Do you have an account? y,n; ")
if ConfirmAccount == "n":
CreateAccount()
else: #ConfirmAccount -- 'y'
DisplayAccountInfo()
while True:
ConfirmAccountF()
So its just supposed to run indefinitely for now, but what I want it to do is pass the variables from 'CreateAccount' into 'DisplayAccountInfo'.
When I press anything other than n for 'ConfirmAccount' I get that the variables are undefined.
If I set it manually in 'DisplayAccountInfo()' then it doesn't throw any errors.
This is just me messing about and trying to understand python, if anyone can help that would be great.
Use the unpacking operator, *:
DisplayAccountInfo(*CreateAccount())
What this does is takes the tuple of four strings returned by CreateAccount and converts them into four arguments to be passed as separate parameters to DisplayAccountInfo. Whereas if you omitted the * operator and just called DisplayAccountInfo(CreateAccount()), that would pass a single tuple argument to DisplayAccountInfo, resulting in a TypeError exception (because DisplayAccountInfo expects four arguments, not one).
Of course if you also need to save the strings returned from CreateAccount for later use, you'll need to do that in between calling CreateAccount and DisplayAccountInfo.
The variable you declared on CreateAccount() can't be accesed by its name from the outside. To pass the information to another function you need to store its values first:
first_name, second_name, age, area = "", "", "", ""
def ConfirmAccountF():
ConfirmAccount = input("Do you have an account? y,n; ")
if ConfirmAccount == "n":
first_name, second_name, age, area = CreateAccount()
else: #ConfirmAccount -- 'y'
DisplayAccountInfo(first_name, second_name, age, area)

Alphabet check as input

Hi I just start learning python today and get to apply what I learning on a flash cards program, I want to ask the user for their name, and only accept alphabet without numbers or symbols, I've tried several ways but there is something I am missing in my attempts. Here is what I did so far.
yname = raw_input('Your Name ?: ')
if yname.isdigit():
print ('{0}, can\'t be your name!'.format(yname))
print "Please use alphbetic characters only!."
yname = raw_input("Enter your name:?")
print "Welcome %s !" %yname
but I figured in this one is if the user input any character more than one time it will eventually continue...So I did this instead.
yname = raw_input("EnterName").isalpha()
while yname == True:
if yname == yname.isalpha():
print "Welcome %s " %(yname)
else:
if yname == yname.isdigit():
print ("Name must be alphabetical only!")
yname = raw_input('Enter Name:').isalpha()
This while loop goes on forever, as well as I tried (-) and (+) the raw input variable as I've seen in some tutorials. So I thought of using while loop.
name = raw_input("your name"):
while True:
if name > 0 and name.isalpha():
print "Hi %s " %name
elif name < 0 and name.isdigit():
print "Name must be Alphabet characters only!"
try:
name != name.isalpha():
except (ValueError):
print "Something went wrong"
This will check for both alphabet in the raw_input and check for the length of the name as I see you tried to do in your last try.
import string
import re
name = re.compile(r'[a-zA-Z]+') #This will check for alphabet.
yname = raw_input("Your Name:") #ask the user for input.
while not name.match(yname):
print "invalid characters"
yname = raw_input("Your Name:")
if 5<=len(yname)<=10:
print "Hi,", yname, "!"
elif len(yname)>10:
print "too long!"
elif len(yname)<5:
print "too short!"
You can rearrange your last attempt a bit to get what you want:
while True:
name = raw_input("your name") # ask inside the loop
if name and name.isalpha():
print "Hi %s " %name
break # leave the loop if done
elif name and name.isdigit():
print "Name must be Alphabet characters only!"
else:
print "Please enter something"
Note that if name will be True if name != "".
name = raw_input('Enter your name: ')
while not name.isalpha():
print 'Invaid characters in name'
name = raw_input('Enter your name: ')
Use regexes:
import re
regex = re.compile("^[a-zA-Z]+$")
valid_name = False
while not valid_name:
user_name = raw_input("EnterName")
if not regex.search(user_name):
print "this can't be your name"
else:
print "Hi there, {0}".format(user_name)
valid_name = True
Also, please take note that programmers often make false assumptions about human names
Edit: as an alternative you can skip compiling a regex and just use the pattern in place:
if not re.search("^[a-zA-Z]+$", user_name):
...
However, since you're doing it in a loop compiled version would have slightly better performance, since re.search actually compiles a regex behind the scenes each time invoked.
Also, please note I've changed match to search and slightly modified a regex since there're some differences and it appears tome me that search suits your situation more.

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

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 ...

Saving Raw_input to a list when used in a While Loop

I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on this code for 2weeks now and I have tunnel vision and cannot work it out:
Basically our assignment was to get to grips with Object-Oriented Programming. We unfortunately have to use "get" and "set" which I've learnt a lot of people dislike, however, as per our tutor we have to do it like that. We were told tp create a program whereby the user is presented with a screen with 3 options. 1. adding a student. 2. viewing a student and 3. removing a student.. within my AddStudent function I have to ask the user to enter fname Lname age degree studying id number (these are the easy bits) and also module name and grade for each module, I have managed to create a loop whereby it will ask the user over and over to enter modules and corresponding grades and will break from said loop when the user enters -1 into the modulname field. However, when trying saving it to a list named students[] ... (which is at the very top of my code above all functions, to apparently make it global) it saves all input from the user re: age name etc but when it comes to saving module names and grades it only saves the last input and not the multiple inputs I need it to. I am unsure if it is within my AddStudent function where it isn't saving or within my ViewStudent function: Both are below (remember I HAVE to use the GET and SET malarky) ;)
students[] # Global List
def addStudent():
print
print "Adding student..."
student = Student()
firstName = raw_input("Please enter the student's first name: ")
lastName = raw_input("Please enter the student's last name: ")
degree = raw_input("Please enter the name of the degree the student is studying: ")
studentid = raw_input("Please enter the students ID number: ")
age = raw_input("Please enter the students Age: ")
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
student.setFirstName(firstName) # Set this student's first name
student.setLastName(lastName)
student.setDegree(degree)# Set this student's last name
student.setGrade(grade)
student.setModuleName(moduleName)
student.setStudentID(studentid)
student.setAge(age)
students.append(student)
print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system."
........................
def viewStudent():
print "Printing all students in database : "
for person in students:
print "Printing details for: " + person.getFirstName()+" "+ person.getLastName()
print "Age: " + person.getAge()
print "Student ID: " + person.getStudentID()
print "Degree: " + person.getDegree()
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
your problem is that the module is a single variable you keep changing. instead, make it a list.
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
should be something like
modules = []
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
modules.append((moduleName, grade))
add a new variable to student which is "Modules" and is a list.
and then modules will be a list of tuples which are (moduleName, grade) and to display them, change the line in viewstudent from:
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
to:
for module, grade in person.getModules():
print "Module: " + module
print "Grades: " + grade
It seems you need something like this:
modules = {}
while True:
module_name = raw_input("Please enter module name: ")
if module_name:
grade = raw_input ("Please enter students grade for " + module_name +": ")
modules[module_name] = grade
Modules is a dictionary ("hash map" in other languages), each mod name is key and grades are values, or you could also do it with tuples, wherever floats your boat.
Instead of checking for -1 as a stop condition you check if is true, in python anything empty is evaluated to false.

Categories