Storing Every Single Inputs and Then Displays In Order - python

Is there actually a way to store every different input for n number of inputs and then displays all of them all together in correct order for example:
The User Inputs Record Number, Name, Employee Type, Number Of Days Worked For n number of users
After n number of users, it displays the following all at once:
Record Number: 1
Employee Name: Alexander
Employee Type: C
Days Worked:5
Pay(RM):2500.00
Record Number: 2
Employee Name: Bella
Employee Type: V
Days Worked:10
Pay(RM):1000.00
Record Number: 3
Employee Name: Tom
Employee Type: S
Days Worked:20
Pay(RM):5000.00
Or is it only possible to display one by one? Here is my current code
print("{0:^15s}{1:^25s}".format("Employee Type", "Employee Rate (per day)"))
print("{0:^15s}{1:>15s}".format("C", "RM 500.00"))
print("{0:^15s}{1:>15s}".format("S", "RM 250.00"))
print("{0:^15s}{1:>15s}".format("V", "RM 100.00"))
print()
numEmployee = 1
confirmation = 0
while confirmation != "Y":
numEmployee = input("Enter The Number Of Employees To Be Keyed In: ")
while numEmployee == str():
print("No Input Has Been Detected. Please Input Number Of Employee(s) In An Integer")
numEmployee = input("Enter The Number Of Employees To Be Keyed In: ")
while eval(numEmployee) <= 0:
print("Please Enter A Valid Number Of Employees")
numEmployee = input("Enter The Number Of Employees To Be Keyed In: ")
confirmation = input("Are You Sure You The Number Of Employee Is Correct? Enter Y to Continue or any other key to reenter The Correct Number:")
confirmation = confirmation.upper()
print()
numEmployee = eval(numEmployee)
#for recordNum in range (1, numEmployee + 1):
recordNum = 1
finalTotalC = 0
finalTotalS = 0
finalTotalV = 0
while recordNum <= numEmployee:
print("Record Number: ", recordNum)
recordNum = recordNum + 1
name = input("Employee Name: ")
while name == str():
print("Please Enter A Name")
name = input("Employee Name: ")
employeeType = input("Employee Type: ")
employeeType = employeeType.upper()
while employeeType == str():
print("No Input Has Been Detected. Please Input An Employee Type")
employeeType = input("Employee Type: ")
employeeType = employeeType.upper()
while employeeType != "C" and employeeType != "S" and employeeType != "V":
print("Employee Type Is Invalid. Please Enter C,S or V Only")
employeeType = input("Employee Type: ")
employeeType = employeeType.upper()
daysWorked = input("Days Worked: ")
while daysWorked == str():
print("No Input Has Been Detected. Please Input Number Of Days Worked In That Month")
daysWorked = input("Days Worked: ")
while eval(daysWorked) < 0 or eval(daysWorked) > 31:
print("Please Enter The Number Of Days In A Range Of 0 until 31 Only")
daysWorked = input("Days Worked: ")
daysWorked = eval(daysWorked)
if employeeType == "C":
EMPLOYEERATE = 500.00
print("Pay (RM): ", format(daysWorked*EMPLOYEERATE, ",.2f"))
totalC = daysWorked*EMPLOYEERATE
finalTotalC = finalTotalC + totalC
print()
if employeeType == "S":
EMPLOYEERATE = 250.00
print("Pay (RM): ", format(daysWorked*EMPLOYEERATE, ",.2f"))
totalS = daysWorked*EMPLOYEERATE
finalTotalS = finalTotalS + totalS
print()
if employeeType == "V":
EMPLOYEERATE = 100.00
print("Pay (RM): ", format(daysWorked*EMPLOYEERATE, ",.2f"))
totalV = daysWorked*EMPLOYEERATE
finalTotalV = finalTotalV + totalV
print()

You need to store the data somewhere, as you are receiving it. I would suggest a list (https://docs.python.org/2/tutorial/datastructures.html#more-on-lists) of dicts (https://docs.python.org/2/tutorial/datastructures.html#dictionaries) might be appropriate for your case. Then you can iterate over the list after you're done (in order to print).

Related

I cannot access the movies list I created (python)

I am currently having issues having my program access my list after the user enters a menu option. the only entry being read is the 1939 entry, any other year will only present the "enter a valid year" option. Another issue is when displaying categories, only the first 2 drama films will pop up, every other category doesn't work when asked for. It also will not display the entire list when I call to display it (only the 1939 entry would pop up). Any help would be very appreciated!
movies = [[1939,'Gone With the Wind','drama'],
[1943,'Casablanca','drama'],
[1965,'The Sound of Music','musical'],
[1969,'Midnight Cowboy','drama'],
[1972,'The Godfather','drama'],
[1973,'The String','comedy'],
[1977,'Annie Hall','comedy'],
[1981,'Chariots of Fire','drama'],
[1984,'Amadeus','historical'],
[1986,'Platoon','action'],
[1988,'Rain Man','drama'],
[1990,'Dances with Wolves','western'],
[1992,'Unforgiven','western'],
[1993,'Schindlers List','historical'],
[1994,'Forrest Gump','comedy'],
[1995,'Braveheart','historical'],
[1997,'Titanic','historical'],
[1998,'Shakespeare in Love','comedy'],
[2001,'A Beautiful Mind','historical'],
[2002,'Chicago','musical'],
[2009,'The Hurt Locker','action'],
[2010,'The Kings Speech','historical'],
[2011,'The Artist','comedy'],
[2012,'Argo','historical'],
[2013,'12 Years a Slave','drama'],
[2014,'Birdman','comedy'],
[2016,'Moonlight','drama'],
[2017,'The Shape of Water','fantasy'],
[2018,'Parasite','comedy']]
menu = """
1 - Display winning movie for a selected year
2 - Display movie and category for a selected year
d - Display entire movie list
dc - Display movies in a selected category - year and title
q = quit
"""
while True:
print(menu)
option = input("Please enter a valid menu option from above: ")
if option in 'qQ':
print("Ending program")
break
elif option == "1":
year = int(input("Please enter a valid year: "))
for m in movies:
if year == m[1]:
print("The winning movie in ", year," was: ", m[1])
else:
print("Input a valid year")
break
elif option == "2":
year = int(input("Please enter a valid year: "))
for m in movies:
if year == m[0]:
print("The winning movie was: ", m[1], "and its category was: ", m[2])
else:
print("Please enter a valid year")
break
elif option == "d":
for m in movies:
print(m[0], m[1], m[2])
break
elif option == "dc":
cat = input("Please enter a valid category")
for m in movies:
if cat == m[2]:
print(m[0], m[1])
else:
print("Please enter a valid category")
break
else:
print()
print("Please select a valid option")
At m[1] pulls movie name and not year.
Converting year input to integer and comparing.
if int(year) == m[0]:
Also, Breaks are used improperly. for display option index are not correctly used.
print(m[0], m[1], m[2])
Corrected Code
while True:
print(menu)
option = input("Please enter a valid menu option from above: ")
if option in 'qQ':
print("Ending program")
break
elif option == "1":
year = input("Please enter a valid year: ")
print(year)
for m in movies:
if int(year) == m[0]:
print("The winning movie in ", year," was: ", m[1])
elif option == "2":
year = input("Please enter a valid year: ")
for m in movies:
if int(year) == m[0]:
print("The winning movie was: ", m[1], "and its category was: ", m[2])
elif option == "d":
for m in movies:
print(m[0], m[1], m[2])
elif option == "dc":
cat = input("Please enter a valid category : ")
for m in movies:
if cat == m[2]:
print(m[1], m[2])
else:
print("Please select a valid option")

Two of my functions don't work correctly, IDE doesn't show errors or crashes

The deposit function and the withdraw function doesn't work. After populating the accounts, I can select D or W menu options and input any number without causing the program to crash or causing an error. The program seems it is working correctly but when you check the balances using the S option, they are not updated.
Names=[]
accountnumbers=[]
balance=[]
def populatelist():
position=0
while(position<=2):
yourname= str(input("Please enter a name: "))
Names.append(yourname)
account = int( input("Please enter an account number: " ))
accountnumbers.append(account)
totalbalance = int( input("Please enter a balance: "))
balance.append(totalbalance)
position = position + 1
##################################### DEPOSIT FUCNTION
def deposit(accountnumber):
foundposition=-1
position=0
if (len(accountnumbers)>0):
while (position <=2):
if (accountnumber==accountnumbers[position]):
return position
position = position + 1
return foundposition
#################################### WITHDRAW FUNCTION
def withdraw(accountnumber):
foundposition=-1
position=0
if (len(accountnumbers)>0):
while (position <=2):
if (accountnumber==accountnumbers[position]):
return position
position = position + 1
return foundposition
def findingaccount(accountnumber):
foundposition=-1
position=0
if (len(accountnumbers)>0):
while (position <=2):
if (accountnumber==accountnumbers[position]):
return position
position = position + 1
return foundposition
def menuoptions():
print ("**** MENU OPTIONS ****")
print ("Type P to populate accounts")
print ( "Type S to search for account")
print ("Type E to exit")
print ("Type D to deposit Amount")
print ("Type W to withdraw Amount")
choice = str(input("Please enter your choice: "))
return choice
response=""
while response!= "E":
response = menuoptions()
if response=="P":
populatelist()
########################### Deposit OPTION
elif response=="D":
searchaccount = int(input("Please enter the account number to add deposit: "))
foundtheposition = deposit(searchaccount)
money = int(input("Please enter the amount to be deposited: "))
money + (balance[foundtheposition])
########################### WITHDRAW OPTION
elif response=="W":
searchaccount = int(input("Please enter the account number to withdraw: "))
thenumber = withdraw(searchaccount)
withdraw = int(input("how much for withdraw"))
withdraw - (balance[thenumber])
if (balance[thenumber]) < withdraw :
print("ERROR: Not enough balance")
elif response=="S":
searchaccount = int(input("Please enter the account number to search: "))
foundaposition = findingaccount(searchaccount)
if ( foundaposition == -1 ):
print ("The account number not found!")
else:
print ("Name is:" + str( Names[foundaposition]))
print (str(Names[foundaposition]) + " " + "account has the balance of :" +str(balance[foundaposition]))
elif response=="E":
print ("Thank you for using the program.")
print ("Bye")
exit
else:
print ("Invalid choice. Please try again!")
You have logic error.
Just change
money + (balance[foundtheposition])
to
balance[foundtheposition] = balance[foundtheposition] + money
or using short-hand operator like
balance[foundtheposition] += money
Same for
withdraw - (balance[thenumber])
Cheers ...
Your deposit scenario needs to add the amount into the selected account:
balance[thenumber] += money
Fair warning there are other errors in your program besides the accounts not updating.

How to exit a while loop

currently I am doing my assignment. The requirement is to test the format of Student ID. I wonder why is my while loop is not working properly..
My validation check is as below:
def isValidStudentIDFormat(stid):
# studentID must have a length of 9
if(len(stid) != 9):
# return the invalid reason
return "Length of Student ID is not 9"
# studentID must starts with a letter S
if(stid[0] != 'S'):
# return the invalid reason
return "First letter is not S"
# studentID must contains 7 numbers between the two letters
for i in range(1,8):
# anything smaller than 0 or bigger than 9 would not be valid.
# so does a character, will also be invalid
if((stid[i] < '0') or (stid[i] > '9')):
# return the invalid reason
return "Not a number between letters"
if((stid[8] < 'A') or (stid[8] > 'Z')):
# return the invalid reason
return "Last letter not a characer"
# return True if the format is right
return True
My function to insert a student record is below:
def insert_student_record():
#printing the message to ask user to insert a new student into the memory
print("Insert a new student \n")
fn = input("Enter first name: ")
#check if user entered space
#strip() returns a copy of the string based on the string argument passed
while not fn.strip():
print("Empty input, please enter again")
fn = input("Enter first name: ")
ln = input("Enter last name: ")
while not ln.strip():
print("Empty input, please enter again")
ln = input("Enter last name: ")
stid = input("Enter student id: ")
while not stid.strip():
print("Empty input, please enter again")
stid = input("Enter student id: ")
result = isValidStudentIDFormat(stid)
while (result != True):
print("Invalid student id format. Please check and enter again.")
stid = input("Enter student id: ")
result == True
#append the student details to each list
#append first name
fName.append(fn)
#append last name
lName.append(ln)
#append student id
sid.append(stid)
#to check if the new student is in the lists
if stid in sid:
if fn in fName:
if ln in lName:
#then print message to tell user the student record is inserted
print("A new student record is inserted.")
However, I'm getting an infinite loop even if I key in the correct format for student ID. Anyone can help ?
You compare result == True when you should assign. Still, you don't check the new student id for validity, which could be done this way:
while (result != True):
print("Invalid student id format. Please check and enter again.")
stid = input("Enter student id: ")
result = isValidStudentIDFormat(stid)
?
def validateStudentIDFormat(stid):
if len(stid) != 9:
raise RuntimeError("Length of Student ID is not 9")
if stid[0] != 'S':
raise RuntimeError("First letter is not S")
for char in stid[1:-1]:
if char.isnumeric():
raise RuntimeError("Not a number between letters")
if not stid[-1].isalpha():
raise RuntimeError("Last letter not a characer")
....
while True:
stid = input("Enter student id: ")
try:
validateStudentIDFormat(stid)
except RuntimeError as ex:
print(ex)
print("Invalid student id format. Please check and enter again.")
else:
break

When I print my list instead of using the names in the list the output shows the index numbers. Python 2D-Lists

Here is my code the lists are where Im having issues. Im new to python and I do not understand how 2D-lists work but I need to add then in to the program for a grade. Any help will be appreciated.
#Define Vars
import locale
locale.setlocale( locale.LC_ALL, '')
order_total = 0.0
price = 3.5
fmt_price = locale.currency(price, grouping=True)
qty = int(0)
#cookie list
cookie_list = list()
cookie_list = "Savannah Thin-Mints Tag-a-longs Peanut-Butter Sandwich".split()
order_list = list()
#cookie choices
def disp_items():
print("Please choose one of our flavours. Enter the item number to choose")
for c in range(len(cookie_list)):
print("{}. \t{}".format(c+1, cookie_list[c]))
print()
#Menu Choices
def disp_menu():
choice_list = ["a", "d", "m", "q"]
while True:
print("\nWhat would you like to do?")
print("a = add an item")
print("d = delete an item")
print("m = display the meal so far")
print("q = quit")
choice = input("\nmake a selection: ")
if choice in choice_list:
return choice
else:
print("I dont't understand that entry. Please Try again.")
# Math Function**********************
def calc_tot(qty):
#this function is qty * price
return qty * 3.5
def disp_order():
print("\nGirl Scout Cookie Order for", cust)
print()
print("Itm\tName\tQty\tPrice")
print("---\t----\t----\t----")
order_total_items = 0 #accumulator
order_price = 0
for c in range(len(order_list)):
detail_list = [" ", 0]
detail_list.append(order_list)
print("{}.\t{}\t{}\t{}".format(c+1, order_list[c][0], order_list[c][1], price))
order_total_items += order_list[c][1]
order_price += price
print("\nYour Order Contains {} items for total of {} \n".format(order_total_items, order_price))
print("-" * 30)
#ADD Process
def add_process():
valid_data = False
while not valid_data:
disp_items()
try:
item = int(input("Enter item number: "))
if 1 <= item <= len(cookie_list):
valid_data = True
else:
print("\nThat was not a vaild choice, please try again.")
except Exception as detail:
print("error: ", detail)
#Valid Qty
valid_data = False
while not valid_data:
try:
qty = int(input("Enter Quantity: "))
if 1 <= qty <= 10:
valid_data = True
else:
print("\nThat was not a valid quantity, please try again.")
except Exception as detail:
print("Error; ", detail)
print("Please try again")
#Function call for multiplication
item_total = calc_tot(qty)
fmt_total = locale.currency(item_total, grouping=True)
#User Choice
print("\nYou choose: {} boxes of {} for a total of {}".format(qty,
cookie_list[item-1],
fmt_total))
print()
#verify inclusion of this item
valid_data = False
while not valid_data:
incl = input("Would you like to add this to your order? (y/n): ")
print()
if incl.lower() =="y":
#2-D List
inx = item - 1
detail_list = [inx, qty]
order_list.append(detail_list)
valid_data = True
print("{} was added to your order".format(cookie_list[inx]))
elif incl.lower() == "n":
print("{} was not added to your order".format(cookie_list[inx]))
valid_data = True
else:
print("That was not a vaild response, please try again")
#Delete function
def del_item():
if len(order_list) == 0:
print("\n** You have no items in your order to delete **\n")
else:
print("\nDelete an Item")
disp_order()
valid_data = False
while not valid_data:
try:
choice = int(input("Please enter the item number you would like to delete: "))
if 1<= choice <= len(order_list):
choice = choice - 1
print("\nItem {}. {} with {} boxes will be deleted".format(choice +1,
order_list[choice][0],
order_list[choice][1]))
del order_list[choice]
valid_data = True
except Exception as detail:
print("Error: ", detail)
print("Please try again")
#Main program
# Banner
print("Welcome to the Girl Scout Cookie")
print("Order Program")
cust = input("Please enter your name: ")
while True:
choice = disp_menu()
if choice == "a":
add_process()
elif choice == "d":
del_item()
elif choice == "q":
break
disp_order()
disp_order()
print("Thank you for your order")
Here's the output
Girl Scout Cookie Order for *****
Itm Name Qty Price
--- ---- ---- ----
1. **0** 1 3.5
2. **0** 1 3.5
3. **4** 5 3.5
Your Order Contains 7 items for total of 10.5
Under name there should be a name of a girl Scout Cookie and not the index number, how do i fix this?
Many Thanks.
When you print the order in disp_order() you should print from cookie_list[c] in the second column. And print the whole item instead off just the first letter.
print("{}.\t{}\t{}\t{}".format(c+1, cookie_list[c], order_list[c][1], price))
The cookie names are not of equal length, so you'll have to adjust for that.

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

Categories