Using a Loop to add objects to a list(python) - python

I'm trying to use a while loop to add objects to a list.
Here's basically what I want to do:
class x:
pass
choice = raw_input(pick what you want to do)
while(choice!=0):
if(choice==1):
Enter in info for the class:
append object to list (A)
if(choice==2):
print out length of list(A)
if(choice==0):
break
((((other options))))
I can get the object added to the list, but I am stuck at how to add multiple objects to the list in the loop.
Here is the code I have so far:
print "Welcome to the Student Management Program"
class Student:
def __init__ (self, name, age, gender, favclass):
self.name = name
self.age = age
self.gender = gender
self.fac = favclass
choice = int(raw_input("Make a Choice: " ))
while (choice !=0):
if (choice==1):
print("STUDENT")
namer = raw_input("Enter Name: ")
ager = raw_input("Enter Age: ")
sexer = raw_input("Enter Sex: ")
faver = raw_input("Enter Fav: ")
elif(choice==2):
print "TESTING LINE"
elif(choice==3):
print(len(a))
guess=int(raw_input("Make a Choice: "))
s = Student(namer, ager, sexer, faver)
a =[];
a.append(s)
raw_input("Press enter to exit")
Any help would be greatly appreciated!

The problem appears to be that you are reinitializing the list to an empty list in each iteration:
while choice != 0:
...
a = []
a.append(s)
Try moving the initialization above the loop so that it is executed only once.
a = []
while choice != 0:
...
a.append(s)

Auto-incrementing the index in a loop:
myArr[(len(myArr)+1)]={"key":"val"}

Related

Creating a function where I can input first names and last names into a dictionary

I am kind of stuck, I am trying to make a function that allows me to append onto an empty dict, I want to add first name and surname, and also make it possible to have people with same last names but different first names. Any ideas? This is my first time asking a question on here, let me know if I need to find any other info thanks!
def people():
people = {}
prompt = input("Would you like to add a person to the list? (Y/N): ")
while prompt.lower() == "y":
qs = dict(name='first name', surname='last name')
for key, value in qs.items():
people[key] = input('Please enter your {}: '.format(value))
print(people)
prompt = input("Another person? (Y/N): ")
print(people)
return people
people()
First ask the user the input('Please enter your {}: '.format(value))
store it in a variable and then assign the people[key] to the variable
Example:
def people():
people = {}
prompt = input("Would you like to add a person to the list? (Y/N): ")
while prompt.lower() == "y":
qs = dict(name='first name', surname='last name')
for key, value in qs.items():
name = input('Please enter your {}: '.format(value))
people[key] = name
print(people)
prompt = input("Another person? (Y/N): ")
print(people)
return people
As mentioned in the comments that the people dicts gets reset
So with the approach of nested dicts you can use this:
def people():
people_ = {}
prompt = input("Would you like to add a person to the list? (Y/N): ")
while prompt.lower() == "y":
qs = dict(name='first name', surname='last name')
print(qs)
index = f"person_{len(people_) + 1}"
people_[index] = {}
for key, value in qs.items():
name = input('Please enter your {}: '.format(value))
people_[index][key] = name
print(people_)
prompt = input("Another person? (Y/N): ")
print(people_)
return people_
def people():
people = {}
add_person_msg = "Add person to list? (Y/N): "
first_name_msg = "First name: "
last_name_msg = "Last name: "
while input(add_person_msg).lower() == 'y': #.lower()
people[input(first_name_msg)] = input(last_name_msg)
return people
print(people())
if you wanted to work with the names before storing in dictionary, for example capitalize them:
def people_dict():
fn_msg = "First name: "
ln_msg = "Last name: "
people = {}
while input("Add person? y/n: ").lower() == 'y':
fn, ln = input(fn_msg).title(), input(ln_msg).title()
people[fn] = ln
return people
Also instead of using .format() method,
input('Please enter your {}: '.format(value)
if you are using Python 3.5 and above you can use f-strings:
input(f'Please enter your {value}:')

Python Repeated Actions

I have a list that contains strings
animalList=['ASLAN', 'KAPLAN', 'KOPEK', 'KEDI']
descLion = ( 'it is called lion....')
descTiger = (' it is called tiger....')
I ask user to enter one of them and check for typos
questOne = input("Enter the name of the animal: ")
questOne = questOne.upper()
while questOne not in animalList:
questOne = input("Whatch out for typos Try again: ")
questOne = questOne.upper()
else:
print(questOne + ' IT IS')
What I couldn't figure out is that I want my code to keep ask for a name of the animal, check for typos and print the related description and repeat this action. I have tried something like that;
while questOne == animalList[0]:
print (descLion)
questOne = input("Enter the name of the animal: ")
questOne = questOne .upper()
while questOne == animalList[1]:
print (descTiger)
questOne = input("Enter the name of the animal: ")
questOne = questOne.upper()
This code kind of works only if the user inputs are in the order of the list. I would like user to be able to enter the input randomly.
You want to use "while True". Example:
while True:
name = input("Enter your name: ")
print("Hi, {}!".format(name))
print("What about now?")

How would I stop the loop when after its added the names to the list and other errors

How would I stop my code looping after it has added the amount of names the user has inputted instead of doing this:
Add Name
Show list
Quit
Enter your choice : 1
How many names would you like to enter: 2 # How would I set a max of 10 names here?
Enter name: Bob
Enter name: Jim
How many names would you like to enter: # How would I stop this line from repeating?
Actual code:
names = []
def displayMenu():
print(" 1. Add Name")
print(" 2. Show list")
print(" 3. Quit")
choice = int(input("Enter your choice : "))
while choice >5 or choice <1:
choice = input("Invalid. Re-enter your choice: ")
return choice
def addname():
while True:
number=int(input('How many names would you like to enter: '))
name = [input('Enter name:') for _ in range(number)]
names.append(name)
def displayData():
#name.split(",") how would i correctly user split here
print(names)
option = displayMenu()
while option != 3:
if option == 1:
addname()
elif option == 2:
displayData()
option = displayMenu()
print("Program terminating")
Okay, first off, since you only have three menu options, this line:
while choice >5 or choice <1:
Should look like this:
while 3 < choice < 1:
So your displayMenu function looks like this:
names = []
def displayMenu():
print(" 1. Add Name")
print(" 2. Show list")
print(" 3. Quit")
choice = int(input("Enter your choice : "))
while 3 < choice < 1: # Only accept choices in between 3 and 1
choice = input("Invalid. Re-enter your choice: ")
return choice
You also said that your addname function was looping forever, this is because you have an infinite while loop.
What you need, as #ettanany said, is a for loop:
In your case, for loop would work also:
def addname():
number = int(input('How many names would you like to enter: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)
What this does is ask the user how many names he wants to enter, and then runs the code inside the loop for that amount of times -- so if the user enters the number 9, it will ask for 9 names.
You also said that there should be a maximum of 10 names. We can use a while loop like you did in the displayMenu function to make sure the user enters a number that is 10 or below:
def addname():
number = int(input('How many names would you like to enter: '))
while number > 10: # Don't allow any numbers under 10
number = int(input('Please enter a number under 10: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)
Finally, in your displayData function, you want to 'split' the names and print them out.
Just doing print(names) would give us a result like this:
[ 'Spam', 'Eggs', 'Waheed' ]
If we want it to look nice, we need to use a for loop.
for name in names:
print( name ) # You can change this line to print( name, end=' ' )
# If you want all the names on one line.
This will yield a result like this:
Spam
Eggs
Waheed
Which looks much better than just printing out the list.
Complete (fixed) code:
names = []
def displayMenu():
print(" 1. Add Name")
print(" 2. Show list")
print(" 3. Quit")
choice = int(input("Enter your choice : "))
while 3 < choice < 1: # Only accept choices in between 3 and 1
choice = input("Invalid. Re-enter your choice: ")
return choice
def addname():
number = int(input('How many names would you like to enter: '))
while number > 10: # Don't allow any numbers under 10
number = int(input('Please enter a number under 10: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)
def displayData():
for name in names:
print( name ) # You can change this line to print( name, end=' ' )
# If you want all the names on one line.
option = displayMenu()
while option != 3:
if option == 1:
addname()
elif option == 2:
displayData()
option = displayMenu()
print("Program terminating")
Instead of while True, you need to use while i < number, so your addname() function should be as follows:
def addname():
i = 0
number = int(input('How many names would you like to enter: '))
while i < number:
name = input('Enter name: ') # We ask user to enter names one by one
names.append(name)
i += 1
In your case, for loop would work also:
def addname():
number = int(input('How many names would you like to enter: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)

Passing a dictionary to a new function in python?

If I create a dictionary that I need to access in multiple functions what would be the best way to pass it?
What I currently am doing keeps reseting the dictionary to empty. If I print in the addDictionary() I get the result I want. However, when I go to look up a element using the key in lookUpEntry(), I can't find it. When I print I get an empty dictionary. I also have to eventually pickle and unpickle so if anyone has any feedback on that, that would also help.
import pickle
def dictionary():
addressBook = {}
return addressBook
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 addDictionary():
addressBook = dictionary()
personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone = addPerson()
addressBook[personLastName] = personFirstName, personEmail, personStreetAddress, personCityState, personPhone
print(personFirstName,personLastName, "has been added to the address book!")
print(addressBook)
return addressBook
def lookUpEntry():
addressBook = dictionary()
keyName = input("Enter the last name of the person you are trying to find.")
while not keyName in addressBook:
keyName = input("That name is not in the address book. Please try again.").lower()
x = input("Enter '1' if you want to look up a email. Enter '2' if you want to look "
"up a persons address. Enter '3' to look up a persons phone number: ")
if x == "1":
print("The email of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[1]])
elif x == "2":
print("The address of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[2]], addressBook[keyName[3]])
elif x == "3":
print("The phone number of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[4]])
else:
print("Sorry that item is not stored in this address book.")
def main():
addDictionary()
lookUpEntry()
main()
Currently you define dictionary as
def dictionary():
addressBook = {}
return addressBook
Here you create a new dictionary every time it is called. Try replacing this with
# a global dictionary
_addressBook = {}
def dictionary():
return _addressBook

Prompt user to enter names and prints out the list in python

trying to make a program that prompts user to enter a famous peoples names and continues asking until they type "done" and prints out the list with the names and the number of names. could anyone give me a little help?
def main():
cList = []
cName = []
while cName != ("done"):
cList.append(cName)
cName = input("Enter another name: ")
print("# of names entered: "), [cList]
i = 0
while i < len(cList):
print myList[i]
i += 1
return
main()
Like this?
names = []
while True:
names.append(raw_input('Enter name: '))
if names[-1] == 'done':
names.pop()
break
print("# of names %i" % len(names))
for name in names:
print(name)

Categories