Adding values from a list based on user input - python

I am trying to take a list of items, each with different amounts and calculate how many of all of the items are needed, based on user input.
For example, a grocery list for a dinner based on how many guest are coming. (5 carrots, 3 onions, 4 peppers, 2 hot dogs, and 1 pound of hamburger) per guest. So the user will input how many guests will be attending and and the item counts will be multiplied based on the input and print that value.
I am new to python, although I know this is a simple problem and I have covered this before, I have spent the past two days trying to get ready for a test and think that I am over-thinking it, because I cant even come close -- so frustrating knowing that once I see it, or something similar it will click. Any help is appreciated. I know that syntax is wrong and everything is messed up, I just typed this up real quick to illustrate a general idea of what I am trying to do. Thanks again.
groc_list= int(input('Enter number of students: ')
carrots= (groc_list* 5)
onions= (groc_list* 3)
peppers= (groc_list* 4)
hot_dogs= (groc_list* 2)
hamburger= (groc_list* 1)
print('You will need', carrots, 'onions', peppers, 'hot dogs', pounds of hamburger')

This works:
groc_list = int(input("Enter number of students: "))
carrots = groc_list * 5
onions = groc_list * 3
peppers = groc_list * 4
hot_dogs = groc_list * 2
hamburger = groc_list * 1
print(
f"You will need {carrots} carrots, {onions} onions, {peppers} peppers, {hot_dogs} hot dogs, {hamburger} pounds of hamburger."
)
Probably this will suit you more:
students = int(input("Enter number of students: "))
grocery_multiplier = {
'carrots': 5,
'onions': 3,
'peppers': 4,
'hot dogs': 2,
'hamburger': 1,
}
texts = []
for field, multiplier in grocery_multiplier.items():
texts.append(f"{multiplier * students} {field}")
print('You will need ' + ', '.join(texts))
When you need to add, remove items to be calculated.
Result:
Enter number of students: 5
You will need 25 carrots, 15 onions, 20 peppers, 10 hot dogs, 5 hamburger

Check if this works. Feel free to ask any question:)
groc_list= int(input('Enter number of students: '))
carrots = (groc_list * 5)
onions= (groc_list* 3)
peppers= (groc_list* 4)
hot_dogs= (groc_list* 2)
hamburger= (groc_list* 1)
print("You will need" , str(carrots)+" " + "carrots ", str(onions)+" "+"onions ", str(peppers)+" "+ "peppers ",str(hot_dogs)+" "+"hot_dogs ", str(hamburger)+" "+ "pounds of hamburger")```

syntax error on line 1, paranthesis was not closed properly.
groc_list= int(input('Enter number of students: '))
carrots= groc_list* 5
onions= groc_list* 3
peppers= groc_list* 4
hot_dogs= groc_list* 2
hamburger= groc_list* 1
print(f'carrots-{carrots}, onions-{onions},peppers-{peppers},hotdogs-{hot_dogs}, hamburgers-{hamburger} ')

In my opinion, you should use a dictionary to track all the variabiles, and use a func. You also miss a round brackets on the first line. Also, at the end, on print, use f. Here is the code that I think is correct
num = int(input('Number of students: '))
mol_dict = {'carrots':5,'onions':3.........)
res_dict = {}
for i in mol_dict:
res_dict[i] = mol_dict[i] * num
print(f'You will need {res_dict['carrots']}.........')
This is more readable, more correct and scalable.

Your code was basically nearly complete. Made a few minor tweaks:
groc_list = int(input('Enter number of students: '))
carrots = groc_list
onions = groc_list* 3
peppers = groc_list* 4
hot_dogs = groc_list* 2
hamburger = groc_list
print('You will need', carrots, 'carrots,', onions, 'onions,', peppers, 'peppers,', hot_dogs, 'hot dogs and', hamburger, 'hamburgers.')

Related

How to create a shopping cart calculator

I am writing a program which takes one input (a number of product) and gives one output (price of the product):
Drink: $2.25
6-pack: $10
25% discount if more than $20
((Sorry if my code is really bad I'm a newbie))
print( "How many drinks do you want?" )
drinks = input( "Enter number: ")
total = int(drinks)
single = 2.25
six = 10
single * 6 = six
if total > 20:
total * 0.75
print( "That will be a total of: ", total, "dollars")
I'm confused how to make it so that, after I have changed the input value to an int, how can I separate and calculate it based on my pricing criteria. Please help?
I assume you're looking for something like this. Hope it helps! I tried to keep your variable names the same so it would make some kind of sense to you. The line I commented out is an error.
drinks = input("How many drinks do you want?")
drinks = int(drinks)
total = 0
single = 2.25
six = 10
sixPacks = drinks // 6
singles = drinks % 6
# single * 6 = six
total += six * sixPacks
total += single * singles
if total > 20:
total *= 0.75
print( "That will be a total of: {} dollars".format(round(total, 2)))
Okay so let's break it down logically.
You first take in the input number of drinks the person wants. You're assigning it to total right away, when you should actually assign it to a variable that holds the number of drinks.
You should then multiply the number of drinks by the cost per drink. You also need to check if the number of drinks are a multiple of 6 so that you can price them by the six pack.
Once you have calculated this check if the total < 20.
Since this is a homework problem. I will encourage you to try to solve it with this approach.

Using a list that is inside a variable

This problem I'm having is that I cant use that list I have just created and stored inside current_pizza_list.
pizza_1 = ['8.00','Pepperoni']
print('Input 1 for ', pizza_1[1])
current_pizza = input('What pizza would you like:')
current_pizza_list = ('pizza_' + str(current_pizza) + '[1]')
pizza_ammount = input('How many', str(current_pizza_list) ,' pizzas would you like:')
num = 5
pizza_name = 'pizza_' + str(num)
print('Our pizza choices are ' + pizza_name + '!')
#What you created above is a variable. That is not a list. Below is a list:
#pizzas = ['pepperoni', 'extra cheese', 'cheese', 'veggie']
current_pizza = input('What pizza would you like: ')
current_pizza_name = ('pizza_' + str(current_pizza) + '[1]')
pizza_ammount = int(input('How many ' + current_pizza_name + "'s would you like?: "))
print('You would like ' + str(pizza_ammount) + ' ' + current_pizza_name + ' pizzas!')
Here is your output:
Our pizza choices are pizza_5!
What pizza would you like: 5
How many pizza_5[1]'s would you like?: 10
You would like 10 pizza_5[1] pizzas!
Now you've stated that you want a list, but in your example there is not list, so i'm not sure what you mean, but below is an example of a list of pizzas and attaching a number to each pizza after we access it:
pizza_list = [1, 2, 3, 4, 5, 6, 7, 8]
print('Our pizza choices are: ')
for pizza in pizza_list:
print('\t' + str(pizza))
pizza_choice = int(input('Which pizza would you like to select?: '))
if pizza_choice in pizza_list:
current_pizza = 'pizza_' + str(pizza_choice)
else:
print('We do not have that pizza')
pizza_amount = int(input('How many ' + current_pizza + "'s would you like?: "))
print('You would like ' + str(pizza_amount) + ' ' + current_pizza + " pizza's.")
Above we have a list, which I do not see in your code example called pizza list. If the user selects a pizza within the list we can attach that pizza number to the end of the pizza_ string. We then ask the user how many pizza's they want. The pizza_list can server as your list. Here is the output:
Our pizza choices are:
1
2
3
4
5
6
7
8
Which pizza would you like to select?: 5
How many pizza_5's would you like?: 20
You would like 20 pizza_5 pizza's.
I'd suggest
pizza_name = 'pizza_%d' % num
Here the digit will be added to the string.(assuming num is an integer)
The same thing can be done for floats and strings as well with minor modifications:
result = 'format_string goes here: %05.2f' % 2.123
foo = 'bar_%s' % 'baz'
The one with the float probably needs a little explanation: the %05.2f means that the float will be formatted to have 5 places in total, padded with leading zeros and 2 decimal digits after the dot.

How do I use user input to determine how the program works?

this is my first post here on stackoverflow and this is my first time using Python to make a program. I want to make a program to ask the user to input names of students then be able to add more information to that student as the program continues to run. Ideally I want the user to choose how many students there are, choose how many rounds are played, give them names, assign scores, and at the end output the final score and the averages of each student.
This is what I have currently:
name_students = list()
num_students = input("How many students?: ")
competitionRounds = input("How many rounds: ")
score_students = list ()
myList = name_students
for i in range(1, int(num_students) + 1):
name_students.append(input("Student Name: "))
print(name_students)
for i in range (1, int(competitionRounds)):
print(input(name_students [0] + " Total Score for each round: "))
This is how the program runs:
How many student?: 3 #Have the user input answers to these questions
How many rounds?: 2
Student Name: Nick
Student Name: Bob
Student Name: Lisa
Nick Total Score for each round:
I was trying to get it to ask for every name listed like
Nick Total Score for round 1:
Bob Total score for round 1:
Lisa Total score for round 1:
Nick Total score for round 2:
Etc.
I appreciate anyone who replies.
---Edit---
So I now have problems taking the numbers inputted by the user and adding them together by the name placed by the user.
My expected outcomes is:
Nick Total Score for round 1: 2
Bob Total score for round 1:3
Lisa Total score for round 1:1
Nick Total Score for round 2:2
Bob Total score for round 2:3
Lisa Total score for round 2:1
Nick Total score for all rounds: 4
Etc
Currently my code looks like:
name_students = list()
num_students = input("How many students?: ")
competitionRounds = input("How many rounds: ")
score_students = []
myList = name_students
total_scores = 0, []
for i in range(1, int(num_students) + 1):
name_students.append(input("Student Name: "))
for i in range (1, int(competitionRounds) +1):
for j in range(len(name_students)):
score_students.append(input(name_students [j] + " Total Score for round " + str(i) +": "))
for i in range (1,int(competitionRounds) +1):
for t in range(len(score_students)):
print(name_students + score_students + total_scores)
You need to change the last loop
for i in range (1, int(competitionRounds)):
for j in range(len(name_students)):
score_students.append(input(name_students [j] + " Total Score for round " + str(i) + ": "))
This will ask the user for each student's score for each round, and keep appending that to score_students. You may then manipulate that the way you want.
How many students?: 2
How many rounds: 3
Student Name: A
Student Name: B
['A', 'B']
A Total Score for round 1: 2
B Total Score for round 1: 1
A Total Score for round 2: 2
B Total Score for round 2: 1

How do I ask all of the questions in the list without repeating the lines of code?

question = ["1 – Which seven-a-side ball game is played in a swimming pool?",
"2 - When was the Olympics last held in London?",
"3 - What is the world record time of the men's 100m sprint?",
"4 - The latest Bond song was sung by whom?",
"5 - Who won the Euro 2016 Final?",
"6 - Who is the mascot of Pokemon?",
"7 - How many stars are on the U.S flag?",
"8 - If 1 = 5, 2 = 10, 3 = 15 and 4 = 20, what does 5 =?",
"9 - In a right angled triangle one side is 3 and another side is 4, what is the length of the hypotenuse?",
"10 - What is the 7th decimal place of pi?"]
multi1 = ["A: Marco Polo","A: 1944","A:9.58seconds","A: Charlie Puth","A: Portugal","A: Mew","A: 49","A: 25","A: 2","A: 4"]
multi2 = ["B: Polo","B: 2004","B: 9.68seconds","B: Sam Smith","B: Wales","B: Mewtwo","B: 52","B: 4","B: 5","B: 1"]
multi3 = ["C: Water Polo","C: 2008","C: 9.54seconds","C: Adele","C: France","C: Pikachu","C: 51","C: 5","C: 3.5","C: 9"]
multi4 = ["D: Polo Marco","D: 2012","D: 9.60seconds","D: Daniel Craig","D: Germany","D: Togepi","D: 50","D: 1","D: 6","D: 6"]
correctAnswer = ['C','D','A','B','A','C','D','D','B','D']
valueWon = ['£0','£100','£2500','£500','£1000','£2500','£5000','£10000','£100000','£1000000']
x = input(question[0] + ' ' +multi1[0]+ ' ' +multi2[0]+ ' ' +multi3[0]+ ' ' +multi4[0])
if x == ("A","B","C"):
print("I'm sorry that was incorrect,",correctAnswer[0],"was the correct answer, you won,",valueWon[0])
else:
y = input("Congratulations, you won" +" " +valueWon[1]+" " +"would you like to continue, yes or no?")
if y == ("No","no"):
exit
I'm making a 'who wants to be a millionaire' game and I want to ask all of the questions in the list without repeating all of the code that I have used above as it will be too lengthy and I know that there is an easier way. Thanks
One way would be to turn your questions into individual Class objects.
class Question():
def __init__(self, id, question, answers, correct_answer):
self.id = id
self.question = question
self.answers = answers
self.correct_answer = correct_answer
question_one = Question(
1,
"Which seven-a-side ball game is played in a swimming pool?",
{"1":"Marco Polo", "2":"Water Polo", "3":"Polo", "4":"Polo Marco"},
"Water Polo"
)
question_list = [question_one]
for _ in question_list:
print("Question number {0}: {1}".format(_.id, _.question))
answer = input("{0}\n".format(_.answers))
if _.answers[answer] == _.correct_answer:
print("You're correct!")
The resulting output would be:
>>>Which seven-a-side ball game is played in a swimming pool?
>>>{'2': 'Water Polo', '1': 'Marco Polo', '3': 'Polo', '4': 'Polo Marco'}
>>>2
>>>You're correct!
And so on and so forth. Please note that if you're in Python 2.7, you'll need to remove the quotations from the numbers in the answers dict.
I am assuming that this is what you want. I see a lot of improvisations that can be made to the code. But still, I am presenting my answers here, for starters.
question = ["1 – Which seven-a-side ball game is played in a swimming pool?","2 - When was the Olympics last held in London?",
"3 - What is the world record time of the men's 100m sprint?",
"4 - The latest Bond song was sung by whom?",
"5 - Who won the Euro 2016 Final?",
"6 - Who is the mascot of Pokemon?",
"7 - How many stars are on the U.S flag?",
"8 - If 1 = 5, 2 = 10, 3 = 15 and 4 = 20, what does 5 =?",
"9 - In a right angled triangle one side is 3 and another side is 4,what is the length of the hypotenuse?",
"10 - What is the 7th decimal place of pi?"]
multi1 = ["A: Marco Polo","A: 1944","A:9.58seconds","A: Charlie Puth","A:Portugal","A: Mew","A: 49","A: 25","A: 2","A: 4"]
multi2 = ["B: Polo","B: 2004","B: 9.68seconds","B: Sam Smith","B: Wales","B: Mewtwo","B: 52","B: 4","B: 5","B: 1"]
multi3 = ["C: Water Polo","C: 2008","C: 9.54seconds","C: Adele","C: France","C: Pikachu","C: 51","C: 5","C: 3.5","C: 9"]
multi4 = ["D: Polo Marco","D: 2012","D: 9.60seconds","D: Daniel Craig","D: Germany","D: Togepi","D: 50","D: 1","D: 6","D: 6"]
correctAnswer = ['C','D','A','B','A','C','D','D','B','D']
valueWon = ['£0','£100','£2500','£500','£1000','£2500','£5000','£10000','£100000','£1000000']
for i,j in enumerate(question):
x = input(j + '\n ' +multi1[i]+ '\n ' +multi2[i]+ '\n ' +multi3[i]+ '\n ' +multi4[i]+'\n')
if x == ("A","B","C"):
print("I'm sorry that was incorrect,",correctAnswer[i],"was the correct answer, you won,",valueWon[i])
else:
y = input("Congratulations, you won" +" " +valueWon[i]+" " +"would you like to continue, yes or no?")
if y == ("No","no"):
break
I hope this helps.
Thanks!
To answer your question simply: you could iterate over each question in the list of questions with a foreach loop.
for q in question:
#do something with q, the for loop will do this for every q in your list 'question'
The problem with this is you don't have access to the corresponding multiple choice answers, the correct answer, or the value won easily. That is, if the loop is iterating and you're on the 2nd question, how does the for loop know to present the 2nd multiple choice answers, the 2nd correct answer, etc?
You could do:
for q in question:
#set idx equal to the index number of the current question,
#so if you're on question 3, it'll be index 2, and you can use
#idx to grab the corresponding multiple choice answers/correct answer/etc
idx = question.index(q)
#have the user input an answer
x = input(q + ' ' + multi1[idx] + ... + multi4[idx])
if (x != correctAnswer[idx]):
print("I'm sorry that was incorrect,",correctAnswer[idx],"was the correct answer")
else:
y = input("Congratulations, you won" +" " +valueWon[idx]+" " +"would you like to continue, yes or no?")
if y == ("No","no"):
break
but enumerate already does this for you:
for i, q in enumerate(question):
#have the user input an answer
x = input(q + ' ' + multi1[i] + ... + multi4[i])
if (x != correctAnswer[i]):
print("I'm sorry that was incorrect,",correctAnswer[i],"was the correct answer")
else:
y = input("Congratulations, you won" +" " +valueWon[i]+" " +"would you like to continue, yes or no?")
if y == ("No","no"):
break
You could (and probably should) create a class for this that way all of your data is coupled together instead of spread out over several objects. Then you would just have to iterate over the list of objects and use those in the same way.

Coin Change Maker Python Program

I am in a beginner programming course. We must do an exercise where we make a change maker program. The input has to be between 0-99 and must be represented in quarters, dimes, nickles, and pennies when the input is divided down between the four. I wrote a code that involved loops and whiles, but he wants something more easy and a smaller code. He gave me this as a way of helping me along:
c=int(input('Please enter an amount between 0-99:'))
print(c//25)
print(c%25)
He told us that this was basically all we needed and just needed to add in the dimes, nickles, and pennies. I try it multiple ways with the dimes, nickles, and pennies, but I cannot get the output right. Whenever I enter '99', I get 3 for quarters, 2 for dimes, 1 for nickles, and 0 for pennies. If anyone would be able to help me, that would be wonderful!
I'm now sure about what you want to achieve. Using the modulo operator you could easily find out how many quarters, dimes, nickles and pennies.
Let's just say you input 99.
c=int(input('Please enter an amount between 0-99:'))
print(c//25, "quarters")
c = c%25
print(c//10, "dimes")
c = c%10
print(c//5, "nickles")
c = c%5
print(c//1, "pennies")
this would print out:
3 quarters
2 dimes
0 nickles
4 pennies
n = int(input("Enter a number between 0-99"))
q = n // 25
n %= 25
d = n // 10
n %= 10
ni = n // 5
n %= 5
c = n % 5
print(str(q) +" " + str(d) +" " + str(ni) + " " + str(c))
I hope this helps? Something like this but don't just copy it. Everytime you divide by 25 10 5 you must lose that part because it's already counted.At the end print what ever you want :).
The actual trick is knowing that because each coin is worth at least twice of the next smaller denomination, you can use a greedy algorithm. The rest is just implementation detail.
Here's a slightly DRY'er (but possibly, uh, more confusing) implementation. All I'm really doing differently is using a list to store my results, and taking advantage of tuple unpacking and divmod. Also, this is a little easier to extend in the future: All I need to do to support $1 bills is to change coins to [100, 25, 10, 5, 1]. And so on.
coins = [25,10,5,1] #values of possible coins, in descending order
results = [0]*len(coins) #doing this and not appends to make tuple unpacking work
initial_change = int(input('Change to make: ')) #use raw_input for python2
remaining_change = initial_change
for index, coin in enumerate(coins):
results[index], remaining_change = divmod(remaining_change, coin)
print("In order to make change for %d cents:" % initial_change)
for amount, coin in zip(results, coins):
print(" %d %d cent piece(s)" % (amount, coin))
Gives you:
Change to make: 99
In order to make change for 99 cents:
3 25 cent piece(s)
2 10 cent piece(s)
0 5 cent piece(s)
4 1 cent piece(s)
"""
Change Machine - Made by A.S Gallery
This program shows the use of modulus and integral division to find the quarters, nickels, dimes, pennies of the user change !!
Have Fun Exploring !!!
"""
#def variables
user_amount = float(input("Enter the amount paid : "))
user_price = float(input("Enter the price : "))
# What is the change ?? (change calculation)
user_owe = user_amount - user_price
u = float(user_owe)
print "Change owed : " + str(u)
"""
Calculation Program (the real change machine !!)
"""
# Variables for Calculating Each Coin !!
calculate_quarters = u//.25
# Using the built-in round function in Python !!
round(calculate_quarters)
print "Quarters : " + str(calculate_quarters)
u = u%0.25
calculate_dime = u//.10
round(calculate_dime)
print "Dime : " + str(calculate_dime)
u = u%0.10
calculate_nickels = u//.05
round(calculate_nickels)
print "Nickels : " + str(calculate_nickels)
u = u%0.5
calculate_pennies = u//.01
round(calculate_pennies)
print "Pennies : " + str(calculate_pennies
Code for the change machine works 100%, its for CodeHs Python
This is probably one of the easier ways to approach this, however, it can also
be done with less repetition with a while loop
cents = int(input("Input how much money (in cents) you have, and I will tell
you how much that is is quarters, dimes, nickels, and pennies. "))
quarters = cents//25
quarters_2 = quarters*25
dime = (cents-quarters_2)//10
dime_2 = dime*10
nickels = (cents-dime_2-quarters_2)//5
nickels_2 = nickels*5
pennies = (cents-dime_2-quarters_2-nickels_2)

Categories