The variable or the types and the costs:
pasta_types = "Lasagne, Spaghetti, Macaroni, Cannelloni, Ravioli, Penne, Tortellini, Linguine, Farfalle, Fusilli"
pasta_costs = "6.00, 4.00, 3.15, 8.50, 9.00, 3.15, 5.00, 4.00, 4.25, 4.75"
The function to see if the in put has a type of pasta that is in the varaible:
def inventory(pt):
return(pt.title() in pasta_types)
Input:
type = input('What pasta would you like: Lasagne, Spaghetti, Macaroni, Cannelloni, Ravioli, Penne, Tortellini, Linguine, Farfalle, and Fusilli ')
Calling Function:
have = inventory(type)
How do I find out what number of the argument that was chosen?
Here's an example of doing something like that which builds and uses a dictionary that associates the name of each pasta type with its cost:
pasta_types = "Lasagne, Spaghetti, Macaroni, Cannelloni, Ravioli, Penne, Tortellini, " \
"Linguine, Farfalle, Fusilli"
pasta_costs = "6.00, 4.00, 3.15, 8.50, 9.00, 3.15, 5.00, 4.00, 4.25, 4.75"
# Create a dictionary associating (lowercase) pasta name to its (float) cost.
inventory = dict(zip(pasta_types.lower().replace(' ', '').split(','),
map(float, pasta_costs.replace(' ', '').split(','))))
## Display contents of dictionary created.
#from pprint import pprint
#print('inventory dictionary:')
#pprint(inventory)
while True:
pasta_type = input('What pasta would you like: ' + pasta_types + '?: ')
if pasta_type.lower() in inventory:
break # Got a valid response.
else:
print('Sorry, no {!r} in inventory, please try again\n'.format(pasta_type))
continue # Restart loop.
print('{} costs {:.2f}'.format(pasta_type, inventory[pasta_type]))
Related
As a beginner I have a few doubts about this project I'm working on
The general idea of this project is to allow users to be able to detect a certain disease through symptoms
I want the program to match the input with the provided lists and pick out the best match and print output.
The problem here is that the list provided with symptoms of diseases shares few common symptoms with each other. So the program must evaluate the entire set of lists and print the best match
I tried something
import re
input1 = input("Enter Your Symptoms: ".lower())
x = re.split("\s", input1) #used to seprate the words in the string and create a list out of it
# Symptoms
cadsym = ['chest pain' , 'body pain' , 'falling sick' , 'feeling faint' , 'shortness of breath']
vhdsym = ['swollen ankles' , 'fanting' , 'shortness of breath']
hasym = ['racing heartbeat', 'slow heartbeat', 'chest pain' , 'anxiety', 'sweating']
mhasym = ['cold sweat', 'heartburn', 'sudden dizziness', 'discomfort in joints']
jsym = ['itching', 'abdominal pain', 'weight loss', 'yellow eyes' , 'yellow nails', 'vomiting']
cpsym = ['rashes on skin' , 'fever' , 'sore throat' , 'brown spots' , 'itching']
msym = ['fever', 'runny nose' , 'sneezing' , 'pink eye' , 'skin rash', 'diarrhoea']
dsym = ['Eye pain' , 'fever' , 'muscle pain' , 'nausea' , 'joint pain', 'rash on thigh']
masym = ['pain in muscle' , 'pain in abdomin' , 'Night sweat' , 'shivering', 'fast heart rate' , 'mental confusion']
tcsym = ['chest pain','Night sweats','shortness of breath','blood cough']
disym = ['increase thirst','frequent urination','hunger','blurred vision','slow healing']
pnsym = ['fever','chills','sharp pain in chest','clammy skin']
htsym = ['nose bleeds','dizziness','morning headaches','irregular heart rhythms','vision changes','buzzing in the ears']
emsym = ['lot of mucus','tight chest','whistle sound while breathing']
cysym = ['bluish colour in sikn',' lips','nail beds']
hysym = ['itchy','red and watery eyes','rod of mouth being itchy','runny or blocked nose']
ansym = ['unusual headache','memory loss','slurred speech','forgotten words','trouble in walking','trouble in moving arms','trouble in moving legs']
hcsym = ['anxiety','shortness of breath','headache','daytime sleep even after sleeping a lot at night','daytime sluggishness']
bcsym = ['sleeping difficulty','sore throat','chest pressure','shortness of breath','runny nose']
asym = ['wheezing','anxiety','early awakening','shortness of breath at night','cough','throat irritation']
if x in cadsym:
print("You Might Have Coronary Artery Disease")
elif x in vhdsym:
print("You Might Have Vulvar Heart Disease")
elif x in hasym:
print("You Might Have Heart Arrhythmia ")
elif x in mhasym:
print("You Might Have Minor Heart Attack")
elif x in jsym:
print("You Might Have Jaundice")
elif x in cpsym:
print("You Might Have Chickenpox")
elif x in msym:
print("You Might Have Measles")
elif x in dsym:
print("You Might Have Dengue")
elif x in masym:
print("You Might Have Malaria")
elif x in tcsym:
print("You Might Have Tuberculosis")
elif x in disym:
print("You Might Have Diabetes")
elif x in pnsym:
print("You Might Have Pneumonia")
elif x in htsym:
print("You Might Have Hypertension")
elif x in emsym:
print("You Might Have Emphysema")
elif x in cysym:
print("You Might Have Cyanosis")
elif x in hysym:
print("You Might Have Hay Fever")
elif x in ansym:
print("You Might Have Anoxia")
elif x in hcsym:
print("You Might Have Hypercapnia")
elif x in bcsym:
print("You Might Have Bronchitis")
elif x in asym:
print("You Might Have Asthama")
else:
print("Not Registered")
As the response for each case is the same sentence with just the disease name changing, why not use a dict where the key is the disease name and the value is the list of symptoms.
A bigger challenge here might be that many of the symptoms include spaces, so any split of the full input string is going to prevent you from finding matches. For example, if the user enters shortness of breath, then x is going to contain ['shortness', 'of', 'breath']
There are two possible work arounds for this:
Ask the user to input one symptom at a time and put all of the symptoms into a list
Split of the symptom lists to all be single words only, but that's going to get a lot more false positives.
Here's my solution using sets, prompting the user for separate symptoms, and putting all of the disease data into a single constant dictionary.
# Use a set for user symptoms to prevent duplicates, and so we can compare
# against our database easily later.
user_symptoms = set()
print("Enter your symptoms one at a time. Leave the entry blank to stop.")
while True:
# .lower() needs to be OUTSIDE the input() call,
# otherwise it changes the prompt, not the input
x = input("Enter a symptom: ").lower()
if len(x):
user_symptoms.add(x)
else:
break
# Dict of diseases with symptoms as sets.
# We can use sets instead of lists as ordering is not important.
DIAGNOSES = {
"coronary artery disease": {'chest pain', 'body pain', 'falling sick', 'feeling faint', 'shortness of breath'},
"vulvar heart disease": {'swollen ankles', 'fanting', 'shortness of breath'},
"heart arrhythmia": {'racing heartbeat', 'slow heartbeat', 'chest pain', 'anxiety', 'sweating'},
"minor heart attack": {'cold sweat' 'heartburn', 'sudden dizziness', 'discomfort in joints'},
"jaundice": {'itching', 'abdominal pain', 'weight loss', 'yellow eyes', 'yellow nails', 'vomiting'},
"chickenpox": {'rashes on skin', 'fever', 'sore throat', 'brown spots', 'itching'},
"measles": {'fever', 'runny nose', 'sneezing', 'pink eye', 'skin rash', 'diarrhoea'},
"dengue": {'Eye pain', 'fever', 'muscle pain', 'nausea', 'joint pain', 'rash on thigh'},
"malaria": {'pain in muscle', 'pain in abdomin', 'Night sweat', 'shivering', 'fast heart rate', 'mental confusion'},
"tuberculosis": {'chest pain', 'Night sweats', 'shortness of breath', 'blood cough'},
"diabetes": {'increase thirst', 'frequent urination', 'hunger', 'blurred vision', 'slow healing'},
"pneumonia": {'fever', 'chills', 'sharp pain in chest', 'clammy skin'},
"hypertension": {'nose bleeds', 'dizziness', 'morning headaches', 'irregular heart rhythms', 'vision changes', 'buzzing in the ears'},
"emphysema": {'lot of mucus', 'tight chest', 'whistle sound while breathing'},
"cyanosis": {'bluish colour in sikn', ' lips', 'nail beds'},
"hay fever": {'itchy', 'red and watery eyes', 'rod of mouth being itchy', 'runny or blocked nose'},
"anoxia": {'unusual headache', 'memory loss', 'slurred speech', 'forgotten words', 'trouble in walking', 'trouble in moving arms', 'trouble in moving legs'},
"hypercapnia": {'anxiety', 'shortness of breath', 'headache', 'daytime sleep even after sleeping a lot at night', 'daytime sluggishness'},
"bronchitis": {'sleeping difficulty', 'sore throat', 'chest pressure', 'shortness of breath', 'runny nose'},
"asthma": {'wheezing', 'anxiety', 'early awakening', 'shortness of breath at night', 'cough', 'throat irritation'},
}
# Find any possible matches using set.intersection(). Put matches in a list.
matches = []
for dx, dx_symptoms in DIAGNOSES.items():
if user_symptoms.intersection(dx_symptoms):
matches.append(dx)
# Now print all the possible matches.
for match in matches:
print(f"You might have {match}.")
else:
print("No matching symptoms registered.")
Example run:
Enter your symptoms one at a time. Leave the entry blank to stop.
Enter a symptom: chest PAIN
Enter a symptom: anxiety
Enter a symptom: hunger
Enter a symptom: SORE throat
Enter a symptom:
You might have coronary artery disease.
You might have heart arrhythmia.
You might have chickenpox.
You might have tuberculosis.
You might have diabetes.
You might have hypercapnia.
You might have bronchitis.
You might have asthma.
I am a beginner in programming and I'm working on the projects in Automate the Boring Stuff with Python, In the book there is a project to create a sandwich, then return the total cost. I want to add to my program by providing an itemized receipt. For example, if I put in an order for 1 sandwich with wheat and chicken and 3 sandwiches with white and turkey, the receipt should show something like this (I will format it better when I figure it out):
1 sandwich ---3.5
wheat, chicken
3 sandwich ---10.5.
white, turkey
Total --- 14.00
My challenge is storing the different sandwich orders into different variables and printing them out at the end.
My code below:
menu = {
'wheat': 1.5, 'white': 1, 'sourdough': 2,
'chicken': 2, 'turkey': 2.5, 'ham': 2, 'tofu': 3,
'cheddar': 0.5, 'mozzarella': 0.25, 'american': 0.5,
'mayo': 0.25, 'mustard': 0.25, 'lettuce': 0.5, 'tomato': 0.5
}
total = 0.0
subtotal = 0.0
while True:
order = {}
print('What bread would you like?')
order['bread'] = pyip.inputChoice(['wheat', 'white', 'sourdough'])
print('How about for your protein?')
order['protein'] = pyip.inputChoice(['chicken', 'turkey', 'ham', 'tofu'])
wantCheese = pyip.inputYesNo('Would you like cheese on the sandwich?')
if wantCheese == 'yes':
order['cheese'] = pyip.inputChoice(['cheddar', 'mozzarella', 'american'])
wantToppings = pyip.inputYesNo('Would you like to add extra toppings?')
if wantToppings == 'yes':
while True:
order['side'] = pyip.inputChoice(['mayo', 'mustard', 'lettuce', 'tomato'])
anotherTopping = pyip.inputYesNo('Would you like another topping?')
if anotherTopping == 'no':
break
orderNumber = pyip.inputInt('How many of those sandwiches would you like? ', min = 1)
for choice in order:
if order[choice] in menu.keys():
subtotal += menu[order[choice]]
total *= orderNumber
total += subtotal
subtotal = 0
anotherOrder = pyip.inputYesNo('Would you like to order another sandwich?')
if anotherOrder == 'no':
break
print(total)
Adjust the following as you see fit. FYI, while coding this up I had "let's get this to work" in mind as opposed to "let's make this as efficient as possible". Moreover, you should format the receipt however you like.
Importantly, I created a list called orders just before the while that will be used to store orders. The form of the elements of orders will be 3-tuples where the first element of the 3-tuple records orderNumber, the third element records the subtotal, and the second element is an order dictionary, just as in your original code, except order["side"] will be a list as this allows for multiple additional toppings to be added. For the sample output below, orders is
[(2, {'bread': 'wheat', 'protein': 'chicken', 'cheese': 'cheddar', 'side': ['mustard', 'lettuce']}, 9.5), (1, {'bread': 'sourdough', 'protein': 'turkey', 'side': []}, 4.5)]
As you can see, there are 2 orders of 'wheat', 'chicken', 'cheddar', 'mustard', 'lettuce' (subtotal 9.5) and 1 order of 'sourdough', 'turkey' (subtotal 4.5).
I hope this helps. Any questions please let me know.
import pyinputplus as pyip
menu = {'wheat': 1.5, 'white': 1, 'sourdough': 2,
'chicken': 2, 'turkey': 2.5, 'ham': 2, 'tofu': 3,
'cheddar': 0.5, 'mozzarella': 0.25, 'american': 0.5,
'mayo': 0.25, 'mustard': 0.25, 'lettuce': 0.5, 'tomato': 0.5
}
orders = []
while True:
order = {}
# choose bread
print("What bread would you like?")
order['bread'] = pyip.inputChoice(['wheat', 'white', 'sourdough'])
# choose protein
print("How about for your protein?")
order['protein'] = pyip.inputChoice(['chicken', 'turkey', 'ham', 'tofu'])
# choose cheese
wantCheese = pyip.inputYesNo("Would you like cheese on the sandwich?")
if wantCheese == 'yes':
order['cheese'] = pyip.inputChoice(['cheddar', 'mozzarella', 'american'])
# choose extra toppings
order["side"] = []
wantToppings = pyip.inputYesNo("Would you like to add extra toppings?")
if wantToppings == 'yes':
while True:
order["side"].append(pyip.inputChoice(
['mayo', 'mustard', 'lettuce', 'tomato']))
anotherTopping = pyip.inputYesNo("Would you like another topping?")
if anotherTopping == 'no':
break
# order number
orderNumber = pyip.inputInt(
"How many of those sandwiches would you like?", min = 1)
# subtotal
subtotal = sum(menu[order[key]] for key in order if key != 'side')
subtotal += sum(menu[j] for j in order['side'])
subtotal *= orderNumber
# add 3-tuple to orders list
orders.append((orderNumber, order, subtotal))
# another order?
anotherOrder = pyip.inputYesNo("Would you like to order another sandwich?")
if anotherOrder == 'no':
break
# add subtotals to form total
total = sum(order[2] for order in orders)
# print orders (for programmer use)
print(f"\nOrders: {orders}")
# print receipt
print(f"\nReceipt\n")
for order in orders:
print(f"{order[0]} sandwich ---{order[2]}")
print(" ", end = "")
for key in order[1]:
if isinstance(order[1][key], list):
for x in order[1][key]:
print(x, end = ", ")
else:
print(order[1][key], end = ", ")
print("\n")
print(f"Total --- {total}")
Sample output:
Receipt
2 sandwich ---9.5
wheat, chicken, cheddar, mustard, lettuce,
1 sandwich ---4.5
sourdough, turkey,
Total --- 14.0
I was supposed to insert new items to a dictionary, and the new items would be decided by the user input. I have tried three differents things (the ones marked as comments), but none is working. Does anyone know how to fix it?
butikk = {"melk": 14.9, "broed": 24.9, "yoghurt": 12.9, "pizza": 39.9}
print(butikk)
ny_vare = str(input("Skriv inn en matvare og prisen: "))
ny_vare_pris = float(input("Hvor mye koster varen? "))
ny_vare1 = str(input("Skriv inn en matvare: "))
ny_vare1_pris = float(input("Hvor mye koster varen? ")
#butikk.append(ny_vare)
#butikk.append(ny_vare1)
#butikk[ny_vare] = ny_vare_pris
#butikk[ny_vare1] = ny_vare1_pris
#butikk.update(ny_vare : ny_vare_pris)
#butikk.update(ny_vare1 : ny_vare1_pris)
print(butikk)
Okay, so your problem is solved. To be noted, you had done 2 things wrong here.
First, you missed a bracket on line 8 and
Second one is that you should apply {} to update the dictionary.
Let me show you the correct code:
butikk = {
"melk": 14.9,
"broed": 24.9,
"yoghurt": 12.9,
"pizza": 39.9
}
ny_vare = input("Skriv inn en matvare og prisen: ")
ny_vare_pris = float(input("Hvor mye koster varen? "))
ny_vare1 = input("Skriv inn en matvare: ")
ny_vare1_pris = float(input("Hvor mye koster varen? "))
butikk.update({ny_vare: ny_vare_pris})
butikk.update({ny_vare1: ny_vare1_pris})
print(butikk)
Now you will get your desired output.
I'm working on assignment for my Python 3 programming class. It's a database to look up movies and the year they came out. However, I'm having a hard time printing the output without extra brackets and quotes:
# Build a dictionary containing the specified movie collection
list_2005 = [["Munich", "Steven Spielberg"]]
list_2006 = [["The Departed", "Martin Scorsese"], ["The Prestige", "Christopher Nolan"]]
list_2007 = [["Into the Wild", "Sean Penn"]]
movies = {
'2005': list_2005,
'2006': list_2006,
'2007': list_2007
}
# Prompt the user for a year
# Displaying the title(s) and directors(s) from that year
user_year = str(input("Enter a year between 2005 and 2007:\n"))
if user_year in movies:
for name in movies[user_year]:
print("%s" % ', '.join(name))
print()
elif user_year not in movies:
print("N/A")
# Display menu
user_choice = ''
while user_choice != 'q':
print("MENU\nSort by:\ny - Year\nd - Director\nt - Movie title\nq - Quit")
print()
user_choice = str(input("Choose an option:\n"))
if user_choice == 'y':
for key, value in sorted(movies.items()):
print("%s:" % key)
print(" %s" % ''.join(str(movies[key])))
# Carry out the desired option: Display movies by year,
# display movies by director, display movies by movie title, or quit
I would like this output to be:
2005:
Munich, Steven Spielberg
2006:
The Prestige, Christopher Nolan
The Departed, Martin Scorsese
etc.
The output I am getting:
2005:
['Munich', 'Steven Spielberg']
2006:
[['The Prestige', 'Christopher Nolan'], ['The Departed', 'Martin Scorsese']]
etc.
Replace
print(" %s" % ''.join(str(movies[key])))
with
print("\t" + '\n\t'.join("{}, {}".format(m[0], m[1]) for m in movies[key]))
I am learning python so this question may be a simple question, I am creating a list of cars and their details in a list as bellow:
car_specs = [("1. Ford Fiesta - Studio", ["3", "54mpg", "Manual", "£9,995"]),
("2. Ford Focous - Studio", ["5", "48mpg", "Manual", "£17,295"]),
("3. Vauxhall Corsa STING", ["3", "53mpg", "Manual", "£8,995"]),
("4. VW Golf - S", ["5", "88mpg", "Manual", "£17,175"])
]
I have then created a part for adding another car as follows:
new_name = input("What is the name of the new car?")
new_doors = input("How many doors does it have?")
new_efficency = input("What is the fuel efficency of the new car?")
new_gearbox = input("What type of gearbox?")
new_price = input("How much does the new car cost?")
car_specs.insert(len(car_specs), (new_name[new_doors, new_efficency, new_gearbox, new_price]))
It isnt working though and comes up with this error:
Would you like to add a new car?(Y/N)Y
What is the name of the new car?test
How many doors does it have?123456
What is the fuel efficency of the new car?23456
What type of gearbox?234567
How much does the new car cost?234567
Traceback (most recent call last):
File "/Users/JagoStrong-Wright/Documents/School Work/Computer Science/car list.py", line 35, in <module>
car_specs.insert(len(car_specs), (new_name[new_doors, new_efficency, new_gearbox, new_price]))
TypeError: string indices must be integers
>>>
Anyones help would be greatly appreciated, thanks.
Just append the tuple to the list making sure to separate new_name from the list with a ,:
new_name = input("What is the name of the new car?")
new_doors = input("How many doors does it have?")
new_efficency = input("What is the fuel efficency of the new car?")
new_gearbox = input("What type of gearbox?")
new_price = input("How much does the new car cost?")
car_specs.append(("{}. {}".format(len(car_specs) + 1,new_name),[new_doors, new_efficency, new_gearbox, new_price]))
I would use a dict to store the data instead:
car_specs = {'2. Ford Focous - Studio': ['5', '48mpg', 'Manual', '\xc2\xa317,295'], '1. Ford Fiesta - Studio': ['3', '54mpg', 'Manual', '\xc2\xa39,995'], '3. Vauxhall Corsa STING': ['3', '53mpg', 'Manual', '\xc2\xa38,995'], '4. VW Golf - S': ['5', '88mpg', 'Manual', '\xc2\xa317,175']}
Then add new cars using:
car_specs["{}. {}".format(len(car_specs)+1,new_name)] = [new_doors, new_efficency, new_gearbox, new_price]
You are not setting the first element go your tuple correctly. You are appending the name to the length of car specs as you expect.
Also new_name is as string, when you do new_name[x] your asking python for the x+1th character in that string.
new_name = input("What is the name of the new car?")
new_doors = input("How many doors does it have?")
new_efficency = input("What is the fuel efficency of the new car?")
new_gearbox = input("What type of gearbox?")
new_price = input("How much does the new car cost?")
car_specs.insert(str(len(car_specs + 1))+'. - ' + name, [new_doors, new_efficency, new_gearbox, new_price])