food = ["pizza", "tacos", "lasagna", "watermelon", "cookies"]
plate = ""
for dish in food:
print(dish)
fav_dish = input("Is this your favorite dish? Y/N: ")
if fav_dish == "Y" and food[-1]:
plate += dish
elif fav_dish == "Y":
plate += dish + ", "
print("I want " + plate +"!")
I am practicing my coding skills and I want the results to look like this.
I want pizza, tacos, and cake!
The results look like this:
pizza
Is this your favorite dish? Y/N: Y
tacos
Is this your favorite dish? Y/N: Y
lasagna
Is this your favorite dish? Y/N: N
watermelon
Is this your favorite dish? Y/N: N
cookies
Is this your favorite dish? Y/N: Y
I want pizzatacoscookies!
You can create the variable plate as a list where you put the favorite dishes and then use the "".join() function.
You put in the commas the separator you want, and in the parenthesis the list to join. In your case:
print("I want " + ", ".join(plate) + "!")
Make plate a list, and append to it in the loop. In the end, you can use the following, which will output the correct commas and words:
", ".join(plate)
first make a list of selection, then operate on that list. This code ignores the case of an empty selection list and can be left as an exercise.
selected = []
for dish in food:
select = input(f'Is [{dish}] your favorite dish? Y/N: ')
if select == 'Y':
selected.append(dish)
# since the second option ignores the dish, you can dis include it from the list
if len(selected) > 1: # do I need the word and at the end of the list
selected[-1] = f'and {selected[-1]}'
separator = ', ' # define pattern for joining a list
print('I want ', separator.join(selected), '!', sep='') # the `sep` keyword (normally a space) is printed between words
Related
I'm a freshman, and I want to make a bill that write out what I bought, quantity and how much total cash it cost.
customer = str(input("Customer's name: "))
print ("Welcome to our store")
print ("This is our products")
print ("orange 0.5$)
print ("Apple 1$)
print ("Grape 0.5$)
print ("Banana 0.5$)
chooseproducts= int(input("What do you want to buy: "))
For output example. Can you guys help me please.
BILL
Orange 5 2.5$
Apple 3 3$
Grape 2 1$
Total: 10 6.5$
First, your str(input(customer's name: )) code needs to be changed. input() calls need a string as the question, and also the apostrophe has Python think that it is the start of a string.
Also, when you are printing the costs, you need another closing quotation mark. When you are asking the user about what they want to buy, I suppose you want them to input the name of the fruit. Since you have the int() in the front, Python cannot turn a string like "orange" or "grape" into an integer. When people want to buy multiple things, however, they might only put one thing in.
I suppose that this isn't all your code, and you have the part where you calculate the cost. If I were to write this code, I would write it like the following:
customer = str(input("Customer's Name:"))
print ("Welcome to our store")
print ("This is our products")
print ("Orange 0.5$")
print ("Apple 1$")
print ("Grape 0.5$")
print ("Banana 0.5$")
prices = {"orange":0.5,"apple":1,"grape":0.5,"banana":0.5}# I added this so we can access the prices later on
#chooseproducts= int(input("What do you want to buy: "))
# The code below this is what I added to calculate the cost.
productnum = input("How many things do you want to buy: ") # This is for finding the number of different fruits the buyer wants
while not productnum.isdigit():
productnum = input("How many different products do you want to buy: ")
productnum = int(productnum)
totalprice = 0
totalfruit = 0
print(' BILL')
for i in range(productnum):
chosenproduct = input("What do you want to buy: ").lower()
while not chosenproduct in ['orange','apple','banana','grape']:
chosenproduct = input("What do you want to buy: ").lower()
fruitnum = input("How many of that do you want to buy: ")
while not fruitnum.isdigit():
fruitnum = input("How many of that do you want to buy: ")
fruitnum = int(fruitnum)
totalfruit += fruitnum
price = fruitnum * prices[chosenproduct]
totalprice += price
startspaces = ' ' * (11 - len(chosenproduct))
endspaces = ' ' * (5 - len(str(fruitnum)))
print(chosenproduct.capitalize() + startspaces + str(fruitnum) + endspaces + str(price) + '$')
print('Total: ' + str(totalfruit) + ' ' * (5 - len(str(totalprice))) + str(totalprice) + '$')
Please make sure you understand the code before copying it, thanks!
I'm writing a program for myself that makes a meal plan. I want to make the meal plan customizable, so I have this method:
def getRestrictedMeals(meals):
restrictions = []
mealsR = []
In the method, I ask the user questions that customize the code and I save their answer in a list (The getRestHelp method just saves some answers as boolean.):
print("Would you like only foods you aren't allergic to?")
print("1. Yes")
print("2. No")
user = int(input("Please choose an option: "))
print()
restrictions.append(getRestHelp(user))
print("Would you like only healthy foods?")
print("1. Yes")
print("2. No")
user = int(input("Please choose an option: "))
print()
restrictions.append(getRestHelp(user))
print("Would you like only Gluten Free foods?")
print("1. Yes")
print("2. No")
user = int(input("Please choose an option: "))
print()
restrictions.append(getRestHelp(user))
print("Would you like only Vegitarian foods?")
print("1. Yes")
print("2. No")
user = int(input("Please choose an option: "))
print()
restrictions.append(getRestHelp(user))
print("What is the longest cook time you want?")
print("Please enter 1000 for any cook time.")
user = int(input())
restrictions.append(user)
Next I grab the information from each meal:
facts = []
for x in meals:
facts.append(x.getAllergy())
facts.append(x.getHealthy())
facts.append(x.getGluten())
facts.append(x.getVegitarian())
facts.append(x.getCookTime())
This is where I'm stuck. I know I need to compare the lists the add the meal to mealR if it meets the restrictions, but I'm not sure how to do that without getting into a mess of 'if' statements. I can't make sure the lists match each other because if the user answers 'No' to a question, then any meal can be added.
If the user input is Allergies = No and Healthy = Yes, I want to avoid something like this (because I would have to go deeper and deeper for each parameter):
if(restrictions[0] == 0):
if(restrictions[1] == 0):
# I would continue going here for other parameters.
else:
if(x.getHealthy()):
# I would continue going here for other parameters.
mealsR[i] = x
i+=1
else:
if(!x.getAllergy()):
# I would continue going here for other parameters.
In this case I think the best approach would be to start with a list containing all of the meals. Then you start removing meals from the list according to each of the restrictions, no need for nested conditionals. It's a good application for filter too.
Use a list of questions for all the repetitive code:
choices = [
"Would you like only foods you aren't allergic to?",
"Would you like only healthy foods?",
"Would you like only Gluten Free foods?",
"Would you like only Vegitarian foods?"
]
restrictiosn = [None] * 5
for i, choice in enumerate(choices):
user = int(input(f"""{choice}
1. Yes
2. No
Please choice an option: """))
restrictions[i] = getRestHelp(user)
If I understand the question, you just need to see if a meal is valid given a set of restrictions. You can do this using a bunch of logical operators:
def isMealValid(meal, restrictions):
return (
not (restrictions[0] and meal.getAllergy())
and (not restrictions[1] or meal.getHealthy())
and not (restrictions[2] and meal.getGluten())
and (not restrictions[3] or meal.getVegitarian())
and meal.getCookTime() <= restrictions[4]
)
You may need to adjust depending on what the meal methods return. You can then use this function in a filter or list comprehension or whatever.
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
I am making a text adventure game, but it keeps running the 1st variation in the code, even though I specified both scenarios:
print("By Rishi Suresh 2021")
print('')
print('')
print("A S h o r t R i d e")
print('')
print('')
print(" P L A Y ( P )")
print('')
print('')
if input()=="p":
print('')
print('')
print("Your journey begins on a bleak day. It's cloudy, and the windows of your apartment amplify the pitter patter of the soft rain outside. Your clothes are strewn about. You hear the landline ringing. You also see a diary.")
print('')
print('')
if input("What do you do? Do you pick up the diary (A) or answer the landline (B)? ")=="b"or "B":
print("")
print("")
print("You pick up the landline, and hear a voice on the other end. It is scratchy, and tells you to come to the London Underground. You pick up your clothes, a empty whiskey bottle and some glasses, and dress. You head outside. ")
elif input() == "A" or "a":
print("The diary reads:")
print('')
print('')
print("Dear Diary,")
print("Tommorow's the day. We have all the trucks ready, all the Tommy's, all the big men. This stop and shop will be the sucess of the century.")
print("The landline rings again. You pick up the landline, and hear a voice on the other end. It is scratchy, and tells you to come to the London Underground. You pick up your clothes, a empty whiskey bottle and some glasses, and dress. You head outside.")
This clause:
if input("What do you do? Do you pick up the diary (A) or answer the landline (B)? ")=="b"or "B":
will always pass, because "B" (and "A" or any non-empty string, for that matter) is a truthy value:
if "B":
print("Hey!")
if "A":
print("I pass, too!")
if "A really, really, really long string that goes on...":
print("So do I!")
if "":
print("I'll never print.")
This means if <anything> or "B": will always pass (provided evaluation of <anything> doesn't throw an exception or change control flow), because the second part of the or is satisfied. The == operator is binding to input (i.e. input(...) == "b" or "B" is (input(...) == "b") or "B"); you can't express "the result is a member of some set" in this way (i.e. x == 1 or 2 is (x == 1) or 2, not x in (1, 2)).
Assign the result of your input calls to some variable result, and then test result in ("b", "B") or result.lower() == "b" (ditto for the second case).
by asking for another input in the elif you are asking for another user input discarding the user's previous input,plus or "a" would cause the statment to always be true since you are not checking if the input is equal to "a", this would be better:
print("")
print('')
print('')
print("")
print('')
print('')
print(" ")
print('')
print('')
if input()=="p":
print('')
print('')
print("")
print('')
print('')
option=input(" a or b")
if option =="b"or option =="B":
print("")
print("")
print("")
elif option == "A" or option == "a":
print("The diary reads:")
print('')
print('')
print("Dear Diary,")
print("")
print("")
I started learning python few days ago and im looking to create a simple program that creates conclusion text that shows what have i bought and how much have i paid depended on my inputs. So far i have created the program and technically it works well. But im having a problem with specifying the parts in text that might depend on my input.
Code:
apples = input("How many apples did you buy?: ")
bananas = input("How many bananas did you buy?: ")
dollars = input("How much did you pay: ")
print("")
print("You bought " +apples+ " apples and " +bananas+ " bananas. You paid " +dollars +" dollars.")
print("")
print("")
input("Press ENTER to exit")
input()
So the problem begins when input ends with 1. For example 21, 31 and so on, except 11 as the conclusion text will say "You bought 41 apples and 21 bananas...". Is it even possible to make "apple/s", "banana/s", "dollar/s" as variables that depend on input variables?
Where do i start with creating variable that depends on input variable?
How do i define the criteria for "banana" or "bananas" by the ending of number? And also exclude 11 from criteria as that would be also "bananas" but ends with 1.
It seems like this could be an easy task but i still can't get my head around this as i only recently started learning python. I tried creating IF and Dictionary for variables but failed.
You would want to have an if statement that checks whether the specified input falls above or equal to 1. This is simple to do and requires an if statement.
A simple way of doing this would be:
if apples == '1':
strApples = str(apples, 'apple')
else:
strApples = str(apples, 'apples')
...and so forth for all the other fruits.
You would then print your conclusion with:
print("You bought", strApples, "and", strBananas + ". You paid " +dollars +" dollars.")
Not the best way of displaying this though.
I would go for a line by line conclusion:
print("You bought: ")
if apples == '1':
print("1 apple")
else:
print(apples, "apples")
if bananas == '1':
print("1 banana")
else:
print(bananas, "bananas")
print("You paid", dollars, "dollars")
EDIT:
I think I now understand that you want every number ending in '1', that is not '11' to be displayed as singular.
This can be done using the following:
apples = input("How many apples did you buy?: ")
bananas = input("How many bananas did you buy?: ")
dollars = input("How much did you pay: ")
print("You bought: ")
if int(apples[-1]) == 1 and int(apples) != 11:
print(apples, "apple")
else:
print(apples, "apples")
if int(bananas[-1]) == 1 and int(bananas) != 11:
print(bananas, "banana")
else:
print(bananas, "bananas")
print("You paid", dollars, "dollars")
Looks like you might be interested by functions.
For example:
def pluralize(x):
for i in ["a", "e", "i", "o", "u"]:
# Is vowel
if x.endswith(i):
return x+"s"
# Is consonant
return x
print(pluralize("Hello World"))
Note: you may want to improve this function to handle things like ending with y, ending with x or s and so on.
EDIT:
https://pastebin.com/m2xrUWx9
this is a pretty basic question but here goes:
I would like to create an array and then would like to compare a user input to those elements within the array.
If one element is matched then function 1 would run. If two elements were matched in the array the an alternative function would run and so on and so forth.
Currently i can only use an IF statement with no links to the array as follows:
def stroganoff():
print ("You have chosen beef stroganoff")
return
def beef_and_ale_pie():
print ("You have chosen a beef and ale pie")
return
def beef_burger():
print ("You have chosen a beef burger")
return
ingredients = ['beef','mushrooms','ale','onions','steak','burger']
beef = input("Please enter your preferred ingredients ")
if "beef" in beef and "mushrooms" in beef:
stroganoff()
elif "beef" in beef and "ale" in beef:
beef_and_ale_pie()
elif "beef" in beef and "burger" in beef:
beef_burger()
As said, this is basic stuff for some of you but thank you for looking!
Since you only can work with IF statements
beef=input().split()
#this splits all the characters when they're space separated
#and makes a list of them
you can use your "beef" in beef and "mushrooms" in beef and it should run as you expected it to
So I understand your question such that you want to know, how many of your ingredients are entered by the user:
ingredients = {'beef','mushrooms','ale','onions','steak','burger'}
# assume for now the inputs are whitespace-separated:
choices = input("Please enter your preferred ingredients ").split()
num_matches = len(ingredients.intersection(choices))
print('You chose', num_matches, 'of our special ingredients.')
You may do something like:
# Dictionary to map function to execute with count of matching words
check_func = {
0: func_1,
1: func_2,
2: func_3,
}
ingredients = ['beef','mushrooms','ale','onions','steak','burger']
user_input = input()
# Convert user input string to list of words
user_input_list = user_input.split()
# Check for the count of matching keywords
count = 0
for item in user_input_list:
if item in ingredients:
count += 1
# call the function from above dict based on the count
check_func[count]()