python printing from dictionary - python

I'm trying to write code that will collect the number of individuals attending an event. Based on the number of people entered, I will ask that many times a) the name of the individual, b) the number of toys they have donated. I want the information to be entered into a dictionary which i will pass to another function. The second function will select individuals who have donated more than 20 toys and print their name and the number of toys the donated as "level 1" and then everyone else as "level 2".
I've checked to make sure that the data is being passed from one function to another correctly. I'm having issues printing the donation amount without the []. Also, it keeps printing the level above each entry instead of listing the entries underneath the level. In other words, I'm trying to get:
Level 1
Selena Gomez 50
Beyonce 40
Level 2
Will Smith 5
What am I doing wrong?
Here is my code:
def data():
people = int(input("How many individuals are attending? "))
attendees = {}
for i in range(people):
name = str(input('Please enter name: '))
amount = int(input('Number of toys donated:'))
attendees[name]= [amount]
return attendees
def print_data():
attendees = data()
for i in attendees:
if attendees[i][0] > 20:
print('Level 1')
print(i, attendees[i])
else:
print('Level 2')
print(i, attendees[i])
print_data()
And here is my output:
How many individuals are attending? 3
Please enter name: Will Smith
Number of toys donated:5
Please enter name: Selena Gomez
Number of toys donated:50
Please enter name: Beyonce
Number of toys donated:40
Level 2
Will Smith [5]
Level 1
Selena Gomez [50]
Level 1
Beyonce [40]

you did two mistakes, you were taking input as list as value of each dictionary element and you have to run two different loops to find the all the values greater than 20 and another one to print all the values less than 20
def data():
people = int(input("How many individuals are attending? "))
attendees1 = {}
attendees2 = {}
for i in range(people):
name = str(input('Please enter name: '))
amount = int(input('Number of toys donated:'))
#amount should be just a variable not list
if amount > 20:
attendees1[name]= amount
else:
attendees2[name] = amount
return attendees1, attendees2
def print_data():
attendees1, attendees2 = data()
if len(attendees1) > 0:
print('Level 1')
for i in attendees1:
print(i, attendees1[i])
if len(attendees2) > 0:
print('Level 2')
for i in attendees2:
print(i, attendees2[i])
print_data()

These two lines should be edited:
attendees[name]= [amount]
#into
attendees[name]= amount
#and
if attendees[i][0] > 20:
#into
if attendees[i] > 20:

Does something like this work for you?
def data():
people = int(input("How many individuals are attending? "))
attendees = {}
for i in range(people):
name = str(input('Please enter name: '))
amount = int(input('Number of toys donated:'))
attendees[name]= amount
return attendees
def print_data(attendees):
level_one = []
level_two = []
for name, count in attendees.items():
if count >= 20:
level_one.append((name, count))
else:
level_two.append((name, count))
print('Level 1')
for name, count in level_one:
print(name, count)
print('\nlevel 2')
for name, count in level_two:
print(name, count)
attendees = data()
print_data(attendees)

Related

Function returns same value for each person

I'm working on a project for school to learn Python. In this project you are sitting at a restaurant and you program the bill. When I calculate the total of what everyone spend in a function and return the values. I only receive the total of the last person for every person.
If you run this code and use these values:
2
tim
4
4
james
12
12
you will see that they both get 69 in total.
I figured out if I press one time tab behind the "calculate_amount" to put it in the for loop you see it actually calculates the amounts correctly for the other people, but somehow it overwrites it when you put it out of the for loop
What I want is that after everyone told me how many drinks and cake they ate, I get a final report with all the totals of each person. Like I have right now but then with the correct totals.
I hope someone can steer me in the right direction thanks
#function makes first a calculation of the total each person has spend
def calculate_amount(amount_drinks, amount_cake):
count_number = 0
totaalFris = amount_drinks * drink_price
total_cake = amount_cake * cake_price
totaal = total_cake + totaalFris
totaal = str(totaal)
# then a for statement to print for each person the amount they have spend
for person in list_names:
count_number += 1
print(str(count_number) + " " + person + " " + str(totaal))
#prices of the food
drink_price = 2.50
cake_price = 3.25
#lists
list_names = []
drinked_sodas = []
eaten_food = []
count = 0
#while loop to check if there are coming people between 2-6
while True:
person_amount = int(input("How many people are coming? (2-6) "))
if person_amount < 2 or person_amount > 6:
print("error")
else: break
# ask for every person coming what their name, drinks and food is. and add that to the lists
for persoon in range(person_amount):
naam_persoon = str(input('\nWhat is your name? '))
list_names.append(naam_persoon)
glasses = int(input("How many drinks did you had? "))
drinked_sodas.append(glasses)
cake = int(input("how much cake did you eat? "))
eaten_food.append(cake)
count += 1
#calling the function which calculates the amount of glasses and cakes everyone had
#if u you put the function in this for statement it kinda works(press one time tab)
calculate_amount(glasses, cake)
#problem is I get same total amount for every person.
With the calculate_amount() function you have not parsed in the people buying drinks, therefore the function could not print the people that have bought the drinks so it just prints the value of the amount given multiple times.
Instead, you could try to create a function that takes the name, drinks, and cake variables and call the function for each person:
drink_price = 2.50
cake_price = 3.25
def singular_tab(name, glasses, cakes):
total_drinks = glasses * drink_price
total_cakes = cakes * cake_price
total = total_drinks + total_cakes
return print(f'name: {name}, tab: {total}')
while True:
person_amount = int(input("How many people are coming? (2-6) "))
if person_amount < 2 or person_amount > 6:
print("error")
else: break
for persoon in range(person_amount):
naam_persoon = str(input('\nWhat is your name? '))
glasses = int(input("How many drinks did you had? "))
cake = int(input("how much cake did you eat? "))
singular_tab(naam_persoon, glasses, cake)
To calculate the total amount of money spent by each person I utilized python dictionaries. With the dictionaries, I stored the name, amount of cakes, and amount of drinks.
After storing the relevant information in the dictionary I then parsed the dictionary into a function which then printed out each person's tab.
drink_price = 2.50
cake_price = 3.25
people_data = []
def tab_amount(dict):
final = []
final_text = ""
for people in dict:
cake_total = int(people[2]) * cake_price
glass_total = int(people[1]) * drink_price
person_total = cake_total + glass_total
final.append([people[0], person_total])
person_total = 0
for totals in final:
final_text += f'name: {totals[0]} spent in total: {totals[1]} euro\n'
return final_text
while True:
person_amount = int(input("How many people are coming? (2-6) "))
if person_amount < 2 or person_amount > 6:
print("error")
else: break
for person in range(person_amount):
name = str(input('\nWhat is your name? '))
glasses = int(input("How many drinks did you had? "))
cake = int(input("how much cake did you eat? "))
people_data.append([name, glasses, cake])
print(tab_amount(people_data))
Hope this helps :)

Extracting a tuple value from a dictionary in python

am working on a restaurant project, and I need a hand :)
so the program will display the main dishes, and the user has to enter which dish he/she wants..
and then the choice will be taken and then added to the bill (dish name, price, num of items)...
so far I chose a dictionary so when the user enters 1 (key), the program will display Mashroum Risto...
this what've created:
dishes = {1 : ('Mashroum Risito', 3.950), 2 : ['Tomato Pasta', 2.250],3:['Spagehtie',4.850]}
now my question is how to get the dish name without the price (the price is 3.950) and extract it! and also how to get the price without the name so then I can send it into the bill function to calculate it? and if you have any suggestions please go ahead, because i don't know if using dictionary was the right choice
def MainDish():
dishes = {1 : ('Mashroum Risito', 3.950), 2 : ['Tomato Pasta', 2.250],3:
['Spagehtie',4.850]}
dishes.values
print("1. Mashroum Risito 3.950KD")
print("2. Tomato Pasta 2.250KD")
print("3. Spagehtie 4.850KD")
choice = eval(input('Enter your choice: '))
NumOfItem = eval(input('How many dish(es): '))
while(choice != 0):
print(dishes.get(choice)) #to display the item only without the
price
a = dishes.values()
recipient(a)
break
The way you have implemented it:
print (dishes[1][0]) #will give you name
print (dishes[1][1]) #will give you price
where [x][y]
x = key in the dict (input in your case)
y = element of the value in the dict (0 = name, 1=price in your case)
You should probably create the dictionary better as below:
Follow up question is not so clear but I think this is what you are after roughly. You will need to tweak the returns to your usage:
def MainDish():
NumOfItem = float(input('How many dish(es): '))
dish = list(dishes)[choice-1]
cost_of_dish = dishes[dish]
totalcost = cost_of_dish * NumOfItem
print (f"\n\tOrdered {NumOfItem}x {dish} at {cost_of_dish}KD each. Total = {totalcost}KD\n")
return dish, cost_of_dish, totalcost
dishes = {'Mashroum Risito': 3.950, 'Tomato Pasta': 2.250}
for key,val in dishes.items():
print (f"{list(dishes).index(key)+1}. {key}: {val}KD")
keepgoing = True
while keepgoing:
choice = int(input('Enter your choice: '))
if choice == 0:
keepgoing = False
break
else:
dish, cost_of_dish, totalcost = MainDish()

Python: modify a table attribute from the options generated in another table

I have created two different functions, one to create an inventory of available products:
def create_piece():
print(Colour().blue('Creating a new piece'.center(200)))
piece_name = input(Colour().orange('Name of the piece: '))
piece_registration = input(Colour().orange('Piece registration number: '))
piece_date = input(Colour().orange('Date of manufacture: '))
piece_location = input(Colour().orange('Manufacturing location: '))
piece_price = input(Colour().orange('Price: '))
Parts.create(Name=piece_name , Parts_registration_number=piece_registration ,
Date_of_manufacture=piece_date ,
Manufacturing_locality=piece_location , Price=piece_price ,
Number_of_parts_sold='0')
print(Colour().green(('Part created satisfactorily')))
As you can see the option "Number_of_parts_sold" has the marker to 0.
Then I have created an option to execute purchase orders:
def order_purchase():
print(Colour().blue('Purchase order portal'.center(200))
Seller_name = input(Colour().orange('Who are you?: '))
number = int(input(Colour().orange('Number of items?: '))
pieces_list=[]
total_cost = 0
for i in range (0, number):
while True:
piece_name = input(Colour().orange('Name of the piece to buy: '))
try:
piece = Pieces.get(Pieces.Name == piece_name)
break
except DoesNotExist:
print(Colour().red('This piece does not currently exist in the system, ')
please enter a correct name.'))
ID = input(Colour().orange('Purchase ID: '))
for price in Piezas.select().where(Pieces.Name == piece_name):
price_orders = (price.price)
total_cost += price_orders
name_piece=str(name_piece)
parts_list.append(part_name)
Orders.create(ID_buy_orders=ID, Date_buy_orders=datetime.now(),
Order_Seller=Seller_name , Order_People = pieces_list,
Price_orders=total_cost)
print(Colour().green('Pieces sold satisfactorily'))
This last function fills in another table in which it stores the number of pieces that each seller buys. However, I would like to know how to relate the second table with the first so that for each piece that is sold (generated in the tuple "lista_piezas") change the marker and add in the first table how many pieces have been sold. How could I do this? Thanks in advance

Creating a sales list that allows users to enter multiple items

I've been working on a project for my class in python and I feel like no matter what I do I can't get it right. We're supposed to create a program that captures 3 items and then 4 bits of information for each item. AKA: Item: x, Quantity: x, price $x, weight x pounds. Then it should print out a subtotal, shipping & handling cost, tax total, and final total. The issue I'm having is that we're not allowed to create a variable for each item and must do everything in a loop. No matter what I've tried all I can do is get everything to print out the last data entered.
Here's my code so far:
def main():
#Range of 3 so that user may enter 3 seperate items
for i in range(3):
#Grabs user input for item description and/or name
strDescription = str(input("Enter description of item: "))
#Grabs user input for price of item
fltPrice = float(input("Enter price of item: $ "))
#Grabs user input for quanitity of item
intQuantity = int(input("Enter quantity of item: "))
#Grabs user input for weight of item in pounds
fltWeight = float(input("Enter weight of item in pounds: "))
#Subtotal is equal to price times number of items purchased
fltPriceSub = fltPrice*intQuantity
#Shipping 25 cents per pound
intShipping = (.25*fltWeight)
#There is a base fee of $5 per order applied to shipping
intBaseRate = 5
#Tax is 9 cents per dollar
fltTax = 0.09*fltPriceSub
fltPriceSubTotal = fltPriceSub+fltPriceSub+fltPriceSub
intShippingTotal = intShipping+intShipping+intShipping+intBaseRate
fltTaxTotal = fltTax+fltTax+fltTax
#Order total is the subtotal+shipping+tax added together
fltOrderTotal = fltPriceSubTotal+intShippingTotal+fltTaxTotal
print("You have purchased ", strDescription, "")
print("Your subtotal is ", fltPriceSubTotal, "")
print("Shipping and handling is ", intShippingTotal, "")
print("The tax is ", fltTaxTotal, "")
print("The order total is ",fltOrderTotal, "")
main()
If anyone could steer me in the right direction I would really appreciate it.

House Point Program

My name is Jamie, I'm a Yr 12 student currently living in NZ. At school, in our computer science class we were tasked with creating a program for house points. A house is sort of like the Houses in Harry Potter, each student is assigned to one. These houses then compete in events and earn points, at the end of the year the house with the most points wins the trophy.
Now we have only been taught about 2-D arrays and parallel lists, as these need to be incorporated plus it must be modular.
The program must be fully user inputed as requirements for excellence (equivalent of A) must be user inputed.
The program must also have these inputs and outputs:
Inputs: House Names, House Events, and Points earned in events for the house
Cancel house name and house event entry when XXX is entered.
Outputs: Winner of each event, house with best average, house with most wins, and overall winner.
I am currently trying to figure out how to do the points to go with house and events.
Appreciate all help,
Jamie :)
EDIT: Posted Code
def number_house():
global numhouse
print("Welcome!")
print()
Flag = True#loop
while Flag:
try:
numhouse = int(input("Please enter the number of events there is: "))
print()
if numhouse < 1 or numhouse > 100:
print("WOW, thats a lot of events, please be reasonable. Thanks.")
else:
Flag = False
except ValueError:
print("Enter only a number, Thanks.")
def event_names():
global event
print("Enter XXX when finished entering event names")
Flag = True
for e in range(numhouse):
e = input("Event name: ")
if e == 'XXX' or e == 'xxx':
Flag = False
else:
event.append(e)
print()
def getData():
global data
global inputlist
global event
lower_bound = 0
upper_bound = 100
k=0
n=str(input("Please enter house names <<<Enter XXX when finished>>> :"))
while n != 'XXX' :
if n == 'XXX' or n == 'xxx':
exit
data = [n]
print()
print ("Please enter the event points in ascending order. ",event,"Thanks")
for k in range(len(event)):
s = getScore(n,lower_bound,upper_bound)
data=data+[s]
inputlist = inputlist + [data]
n=str(input("Please enter house names <<<Enter XXX when finished>>> :"))
def getScore(name,min,max):
global event
sc= -1
while sc < min or sc > max :
try :
sc = int(input("Please enter score for "+ name + " :"))
except ValueError :
print("Invalid Input please enter an interger. Thanks")
return sc
score =[]
getscore = []
data = []
inputlist = []
event = []
number_house()
event_names()
getData()
print()
print(inputlist)
LOWER_BOUND = 0
UPPER_BOUND = 100 # both in caps because this is a constant
def get_score(house_name, event_name):
# an extra argument so you can tell which event is being scored.
# removed the min, max cause we are using the constants!
score = -1
while score < LOWER_BOUND or score > UPPER_BOUND:
try:
score = int(input("Please enter score for %s in the event %s:" % (house_name, event_name)))
if score < LOWER_BOUND :
print ("Score is too low, minimum score is %i.\nPlease try again." % min_score)
if score > UPPER_BOUND:
print ("Score is too high, maximum score is %i\nPlease try again." % max_score)
except ValueError:
print("Invalid Input please enter an integer. Thanks")
return score # note the use of return to avoid using global
def get_number_of_events():
print("Please enter the number of events there is.")
while True:
try:
n_events = int(input(">>"))
except ValueError:
print("Enter only a number, Thanks.")
if n_events > 100:
print("WOW, that's a lot of events, please be reasonable. Thanks.")
elif n_events < 1:
# this is a different condition that would get a wrong error in your program,
# note the use of 'elif', in Python this an 'else if'.
print ("That's too few events! Try Again.")
else:
# no need to use Flag, just use break when you want to leave a loop.
break
return n_events
def get_events_names(n_events):
print ("Please enter the events names")
events = []
for n in range(1, n_events + 1):
# starting at 1 to give a better display
event_name = input("Event %i name: " % n)
events.append(event_name)
return events
def get_data(events):
data = []
while True:
house_name = input("Please enter house names <<<Enter XXX when finished>>> :")
if house_name.upper() == "XXX":
# using .upper() to avoid checking twice for either 'xxx' or 'XXX'.
# I would ask the user for how many houses are there instead, but your choice ;)
break
print ("Please enter the events points in ascending order.")
# not actually need to be in ascending order, you can sort them later if you want.
scores = []
for event_name in events:
# don't use range(len(something)), loops in Python are easy!
score = get_score(house_name, event_name)
scores.append([event_name, score])
data.append([house_name, scores])
# use .append() instead of data = data + [...]
return data
def main():
print("Welcome!\n")
n_events = get_number_of_events()
events_names = get_events_names(n_events)
print()
data = get_data(events_names)
print()
for house_name, event_data in data:
print ("House " + house_name)
for event_name, score in event_data:
# note the use of tuple unpacking
print ("\tEvent: %s Score: %i" % (event_name, score))
if __name__ == '__main__':
main()
This time maintaining the same structure as your program.
Check comments for some tips and tricks.
Also, try to keep your variable names with meaning and check the PEP 8 guidelines for naming conventions (variables and functions should be snake_case,
Output:
Welcome!
Please enter the number of events there is.
>>2
Please enter the events names
Event 1 name: Quidditch Match
Event 2 name: Duels
Please enter house names <<<Enter XXX when finished>>> :Gryffindor
Please enter the events points in ascending order.
Please enter score for Gryffindor in the event Quidditch Match:100
Please enter score for Gryffindor in the event Duels:30
Please enter house names <<<Enter XXX when finished>>> :Slytherin
Please enter the events points in ascending order.
Please enter score for Slytherin in the event Quidditch Match:40
Please enter score for Slytherin in the event Duels:50
Please enter house names <<<Enter XXX when finished>>> :XXX
House Gryffindor
Event: Quidditch Match Score: 100
Event: Duels Score: 30
House Slytherin
Event: Quidditch Match Score: 40
Event: Duels Score: 50
I'll try to give you a different approach, see if that helps you.
def main():
events = []
houses = []
scores = {} # key = House name, value = scores
print "Welcome!\n"
# create the houses
print "Please enter how many houses there is:"
n_houses = int(raw_input(">>"))
print "Please enter houses names:"
for n in range(n_houses):
print "House", n+1
house_name = raw_input(">>")
houses.append(house_name)
# create the events
print "Please enter the number of events there is"
n_events = int(raw_input(">>"))
print "Please enter the event names"
for n in range(n_events):
print "Event", n+1
event_name = raw_input(">>")
events.append(event_name)
# get the scores for each house for each event
for event in events:
for house in houses:
print "Please enter the score for House %s in the event %s"%(house, event)
score = int(raw_input(">>"))
# initialize the score with a empty list
if house not in scores:
scores[house] = []
# add the score list
scores[house].append(score)
print "\nThe result is:"
# process the result
for house, score in sorted(scores.items(),
key=lambda x: sum(x[1]),
reverse=True):
print "House %s. Total Score: %i"%(house, sum(score))
if __name__ == "__main__":
main()
First thing you should notice is that I'm not using global, using global is usually frowned upon, it can lead to undesired interactions on data.
Also, instead of asking for inputs like "XXX" to break the loop, I asked the user for the number of inputs he wants to deal before, so I can loop over this number and process each separately.
I do the same thing with the house, I ask for how many houses are there, and then their names.
Next I do a nested for loop with the event names and house names. The order matters, we deal with each event first. You can change it to deal with each house first.
And finally I process the scores. the line for house, score in sorted(scores.items(), key=lambda x: sum(x[1]), reverse=True): is a bit clogged and advanced but it means this: I want to loop over a sorted list of items, giving me two items at a time, the items are named house and score, they will be sorted by the function sum(x[1]), and I want this in the reversed order (or else the last would show in first).
key=lambda x: sum(x[1]) is a bit of a hack, it could be done better. lambda means a function, it takes x as input, x in this case is a tuple of house, score, so I want the score, so I access it using x[1], and since I want the sum I use sum(x[1]).
Usage:
Welcome!
Please enter how many houses there is:
>>2
Please enter houses names:
House 1
>>Gryffindor
House 2
>>Slytherin
Please enter the number of events there is
>>2
Please enter the event names
Event 1
>>Quidditch Match
Event 2
>>Duels
Please enter the score for House Gryffindor in the event Quidditch Match
>>100
Please enter the score for House Slytherin in the event Quidditch Match
>>90
Please enter the score for House Gryffindor in the event Duels
>>250
Please enter the score for House Slytherin in the event Duels
>>240
The result is:
House Gryffindor. Total Score: 350
House Slytherin. Total Score: 330
Notice that this was made on Python 2.7, to port to Python 3 just change raw_input to input and print to print()

Categories

Resources