Goal:
Display my list of commission pay with a £ symbol.
Explanation of what the problem is:
When it comes to displaying the result it does not print the whole result instead it just prints the £ symbol.
What I have tried:
As you can see in the code, I have attempted to convert the array into a string (putting it into its own variable) then I added the currency symbol (£) to it and asked for commission2 to be called. However, it does not show.
OUTPUTTED:
Name Id Houses Sold Commission
£1000
ki 2 2 £
(the £1000 is just to show that the data is actually there, but for some reason when printing in the list, it is not displayed...)
OUTPUT DESIRED:
Name Id Houses Sold Commission
ki 2 2 £1000
I've been at it for hours so any help would be greatly appreciated!
Code where the error occurs:
def print_entered_info(names, ids, num_sold_houses):
print()
row_width = 12
comission_per_house = 500
header = ['Name', 'Id', 'Houses Sold', 'Commission']
print(' '.join(f'{h:<{row_width}}' for h in header))
commission = [n * comission_per_house for n in num_sold_houses]
commission2 = commission
commission2 = ''.join(str(e) for e in commission)
commission2= "£" + commission2
print(commission2)
for values in zip(*[names, ids, num_sold_houses, commission2]):
print()
print(' '.join(f'{v:<{row_width}}' for v in values))
My full code:
def get_int_input(prompt: str) -> int:
num = -1
while True:
try:
num = int(input(prompt))
break
except ValueError:
print('Error: Enter an integer, try again...')
return num
def get_yes_no_input(prompt: str) -> bool:
allowed_responses = {'y', 'yes', 'n', 'no'}
user_input = input(prompt).lower()
while user_input not in allowed_responses:
user_input = input(prompt).lower()
return user_input[0] == 'y'
names = []
ids = []
num_sold_houses= []
def get_single_employee_info(names, ids, num_sold_houses):
names.append(input('What is the employee\'s name?: '))
ids.append(get_int_input('What is the employee\'s id?: '))
num_sold_houses.append(get_int_input('How many houses did the employee sell?: '))
def get_houses_sold_info(names, ids, num_sold_houses):
get_single_employee_info(names, ids, num_sold_houses)
add_another_employee = get_yes_no_input('Add another employee [yes/no]?: ')
while add_another_employee:
get_single_employee_info(names, ids, num_sold_houses)
add_another_employee = get_yes_no_input(
'Add another employee [yes/no]?: ')
def print_entered_info(names, ids, num_sold_houses):
print()
row_width = 12
comission_per_house = 500
header = ['Name', 'Id', 'Houses Sold', 'Commission']
print(' '.join(f'{h:<{row_width}}' for h in header))
commission = [n * comission_per_house for n in num_sold_houses]
commission2 = commission
commission2 = ''.join(str(e) for e in commission)
commission2= "£" + commission2
print(commission2)
for values in zip(*[names, ids, num_sold_houses, commission2]):
print()
print(' '.join(f'{v:<{row_width}}' for v in values))
print()
total_commission = sum(commission)
print(f'Total Commission: £{total_commission}.00 (before bonus)')
print()
bonus = max(commission)
if bonus >= max(commission):
bonus = bonus*0.15
bonus = (int(max(commission)) + bonus)
commission = bonus
print("The person at the top of ranking gets: " + "£" + str(commission)+"0")
print()
rankings = sorted(zip(num_sold_houses, names), reverse=True)
print('Ranking:')
for houses_sold, name in rankings:
print(f'{name} - {houses_sold}')
def main() -> None:
print('Houses Sold Tracker')
print('===================')
names, ids, num_houses_sold = [], [], []
get_houses_sold_info(names, ids, num_houses_sold)
print_entered_info(names, ids, num_houses_sold)
if __name__ == '__main__':
main()
Change out
commission2 = ''.join(str(e) for e in commission)
to
commission2 = ["£" + str(e) for e in commission]
and remove the line under it. Your ''.join was taking 2 list elements and forcing them into a single string, which is not what you want for this logic. You want a list output for the commission2 variable so we create a list and append the stringified values to it along with the currency symbol.
Output:
Name Id Houses Sold Commission
Kevin 1 3 £1500
Stacey 2 5 £2500
Total Commission: £4000.00 (before bonus)
The person at the top of ranking gets: £2875.00
Ranking:
Stacey - 5
Kevin - 3
Related
The canteen in the Institute maintains has a table of prices of items, like:
Samosa: 15
Idli: 30
Maggie: 50
Dosa, 70
…
For the program you have to write, set the menu in your program by this statement (feel free to add more items).
menu = [("Samosa", 15), ("Idli", 30), ("Maggie", 50), ("Dosa", 70), ("Tea", 10), ("Coffee", 20), ("Sandwich", 35), ("ColdDrink", 25)]
Write a program to take a user's order on a terminal and compute the bill. First show the menu by printing the menu. For ordering an item, the user inputs the item number and the quantity desired (e.g. an input can be: 3 1 followed by 1 5). The program should prompt the user to order more, till he/she hits return (without any numbers) - which is the end of the order. Print a bill for this order in the form (for the input example above):
Maggie, 1, Rs 50
Samosa, 5, Rs 75
TOTAL, 6 items, Rs 125
How can I access the list and take inputs and add them?
First initialize the global variables:
bill = []
total_quantity = 0
total_price = 0
Inside the loop you will ask for the order and exit the loop if it is an empty string:
order = input("Please specify an item number and a quantity: ")
if order == "" : break
Then parse the order, by splitting the input string before and after the space:
(index_string, quantity_string) = order.split(" ")
Now access the menu variable and compute the price:
quantity = int(quantity_string)
item = menu[int(index_string)-1]
name = item[0]
unit_price = int(item[1])
price = unit_price * quantity
and update the global variables:
bill.append("%s, %d, Rs %d" % (name, quantity, price))
total_quantity += quantity
total_price += price
Finally you can print what you collected:
for string in bill :
print(string)
print("\nTOTAL, %d items, Rs %d" % (total_quantity, total_price))
This is the final code:
menu = [("Samosa", 15), ("Idli", 30), ("Maggie", 50), ("Dosa", 70), ("Tea", 10), ("Coffee", 20), ("Sandwich", 35), ("ColdDrink", 25)]
print(menu)
bill = []
total_quantity = 0
total_price = 0
while True :
order = input("Please specify an item number and a quantity: ")
if order == "" : break
(index_string, quantity_string) = order.split(" ")
quantity = int(quantity_string)
item = menu[int(index_string)-1]
name = item[0]
unit_price = int(item[1])
price = unit_price * quantity
bill.append("%s, %d, Rs %d" % (name, quantity, price))
total_quantity += quantity
total_price += price
for string in bill :
print(string)
print("\nTOTAL, %d items, Rs %d" % (total_quantity, total_price))
I get an error in taking the values in the list what is the right code to input in getting the average in the list
values = [["Name", 'Age', 'Grade']]
for i, val in enumerate(values):
print(i, val)
while True:
print("\n1 - Add\n2 - Show Report\n")
choice = int(input("Enter your choice: "))
if choice == 1:
name = str(input("Input Name: "))
age = int(input("Enter Age: "))
grade = float(input("Enter Grade: "))
values.append([name, age, grade])
for i, val in enumerate(values):
print(i, val)
elif choice == 2:
for i, val in enumerate(values):
a = sum(val[1] / i)
print("The average age in the list is", a)
b = sum(val[2] / i)
print("The average grade in the list is", b)
This should be the output of the program
Should I add a code to remove 'Age' and get the Sum then divide?
Sample output
0 ['Name', 'Age', 'Grade']
1 - Add
2 - Show
Enter your choice: 1
Input name: Bob
Input Age: 24
Input Grade: 90
0 ['Name', 'Age', 'Grade']
1 ['Bob', 24, 90.0]
1 - Add
2 - Show
Enter your choice: 1
Input name: Jun
Input Age: 20
Input Grade: 95
0 ['Name', 'Age', 'Grade']
1 ['Bob', 24, 90.0]
2 ['Jun', 20, 95.0]
1 - Add
2 - Show
Enter your choice: 2
The average age in the list is 22
The average grade in the list is 92.5
Without changing too much of your code :
Here is your list of list (which is basically a table)
Name, Age, Grade
Bob, 24, 90.0
Jun, 20, 95.0
Remember that the first row are headers (strings) that cannot be divided. You have to ignore it. Plus the index of that row is 0 and a division by 0 breaks the universe. Change that to enumerate(values[1:]) to skip the first row.
elif choice == 2:
for i, val in enumerate(values):
a = sum(val[1] / i)
print("The average age in the list is", a)
b = sum(val[2] / i)
print("The average grade in the list is", b)
Then you have to sum all grades and all ages. One way to do it is to put it to a variable. There for each row (student) it will add his age to the sum of ages and same for his grade. Then we can calculate the average by dividing these values with the number of student present in the list. Size of the list -1 because we removed the first row. len(values) gives the number of element in that list.
elif choice == 2:
# EDIT: i forgot to set these var before calling +=, it would cause a NameError (undefined).
sumAge = sumGrade = 0
for i, val in enumerate(values[1:]):
sumAge += val[1]
sumGrade += val[2]
averageAge = sumAge / (len(values)-1)
averageGrade = sumGrade / (len(values)-1)
print("The average age in the list is", averageAge)
print("The average grade in the list is", averageGrade)
Doing more
In fact I would use object, because your list is just a list of student described by their name, age and grade.
class Student:
"""A class representing a student, described with a Name, Age and Grade"""
def __init__(self, name :str, age :int, grade :float):
self.name = name
self.age = age
self.grade = grade
So you can set your list of students almost the same way as before
students: List[Student] = []
# There you can set your input.
studentA = Student("Bob", 24, 95.0)
students.append(studentA)
studentB = Student("Jun", 20, 90.0)
students.append(studentB)
If you're wondering how class works. Here is a example of a part of your code translate to a Class. :
from typing import List
class Student:
"""A class representing a student, described with a Name, Age and Grade"""
# __init__ is called when you create an object of type Student
def __init__(self, name :str, age :int, grade :float):
self.name = name
self.age = age
self.grade = grade
# __str__ is called in print(instanceofstudent), we can choose what to print, so we don't have to think about it when calling print(student)
def __str__(self) -> str:
return f"__str__ : {self.name} - {self.age} - {self.grade}"
# __repr__ is called in print(listofstudent), same here, we choose what to display when we print a list of students.
def __repr__(self) -> str:
return f"__repr__ : {self.name} - {self.age} - {self.grade}"
students: List[Student] = [] # :List[Student] is just to give python more information about what we will put in the list.
# There you can set your input.
studentA = Student("Bob", 24, 95.0) # here we call __init__
students.append(studentA)
studentB = Student("Jun", 20, 90.0) # here we call __init__
students.append(studentB)
print(students) # here we call student.__repr__ to print all element of the list
sumAge = sumGrade = 0
for student in students:
print(student) # here we call student.__str__
print(student.name) # here we get the attributes directly
sumAge += student.age
sumGrade += student.grade
print(f"SumAge : {sumAge}")
print(f"SumAge : {sumGrade}")
averageAge = sumAge/len(students)
averageGrade = sumGrade/len(students)
print(f"average age of students : {averageAge}")
print(f"average grade of students : {averageGrade}")
The code should Capture products in stock (i.e. name, price, date supplied, supplier name, quantity), Retrieve the price when name is given upon each purchase and deducts the quantity in
stock, Calculate the total price for each purchase and prints value indicating date and time of
purchase, Sends an alert when quantity reaches 5 to shopkeeper and places order to supplier.
My code right now is not looping so that I can add a number of products then be able to access them, I tried using a while loop but it is running forever. Kindly help
import datetime
class Stock:
def __init__(self, name, price, supplier, quantity,date):
self.name = name
self.price = price
self.date = date
self.supplier = supplier
self. quantity = quantity
def check_item(self, name):
for i in range(len(ls)):
if (ls[i].name == name):
return i
def sale(self):
n = int(input("How many products to sale: "))
total = 0
for j in range(n):
name = input("Enter Product name : ")
quantity = int(input("Enter quantity: "))
i = obj.check_item(name)
if i and ls[i].quantity >= quantity:
ls[i].quantity -= quantity
if ls[i].quantity < 5:
print("Low Stock! Low Stock! Order Placed")
obj.place_order(name, ls[i].supplier, quantity+10)
print("....Uncle G Shop....")
print(datetime.date.today())
print("Product Name | Quantity | Cost $")
print(ls[i].name, end=" ")
print(quantity, end=" ")
print(ls[i].price * quantity)
total += ls[i].price * quantity
print("\n")
print("Total Cost----->", "$" + total)
else:
print("Product out of stock or not enough quantity")
def purchase(self):
name = input("Enter Product name: ")
date = datetime.date.today()
i = obj.check_item(name)
if i:
ls[i].quantity += int(input("Enter quantity: "))
ls[i].price = int(input("Enter product price: "))
ls[i].date = date
else:
quantity = int(input("Enter quantity: "))
price = int(input("Enter product price: "))
supplier = input("Enter Supplier: ")
ob = Stock(name, price, supplier, quantity, date)
ls.append(ob)
def place_order(self,name, supplier, quantity):
return name, supplier, quantity
def print_products(self):
def __repr__(self):
return str(self.name) + str(self.price) + str(supplier) + str(self.quantity) + str(self.date)
return __repr__
def main(self):
print("Welcome To Uncle G Shop")
print("choose an option below")
print("\n1.Enter a Product\n2.Make a sale \n3.See all Products\n4.Exit")
option = int(input("Enter option here: "))
while True:
if option == 1:
obj.purchase()
elif option == 2:
obj.sale()
elif option == 3:
obj.print_products()
elif option == 4:
print("Have a good day")
break
else:
print("Enter a valid input!")
# A list to add Products
ls = []
# an object of Stock class
obj = Stock('', 0, 0, 0, '')
obj.main()
Your main menu doesn't have a break from the while loop for option 4.
You also need to think again about how to use your class. At present, you have multiple methods referring to a variable, ls, created outside of the class. Either treat Stock as a class to deal with individual purchase records, or to deal with stock overall. You could maintain in the class itself a list of instances of the class and offer class methods, as well as instance methods, to manage that overall stock.
so I am trying to learn python and have a csv file like this
1 product_id product_name price
2 1001 cake 15
3 1002 sprite 30
4 1003 coffee 50
5 1004 ice cream 30
6 1005 banana 10
my program is
import csv
productid=input("Enter the product ID: ")
quantity=int(input("Enter the quantity: "))
csv_file=csv.reader(open("shoppinglist.csv", "r"),delimiter=",")
for row in csv_file:
if productid==row[0]:
product_id=row[0]
product_name=row[1]
product_price=row[2]
print("\nProduct ID: {}".format(row[0]))
print("Product Name: {}".format(row[1]))
print("Product Price: {}".format(row[2]))
total=quantity*(int(product_price))
print("\nThe Total Amount Payable is: {}".format(total))
I can enter one productid at a time and get the output but i am looking for a way so that i can enter multiple productid's ad they get searched in the csv file and then the total is calculated and all the product details output.
PS: I have tried to explain my problem as best as i can but if i have made any mistake please be kind to point it out to me
my output is
Enter the product ID: 1001 Enter the quantity: 5
Product ID: 1001 Product Name: cake Product Price: 15
The Total Amount Payable is: 75
i just do not want to print the product but to search for its id in the csv file and if it exits ask the user to input the quantity for every productid entered and then print the details of the products along with the total amount.
You Need a Loop to look around to your product each time you offered a product Id
I Hope You Understand the following code.
# Author Name : Sandip Sadhukhan
import csv
def findProduct(productId):
csv_file = csv.reader(open('shoppinglist.csv', 'r'), delimiter=',')
productPrice = 0
productName = ''
isFound = False
for row in csv_file:
if productId == row[0]:
productName = row[1]
productPrice = row[2]
isFound = True
break
result = {
'isFound': isFound,
'productName': productName,
'productPrice': productPrice,
'productId': productId
}
return result
total = 0
printList = []
while(True):
productid = input("Enter a product Id: ")
result = findProduct(productid)
if not(result['isFound']):
print("Product is not found...")
continue
quantity = int(input("Enter the quantity: "))
if(quantity <= 0):
print("Please select atleast 1 quantity.")
continue
total += quantity * (int(result['productPrice']))
temp = [result['productName'], quantity, result['productPrice']]
printList.append(temp)
addMore = input("Add more Items? (Y/N) : ")
if(addMore.lower() == 'n'):
break
print("\nBill\n====\n\n[Product Name] [Product Price] [Quantity]")
for item in printList:
print("{} {} {}".format(item[0], item[2], item[1]))
print("The total Amount payable is : {}".format(total))
You can just parse your input to be the way you want. For example,
def product(id): # given product id, returns price, 0 if item does not exist
# your code goes here
id = input("Enter your product ids separated by spaces: ") # For e.g. 2 3 1
id = id.split(" ")
total = 0
for i in id:
price = product(id)
if price != 0:
quantity = print("Enter quantity of " + str(id) + ": ")
total += quantity*price
print("The total price is: " + price)
This code parses the ids so they are in an array. It then goes through each id in the array and performs your code.
You should really look into pandas, it's going to make all these kinds of operations much simpler.
I wrote this code but I don't know how to add all donations for each donor when the loop runs several times.
It should print like this:
Donor 1 has donated £10 in total
Donor 2 has donated £15 in total...
import random
number_of_staff = (random.randint(3,5))
suggested_donation = (random.randint(10, 20))
amount_to_be_raised = number_of_staff * suggested_donation
a = []
def amount():
print('Amount to be raised by team number ______is £', amount_to_be_raised, '.')
print('Number of staff that will contribute is', number_of_staff)
print('Suggested donation is', suggested_donation)
def donation_loop(number_of_staff):
for j in range(number_of_staff):
print('Donor', j + 1)
actual_donation = int(input('Please enter donation £'))
a.append(actual_donation)
global b
b = sum(a)
print('The total sum donated is', b)
def stop():
while b < amount_to_be_raised:
donation_loop(number_of_staff)
else:
pass
amount()
donation_loop(number_of_staff)
stop()
Your code is almost correct, you have several ways to fix it, my favorite one is as follows:
import random
number_of_staff = (random.randint(3,5))
suggested_donation = (random.randint(10, 20))
amount_to_be_raised = number_of_staff * suggested_donation
a = {}
def amount():
print('Amount to be raised by team number ______is £', amount_to_be_raised, '.')
print('Number of staff that will contribute is', number_of_staff)
print('Suggested donation is', suggested_donation)
def donation_loop(number_of_staff):
global total_donations
for j in range(number_of_staff):
print('Donor', j + 1)
actual_donation = int(input('Please enter donation £'))
total_donations += actual_donation
if f'Donor{j + 1}' not in a:
a[f'Donor{j + 1}'] = []
a[f'Donor{j + 1}'].append(actual_donation)
print('The total sum donated is', total_donations)
def stop():
while total_donations < amount_to_be_raised:
donation_loop(number_of_staff)
amount()
total_donations = 0
stop()