Just started venturing into arrays using python 2.7.5. My objective is to ask the user for input and store the input in multiple arrays.
So far this is what I have, as far as storing multiple arrays with input. I run into an error when trying to print the input at the end.
Here is the code I have so far.
# want user to enter a list of employee names, error occurs when trying to recall user entry
emp_name = [0]
emp_name = raw_input("please enter employee name")
while emp_name !="neg":
emp_name = raw_input("please enter employee name,enter neg to exit")
print "employee 2 is:", emp_name[1] #I want the 2nd name entered to appear
Then you are going to want to:
Change the names of your variables so that you don't have the list be the same name as the input.
Append each name you get to the list.
This should be what you want:
employees = []
name = raw_input("Please enter an employee name: ")
while name != "neg":
# Append the previous name.
employees.append(name)
# Get a new name.
name = raw_input("Please enter an employee name or 'neg' to exit: ")
# You need a try/except here in case there is no second employee.
# This can happen if the user types in "neg" to begin with or only 1 name.
try:
print "Employee 2 is: ", employees[1]
except IndexError:
print None
Also, I slightly changed your input prompts to make them cleaner and more user-friendly.
Below is a sample of the script in action:
Please enter an employee name: Bob
Please enter an employee name or 'neg' to exit: Joe
Please enter an employee name or 'neg' to exit: neg
Employee 2 is: Joe
And here is one without a second employee:
Please enter an employee name: Joe
Please enter an employee name or 'neg' to exit: neg
Employee 2 is: None
Your first line declares emp_name as an array.
Your second line raw_input("please enter employee name") re-assigns it as a string.
So when you tell it to print emp_name[1], it has no idea what emp_name[1] is because it sees a string at that point.
If you write, instead:
emp_name[0] = raw_input("please enter employee name")
That means you're assigning that employee name to element 0 of array emp_name.
Then you want to add index entries inside the while, rather than re-assigning them (you see, it doesn't automatically accumulate entries, you have to tell it to).
Happy Coding!
You can add to a list with list.append(), but you need to capture user input into a separate variable:
employees = []
emp_name = raw_input("Please enter employee name, enter neg to exit")
while emp_name != "neg":
emp_name = raw_input("Please enter employee name, enter neg to exit")
employees.append(emp_name)
print "employee 2 is:", employees[1]
Apart from using separate variables for the list of names and for the name the user has just entered, I also started the list entirely empty.
You can avoid using two raw_input() calls by changing the while loop to an infinite loop and instead break out of the loop when 'neg' has been entered:
employees = []
while True:
emp_name = raw_input("Please enter employee name, enter neg to exit")
if emp_name == 'neg':
break
employees.append(emp_name)
You may also need to test if there are enough employees entered before you print the second employee:
if len(employees) > 1:
print "Employee 2 is:", employees[1]
else:
print "You didn't enter enough employees!"
Related
# Initialized list of cities
CitiesInMichigan = ["Acme", "Albion", "Detroit", "Watervliet", "Coloma", "Saginaw", "Richland", "Glenn", "Midland",
"Brooklyn"]
# Get user input
inCity = input("Enter name of city: ")
# Write your test statement here to see if there is a match.
for i in range(len(CitiesInMichigan)):
if CitiesInMichigan[i] == inCity:
while CitiesInMichigan is True:
print("City found. ")
break
else:
print("Not a city in Michigan. ")
input("Enter name of city: ")
# If the city is found, print "City found."
# Otherwise, "Not a city in Michigan" message should be printed.
So what I am trying to go for was to have the input case insensitive so (Acme, ACME, acMe, etc.) would work
and to have it break if input matches or try again if input is false.
Instead I have been receiving that all inputs are not a city of Michigan.
What am I doing wrong?
P.S I am studying python for school and as a passion, I am still new and wrapping my head around it please criticize anything I do wrong to further improve my codings.
Thank you
Your while loop is unnecessary and your else clause should simply be moved outside of the loop. You also need to loop all the way back to your initial input if a city is not found.
cityFound = False
while not cityFound:
inCity = input("Enter name of city: ")
for i in range(len(CitiesInMichigan)):
if CitiesInMichigan[i] == inCity:
print("City found. ")
cityFound = True
break
if not cityFound:
print("Not a city in Michigan. ")
To do case insensitive matching you should use the string upper method on both the input and the value in your CitiesInMichigan list before you check for equality.
Other notes:
You don't need to use an index in your for loop, you can just use for city in CitiesInMichigan
Generally variable names begin with lower case letters (citiesInMichigan instead of CitiesInMichigan). Class names start with upper case letters
as others have mentioned, the while loop is unnecessary. below code is longer than it needs to be, but it explains itself well.
# Initialized list of cities
CitiesInMichigan = ["Acme", "Albion", "Detroit", "Watervliet", "Coloma", "Saginaw", "Richland", "Glenn", "Midland",
"Brooklyn"]
def get_input():
'''Get user input and capitalize it'''
inCity = input("Enter name of city: ")
inCity = inCity.capitalize()
check_against_list(name=inCity)
def check_against_list(name):
'''check if the item is in the list. if yes, print. if not, print and start over'''
if name in CitiesInMichigan:
print("City found. ")
else:
print("Not a city in Michigan. ")
get_input()
get_input()
CitiesInMichigan = ["Acme", "Albion", "Detroit", "Watervliet", "Coloma", "Saginaw", "Richland", "Glenn", "Midland",
"Brooklyn"]
CitiesInMichigan_casefold = [i.casefold() for i in CitiesInMichigan ]
inCity = input("Enter name of city: ")
while True:
if inCity.casefold() in CitiesInMichigan_casefold:
print("city found",inCity)
break
else:
print("city not found")
inCity = input("Enter name of city again: ")
Try this. you have to compare case fold strings both in input and as well as from the mentioned list.
if the city is found, it prints city name and breaks the loop.
else it continues until the city is matched.
I'm trying to write a travel itinerary program using base Python functionality. In step 1, the program should ask for primary customer (making the booking) details viz name and phone number. I've written code to also handle errors like non-alphabet name entry, errors in phone number input (ie phone number not numeric, not 10 digits etc) to keep asking for valid user input, as below, which seems to work fine:
while True:
cust_name = input("Please enter primary customer name: ")
if cust_name.isalpha():
break
else:
print("Please enter valid name")
continue
while True:
cust_phone = input("Please enter phone number: ")
if cust_phone.isnumeric() and len(cust_phone) == 10:
break
else:
print("Error! Please enter correct phone number")
continue
while True:
num_travellers = input("How many people are travelling? ")
if int(num_travellers) >= 2:
break
else:
print("Please enter at least two passengers")
continue
Output:
Please enter primary customer name: sm
Please enter phone number: 1010101010
How many people are travelling? 2
For the next step, the program should ask for details of all passenger ie name, age and phone numbers and store them. I want to implement similar checks as above but my code below simply exits the loop once the number of travellers (num_travellers, 2 in this case) condition is met, even if there are errors in input:
for i in range(int(num_travellers)):
travellers = []
travel_name = input("Please enter passenger name: ")
if travel_name.isalpha():
travellers.append(travel_name)
else:
print("Please enter valid name")
continue
for j in range(int(num_travellers)):
travel_age = []
age = input("Please enter passenger age: ")
if age.isnumeric():
travel_age.append(age)
else:
print("Please enter valid age")
continue
Output:
Please enter passenger name: 23
Please enter valid name
Please enter passenger name: 34
Please enter valid name
Please enter passenger age: sm
Please enter valid age
Please enter passenger age: sk
Please enter valid age
Please enter passenger age: sk
I've tried using a while loop like mentioned in this thread but doesn't seem to work. Where am I going wrong? Thanks
You have missed while True: loop when asking for passenger data. Try something like below:
travellers = []
for i in range(int(num_travellers)):
while True:
travel_name = input("Please enter passenger name: ")
if travel_name.isalpha():
travellers.append(travel_name)
break
else:
print("Please enter valid name")
continue
BTW I moved travellers variable out of the loop, otherwise it is going to be cleared on every iteration.
When I run the program it asks for my input multiple times even after I've entered it once already.
Peeps = {"Juan":244, "Jayne":433, "Susan":751}
Asks the user to input a name which is the key to a value, which it returns
for i in Peeps:
if i == input("Type in a name: "):
print("The amount", [i], "owes is:", "$" + str(Peeps[i]))
break
else:
print("Sorry that name does not exist, please enter a new name.")
You need to ask the user input first instead of comparing the user input directly to the key.
You do not want to do it like that. Take a look at the following instead:
Peeps = {"Juan":244, "Jayne":433, "Susan":751}
name = input("Type in a name: ")
if name in Peeps:
print("The amount", name, "owes is:", "$" + str(Peeps[name]))
else:
print("Sorry that name does not exist, please enter a new name.")
You do not have to loop through your dict and check the user input against each value individually (plus you are forcing the user to update\re-enter his input continuously).
Just receive it once and process it.
If you want to keep the loop running to allow for multiple queries, use while like so:
Peeps = {"Juan": 244, "Jayne": 433, "Susan": 751}
name = input("Type in a name or leave blank to exit: ")
while name:
if name in Peeps:
print("The amount", name, "owes is:", "$" + str(Peeps[name]))
else:
print("Sorry that name does not exist, please enter a new name.")
name = input("Type in a name or leave blank to exit: ")
I'm creating a address book program, and need to have a dictionary that I can add too, edit, and delete, as well as pickle. What would be the best way to create it so it is accessible by all the functions? I currently have the dictionary in the addon function but wouldn't it reset if I were to call the dictionary to another function?
My code so far (not including the menuModule)
def addPerson():
personLastName = input("Enter the last name of "
"the person you want to add: ").lower()
personFirstName = input("Please enter the first name of "
"the person you want to add: ")
localPart = input("Please enter the local part of the email address")
while not localPart.isalnum():
localPart = input("Please enter a valid input, a-z and numbers 0-9: ")
domain = input("Please enter the domain of the email addres: ")
while not domain.isalnum():
domain = input("Please enter a valid input, a-z and numbers 0-9: ")
topLevelDomain = input("Please enter the top level domain, examples: com, net, org: ")
while not topLevelDomain.isalnum() or len(topLevelDomain) > 3:
topLevelDomain = input("Please enter only letters, a-z and not more then 3 characters: ")
personEmail = localPart + "#" + domain + "." + topLevelDomain
personStreetAddress = input("Please enter house number and street of the person you want to add: ")
personCityState = input("Please enter the city, state abbreviation and zipcode of the person you want to add: ")
personPhone = input("Please enter the phone number of the person you want to add: ")
personPhoneStr = personPhone.strip("-")
while not personPhoneStr.isdigit() and not len(personPhoneStr) == 10:
personPhone = input("Error. That is not a valid phone number. Try again: ")
personPhoneStr = personPhone.strip("-")
return personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone
def appendDictionary():
personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone = addPerson()
listX = [personFirstName, personEmail, personStreetAddress, personCityState, personPhone]
addressBook = {personLastName: listX}
print(personFirstName,personLastName, "has been added to the address book!")
print(addressBook)
return addressBook
Try using lists. One list for each of the variables because if you try to store them as a tuple and then add them into a master list you will not be able to or it will be hard to charge them and edit them. Here is an example of storing the data:
nameList.extend(john)
emailList.extend(john#gmail.com.uk)
john_index = len(nameList)
Give each person an index to help you file their information so if our list looked like [jane#live.com, sam#wenston.com, john#gmail.com.uk] johns data is going to be the last in the list because we just entered it in position 3 on the list and the length function returns 3 so you know where johns data is stored and if you were to add more data it would stack up accourdingly.
here is an example of getting it back out of the list and editing it:
print nameList[john_index]
print emailList[john_index]
emailList[john_index] = new_value
I hope you understand :)
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.