Why While Loop does not work in my program? - python-3.x

The assignment is to create a program that allows user to enter friend's name and phone number then print out contact list sorted by last name. Also to use function.
My problem is it only asks the user to make one action and then it just ask for details right away. It should ask the user to choose another action. Either to exit, add contact, show contacts or sort contacts.
def menu():
'''Display Menu'''
print(
"""
Contact Lists
0 - Exit
1 - Show Contacts
2 - Add Contacts
3 - Sort Contacts
"""
)
def ask():
user = None
user = input("Action: ")
print()
return user
def main():
menu()
action = ask()
names = []
while action != 0:
if action == "0":
print("Closing Contact Lists.")
elif action == "1":
print("Contact Lists: ")
for name in names:
print(name)
#setting a condition if user enter "2" it will let user add name, last name and phone number
elif action == "2":
name = input("Add contact's first name: ") #input 1
last_name = input("Add contact's last name: ") #input 2
contact_number = input("Add phone number for the contact name: ") #input 3
entry = (last_name, name, contact_number)
names.append(entry)
#setting a condition if user enter "3" it will sort contact list according to last names
elif action == "3":
entry.sort(reverse=True) #use of sort() to sort lists of by last names
print(names)
else:
print("Invalid Action!")
main()

Two errors in your code:
You should read user's input at the end of every loop.
Try to add action = ask() below your last else condition.
edit
code pieces:
#setting a condition if user enter "3" it will sort contact list according to last names
elif action == "3":
entry.sort(reverse=True) #use of sort() to sort lists of by last names
print(names)
else:
print("Invalid Action!")
action = ask()
sort() should be performed on names(a list), not entry(a tuple)

Related

grocery list in python 3

I'm confused about how to compare user input and a set list on python. For this problem, I have to create a program that asks the user for a list of ingredients. As the user enters the ingredients, I then need to store them in a list. Once the user is done entering their list, I need to pass this list to a function that will compare the ingredients to an already existing list of pantry items. If all items are available in the pantry, it should print out "you don’t need to go shopping". If any item is missing, it should print out "you need to go shopping" and list the missing ingredients. I've tried several ways of doing it but I can't figure it out.
So basically my function has to have:
1: A pre-created list for pantry items
2: User input into an ingredient list
3: Pass the ingredient list to a method
4: Use a conditional and loop in the method
5: Print out the results of whether the user needs to go shopping based on the items in the ingredient list that are not in the pantry.
This is what I have right now. Whenever I run it, it allows me to type in an item but then says <function end at 0x7fec87bf58b0> :
shopping_list = []
set_list = ['bread', 'jelly', 'peanut butter', 'chips']
#prints out what I need or if I have everything on my list
def end():
for item in shopping_list:
if shopping_list == set_list:
print("you have everything")
else:
print("You have to go grocery shopping! You need:" + str(new_list))
while True:
#asks for new items and removes them from the set list to return a new list
try:
new_item = input("Item? : ")
except ValueError:
print("Oops! That was no valid item. Try again...")
new_list = set_list.remove(new_item)
print(new_list)
if new_item == 'done':
print(end)
end is a function. When you write print(end) you ask python to print info about function. So it prints <function end at 0x7fec87bf58b0>. To print a result of a function you should call it first
So the end of your script will look like
if new_item == 'done':
result = end() # calling a function
print(result)
There you go:
pantry_items = ["apple", "banana", "eggs"]
ingridient_list = []
shopping_list = []
def compare_lists():
for item in pantry_items:
if item not in ingridient_list:
shopping_list.append(item)
userinput = ""
while (len(ingridient_list) < len(pantry_items)):
userinput = input("Enter smth.: ")
if (userinput == "done"):
compare_lists()
if len(shopping_list) > 0:
print("You need:")
print(shopping_list)
else:
print("You dont need to go shopping")
break
ingridient_list.append(userinput)
My python is a bit rusty, but this will do the job

Why does my if statement activate even though the conditions aren't met?

Simple question here, made a little program asks the user to create a username and password. Every thing worked until I added this "if user" statement. It should restart the loop if I enter 'x' or 'X' but it restarts it regardless of what I enter. What's happening here?
db = {}
num_of_entries = 0
def addToDict(a, b):
db[a] = b
print(f"User created: '{a}'")
def removeFromDict(key):
del db[key]
print()
print(f"User '{key}' has been removed.")
while True:
clear = "\n" * 100
print()
print("""
Hi there!
Would you like to create a new account or delete an existing one?
('Create' to create, 'Delete' to delete)
""")
choice = input("> ").upper()
if choice == 'CREATE':
print(f'{choice} mode selected.')
print()
user = input("Please enter a username: ")
if user == 'X' or 'x':
continue
else:
if user not in db:
passW = input("Please enter a password: ")
print(clear)
print()
addToDict(user, passW)
The problem here is that you are posing two separate conditions user == 'X' and 'x'.
since 'x' is not null or false it will always be true making the if statement always true as it uses an or operator between the two conditions.
What you need to do as is suggested above is:
if user == 'X' or user == 'x':
You could also do:
if user.lower() == 'x':
Or even:
if user in ['X', 'x']:

How do I calculate the total sum of my cart to my dictionary list based on user input menu?

I have created a simple menu to add things based on user input.
dictionary = {"Service A": 100, "Service B": 200}
cart = []
def main():
while(True):
print("1. List of Services")
print("2. Payment")
print("3. Exit")
print("\nServices you have added:", cart)
a = input("Please enter a choice: ")
if a=="1":
Q1()
elif a=="2":
Q2()
elif a=="3":
break
def Q1():
print('1. Service A : $100/year')
print('2. Service B : $200/year\n')
service = input("Enter the service 1-2 that you would like to add: ")
if not service.isnumeric():
print('Please enter valid choice number!')
elif service.isnumeric():
print(f'\nYou have selected choice number {service} which is: ')
if service == '1':
print ('\n''1. Service A: $100/year.''\n')
cart.append ("Service A")
if service == '2':
print ('\n''2. Service B: $200/year.''\n')
print('You will be return to main menu.')
cart.append ("Service B")
def Q2():
print("\nServices you have added:", cart)
#total = sum(cart)
#print('\nYour subscription will be a total of :',total)
main()
del(cart)
print("Goodbye and have a nice day!")
I need help in def Q2():
I want the services that I have added to my cart referencing to the dictionary list to get the total sum.
I'm not sure what is the exact codes. Please go easy on me, I'm a beginner.
def Q2():
print("\nServices you have added:", cart)
#total = sum(cart)
#print('\nYour subscription will be a total of :',total)
def Q2():
print("\nServices you have added:", cart)
total = 0
for i in cart:
total = total + dictionary[i]
#total = sum(cart) #This line of code will only merge the selected strings, not the sum of the numbers we need. Because the user added to the list named cart is a string instead of a number
print('\nYour subscription will be a total of :',total)
Hello, thank you for your question.
I added my note after the line of total = sum(cart) code: Because the user added to the list named cart is a string instead of a number. So we can use the for loop to use each string element in the cart as the key value of the dictionary to correspond to its value, and sum all the corresponding values, and finally declare a regional variable named total and store the sum.

Dictionary in Python not printing correctly

I want to print the contacts map but it doesn't work.
I removed all the if statements and it worked, but once I put the if statements in, it fails.
while True:
contacts = {}
print('''Type
1 to Add/Update contact
2 to Display all contacts
3 to Search
4 to Delete contact
5 to Quit.''')
choice = input("Which option?")
if int(choice) == 1:
contacts = {}
name = input("Enter the name of the contact.")
contact = input("Enter the phone number/email address.")
contacts[name] = contact
if int(choice) == 2:
print("Done!")
print(contacts)
if int(choice) == 3:
for key, value in contacts.items():
print(key)
The output is simply {}.
In each iteration of the while loop, you are clearing the contacts dictionary.
while True:
contacts = {}
...
should be
contacts = {}
while True:
...
it looks correct to me.
Maybe try
mycontact=contacts.keys()
phone=contacts.values()
print(mycontact)
print(phone)
If neighter of the solutions work (mine nor yours) try to doublecheck your if statement
choice = input("Which option?")
if int(choice) == 3:
print(this works)
else
print(this does not work)

how can i fix this list index issue, or is there a better way to handle a 'user account'

balance=UBal[UName.index(name)]
what's wrong with this code?
it keeps ending the program
'name' is a string input by a user, and 'name' will be in the list 'UName'
I want the index number from 'name'
using this index number I want to get an integer from the list UBal
I want this integer assigned to 'balance'
this doesn't happen, the program just stops and the 3 red '>>>' is shown
these are the lists
['user one', 'user two', 'user three', 'user four'] #usernames
['100', '200', '300', '400'] #money
my main goal is to be able to get a particular user's account to be accessed.
and their money to be managed
check balance
deposit/withdraw money
delete account
I thought that if i used a code like what i gave at the top, i'd be able to handle a particular account, but if there's a better method, please do tell.
EDIT:
UName=[]
UIdNo=[]
UBal=[]
UserNames=open("UserNames.txt", "r")
UserIDs=open("UserIDs.txt", "r")
UserBalances=open("UserBalances.txt", "r")
# Duplication of data from data storage into empty lists
with open("UserNames.txt") as UserNames:
UName = [line[:-1] for line in UserNames]
with open("UserIDs.txt",) as UserIDs:
UIdNo = [line[:-1] for line in UserIDs]
with open("UserBalances.txt",) as UserBalances:
UBal = [line[:-1] for line in UserBalances]
def handle_user():
name=input("Please enter the user's name again")
if name not in UName:
print("incorrect username")
handle_user()
print("Please Select an action to perform:\n")
print("[ <1> Check Balance ]")
print("[ <2> Deposit cash ]")
print("[ <3> Withdraw cash ]")
print("")
print("[ <97>Remove account ]")
print("")
print("[ <98>Main Menu ]")
ans=input(">> ")
balance=UBal[UName.index(name)]
if ans==1:
print("Account Balance of", name, "is", balance)
print ("Your account balance is" )
menu_actions['handle_user']()
elif ans==2:
print("Please enter a deposit amount:\n")
dep=input(">> ")
elif ans==3:
print("Please enter a withdrawal amount:\n")
wit=input(">> ")
elif ans==97:
del1=input("Are you sure you want to delete this account?")
print("1.YES")
print("2.NO")
if del1==1:
del2=input("CONFIRM ACCOUNT DELETION")
print("[ <1> YES ]")
print("[ <2> NO ]")
if del2==1:
print ("The account of accountholder NAME is being deleted")
filestore.deleteaccount(self.username)
print ("The account has been successfuly deleted")
menu_actions['main_menu']()
elif del2==2:
print("Please Select an action to perform:\n")
menu_actions['handle_user']()
elif choice !='1' and choice!='2':
menu_actions['handle_user']()
elif ans !='1' and ans!='2':
menu_actions['handle_user']()
elif ans !='1' and ans!='2' and ans!='3' and ans!='97' and ans!='98':
print("Please select a valid option:\n")
menu_actions['handle_user']()
return
The problem why nothing happens after you enter 1 is that you're comparing the variable ans of type string with integers 1, 2, 3 and 97. Change it to:
if ans == "1":
# your code
elif ans == "2":
# your code
elif ans == "3":
#your code
etc
At least it will fix your current problem. I could not run your further code since I don't have this method menu_actions.

Resources