make all the variables global inside a function of python3 - python-3.x

How to declare all the variables global inside a function for python-3 for the below code .I have to use many variables with name "dairy" like "dairy_choice",etc and wish to use again in program.
def dairy_menu():
for key in dairy:
print(key,":",dairy[key])
global dairy_choices
dairy_choices = {}
while True:
global dairy_choice
dairy_choice = input("Enter your desired product = ")
if dairy_choice not in dairy_key_list:
print("Enter a valid choice from the above list!")
if dairy_choice in dairy_key_list:
dairy_choice_quantity = int(input("Enter the desired quantity = "))
dairy_choices[dairy_choice]=dairy_choice_quantity
dairy_choice_more = input("Continue shopping Dairy? [y/n] = ")
if dairy_choice_more=="y":
continue
elif dairy_choice_more=="n":
print("Your choices were:")
for key in dairy_choices:
print(key,":",dairy_choices[key])
break

Related

passing one function to another inside a for loop

New to programming. I wrote a program that Asks the user to enter the name, age and shoe size for four people and adds it to a dictionary. In fact, it works even when I don't use one function as an argument for another function. However, when i try to pass get_user_info() to store_user_info it doesnt work. I also tried to pass get_user_info to three separate variables and then passed these variables to store_user_info and it still didn't work. I am probably making a dumb error. Sorry its kind of a basic type of query but I just started learning programming. Any guidance is appreciated.
FOLLOWING CODE DOESN'T WORK: IT RUNS THE FOR LOOP BUT NEVER PROMPTS FOR THE INPUT FOR MORE THAN ONCE
#get user info
def get_user_info():
while True:
try:
user_input_name = (input("What is your name "))
user_input_age = int(input("How old are you "))
user_input_shoesize = float(input("What is your show size "))
break
except (ValueError,IndexError):
print('wrong selection or input')
return user_input_name,user_input_age,user_input_shoesize
#Store user info
def store_user_info(user_info):
user_information = {}
for i in range(3):
name, age, shoesize = user_info
user_information[name] = {"age" : age,"shoesize": shoesize}
print(user_information)
return user_information
=
store_user_info(get_user_info())
YET THE FOLLOWING WORKS and the loop works 3 times as expected:
#get user info
def get_user_info():
while True:
try:
user_input_name = (input("What is your name "))
user_input_age = int(input("How old are you "))
user_input_shoesize = float(input("What is your show size "))
break
except (ValueError,IndexError):
print('wrong selection or input')
return user_input_name,user_input_age,user_input_shoesize
#Store user info
def store_user_info():
user_information = {}
for i in range(3):
name, age, shoesize = get_user_info()
user_information[name] = {"age" : age,"shoesize": shoesize}
print(user_information)
return user_information
store_user_info()

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.

How to have a function return a variable that can be used in the rest of the program? Python 3

I'm trying to make a name generator function which will then return the parts of the name for use in the rest of my program. I put this inside of a function so that I could give the user the option to regenerate the name, instead of being stuck with the first one.
Putting the lists inside the function, and then being able to call the function again causes the random numbers to recalculate, so a new name is generated, but when I try to use "return" to move the variables outside of the function, I get an error.
There's probably a better way to do this, but I'm drawing a blank.
Here's what I have:
def naming():
titles = ["Sir", "Dr.", "Reverend", "Madam", "Master", 'Miss', 'Mrs.']
descriptors = ['sane', 'feelbe', 'cross-eyed', 'bow-legged', 'mad man', 'strange', 'frail', 'old', 'insane', 'cruel', 'bonkers', 'big-headed', 'knock-kneed', 'esquire', 'the huge']
name = input("What is your name?\n> ")
title = titles[random.randrange(0, 6)]
descriptor = descriptors[random.randrange(0,14)]
print(f"You shall be called {title} {name} the {descriptor}")
print("Does that work for you?")
choice = input("> ")
if choice == "yes":
return title, name, descriptor
if choice == "no":
print("Sorry, I'll try again.")
naming()
else:
print("Sorry I don't understand.")
naming()
I actually figured it out on my own. Here's what I did:
while True:
titles = ["Sir", "Dr.", "Reverend", "Madam", "Master", 'Miss', 'Mrs.']
descriptors = ['sane', 'feelbe', 'cross-eyed', 'bow-legged', 'mad man', 'strange', 'frail', 'old', 'insane', 'cruel', 'bonkers', 'big-headed', 'knock-kneed', 'scissor-handed', 'huge']
name = input("What is your name?\n> ")
title = titles[random.randrange(0, 6)]
descriptor = descriptors[random.randrange(0,14)]
print(f"You shall be called {title} {name} the {descriptor}")
print("Does that work for you?")
choice = input("> ")
if choice == "yes":
break
if choice == "no":
print("Sorry, I'll try again.")
else:
print("Sorry I don't understand.")
The code works fine, have you tried to atribute the return values to variables?
IE:
title, name, descriptor = naming()

Why While Loop does not work in my program?

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)

How to add a float to an amount in a class

I have a code to make a banking app. I need to make sure that the input can take in any number including decimals but not take in letters or other symbols.
Ive tried using a float instead of int
if selection == 1:
if initial_balance > 1:
print("\nAn account has already been opened. Please select another
option.")
print(menu)
else:
name = input("\nEnter the account owner's name: ")
# While loop to make sure user puts valid initial deposite
while True:
initial_balance = input("Enter your initial balanc: $")
try:
float(initial_balance)
except ValueError:
print("Sorry, Please deposit one or more dollars.")
continue
if initial_balance < 1:
print("Please deposit one or more dollars.")
continue
else:
balance += initial_balance
print("\nAccount owner: " + name)
account = BankAccount(initial_balance)
print("Initial balance: $ " + str(initial_balance))
print(menu)
break
break
expected:
enter an initial balance : 20.75
account owner: jimmy
initial balance: $20.75
actual:
enter an initial balance : $20.75
sorry please deposit one or more dollars
while True:
initial_balance = input("Enter your initial balanc: $")
try:
float(initial_balance)
You are applying float to the initial balance, but you are not updating the variable, so it remains in string format. Below is a fixed version.
while True:
initial_balance = input("Enter your initial balanc: $")
try:
initial_balance = float(initial_balance)

Resources