How can i use an array to take user input - python

I need to request 3 items from a user then,
Request the price of those three items from a user
Calculate the total of all three
Calculate the average
print a statement saying "the total of product 1, product 2, product 3 is xxxx and the average is xxxx
I've tried to use 6 strings (so 3 for the products and 3 for the prices) so I could call each value separately. But then I was told an array would greatly shorten the code and neaten it up so I tried that but I'm battling to call it forward. I know how to work out the average and total but I'm struggling with the array part.
products = []
products = input("Please enter three shopping products: ")
The code then prints and allows me to input the 3 products like below:
Please enter three shopping products: Shampoo, Soap, Bread
(I still need to ask the prices for each product through an array)
shopping = products[0]
print(shopping)
S
The first way I tried was the 6 strings, like below:
product1 = input("Please enter a shopping item: ")
product2 = input("Please enter a second shopping item: ")
product3 = input("Please enter a third shopping item: ")
price1 = input("Please enter the price for the first shopping item: ")
price2 = input("Please enter the price for the second shopping item: ")
price3 = input("Please enter the price for the third shopping item: ")
It prints the question and allows my input, but it doesn't look very neat.
I now need to calculate the average of the prices as well as the total (which I can do without the array but if I'm using the array it's confusing)
I'm wanting my end result to be:
The Total of [product1], [product2], [product3] is Rxx, xx and the average price of the items are Rxx, xx.

products = []
prices = []
for i in range (0,3):
product = raw_input("Enter your Item to the List: ")
products.append(product)
for j in range (0,3):
price = float(raw_input("Enter your price to the List: "))
prices.append(price)
print "The total of products is " + str(sum(prices)) + " and the average price is " + str(sum(prices)/3)

You could split the input into an array which would shorten the code by quite a bit.
products = input("Please enter three shopping products (Seperated by comma): ")
result = [x.strip() for x in products.split(',')]
This would strip the string of spaces and but them into an array.

class ShoppingItem:
price = 0
name = ""
def __init__(self, name, price):
self.price = price
self.name = name
shoppingItems = []
for i in range(0, 3):
productName = input("Please enter a shopping item: ")
price = input("Please enter a price for the shopping item: ")
shoppingItems.append(ShoppingItem(productName, price))
total = sum(i.price for i in shoppingItems)
average = total/len(shoppingItems))

itemsList = []
priceList = []
for i in range(1,4):
itemStr = "Enter the {} shopping item: ".format(i)
itemsList.append(input(itemStr))
priceStr = "Enter the price of {} shopping item: ".format(itemsList[i-1])
priceList.append(int(input(priceStr)))
print("The Total of {}, {}, {} is {} and the average price of the items are {}".format(*itemsList, sum(priceList), sum(priceList) / float(len(priceList))))
OUTPUT:
Enter the 1 shopping item: shopping_item_1
Enter the price of shopping_item_1: 1
Enter the 2 shopping item: shopping_item_2
Enter the price of shopping_item_2: 2
Enter the 3 shopping item: shopping_item_3
Enter the price of shopping_item_3: 3
The Total of shopping_item_1, shopping_item_2, shopping_item_3 is 6 and the average price of the items are 2.0
EDIT:
If the shopping items are unique, I'd suggest a dict approach with items as keys and prices as values:
n = int(input("Enter the total items: "))
shoppingDict = {}
for i in range(n):
keys = input("Enter the shopping item: ")
values = int(input("Enter the price of item: "))
shoppingDict[keys] = values
print("The Total of {}, {}, {} is {} and the average price of the items are {}".format(*shoppingDict.keys(), sum(shoppingDict.values()), sum(shoppingDict.values()) / float(sum(shoppingDict.values()))))
OUTPUT:
Enter the total items: 3
Enter the shopping item: shopping_item_1
Enter the price of item: 1
Enter the shopping item: shopping_item_2
Enter the price of item: 2
Enter the shopping item: shopping_item_3
Enter the price of item: 3
The Total of shopping_item_1, shopping_item_2, shopping_item_3 is 6 and the average price of the items are 1.0

Related

How to find the total cost for this python program

I have created a simple python program that lets users drive different cars. The user will enter their full name, address, and phone number. The user will then be asked which car they wish to drive, with a maximum of five selected cars. The cars have set prices and a total bill will be added up at the end of the program, however, I am currently unable to find a solution to work out the total cost for the user. The program also asks the user how many laps of the race they wish to perform in the car, I have already worked out how to display the total cost of the laps, but need it added to the total cost somehow. Thanks!
Code
cars_list = ["Lamborghini", "Ferrari", "Porsche", "Audi", "BMW"]
cars_prices = {"Lamborghini":50, "Ferrari":45, "Porsche":45, "Audi":30, "BMW":30}
laps_cost = 30
final_cost = []
final_order = {}
cust_num_cars = int(input("Please enter the number of cars you want to drive in this session: "))
while cust_num_cars > 5:
cust_num_cars = int(input("You can only drive a maximum of five cars! Please try again.\n Enter cars: "))
for index in range(cust_num_cars):
print("\nChoose a car type from the following list", cars_list)
select_cars = input("Select a car type: ")
if select_cars in cars_list:
print("\nYou have selected to drive the", {select_cars})
final_cost.append(cars_prices[select_cars])
if select_cars not in cars_list:
print("\n",{select_cars}, "is not in the available list of cars to drive!")
cust_name = input("\nPlease enter your full name: ")
cust_address = input("Please enter your full address: ")
cust_phone_num = int(input("Please enter your mobile phone number: "))
add_laps = input("\nWould you like to drive additional laps? (Yes/No): ")
if add_laps == "Yes":
print("\nYou have selected an additional lap!")
num_of_laps = int(input("Number of additional laps: "))
print("\nYou have selected", num_of_laps, "additional laps!")
final_cost.append(cars_prices[add_laps])
sum = num_of_laps * laps_cost
else:
print("\nYou have selected no additional extra laps.")
print("Total laps cost: £",final_cost)
print("\n----Order & Billing summary----")
print("Customer Full Name:", cust_name)
print("Customer Address:", cust_address)
print("Customer Phone Number", cust_phone_num)
print("Total cost", final_cost.append(cars_prices))
I have tried everything I know in my little experience with Python to work out a final cost. I have worked out the total cost for the number of laps, but can't work out how to add that to the cost of the selected cars and then display a total cost.
First, you can't use a for-loop because when you select a car that isn't in the possibilities you have lost an iteration, use a while loop
# final_cost renamed to car_cost
while len(car_cost) != cust_num_cars:
print("\nChoose a car type from the following list", cars_list)
select_cars = input("Select a car type: ")
if select_cars in cars_list:
print("\nYou have selected to drive the", select_cars)
car_cost.append(cars_prices[select_cars])
else:
print("\n", select_cars, "is not in the available list of cars to drive!")
Then use sum() for the cars cost and add to the laps cost
num_of_laps = 0
add_laps = input("\nWould you like to drive additional laps? (Yes/No): ")
if add_laps == "Yes":
print("\nYou have selected an additional lap!")
num_of_laps = int(input("Number of additional laps: "))
print("\nYou have selected", num_of_laps, "additional laps!")
else:
print("\nYou have selected no additional extra laps.")
total = num_of_laps * laps_cost + sum(car_cost)
print("Total price:", total)
To calculate the total cost, you can use the built-in sum() function, which takes an iterable (like a list) and returns the sum of all its elements. In your case, you can use it to add up all the prices of the cars that the user selected:
total_cost = sum(final_cost)
Then you can add the cost of the laps to the total cost. In your code, the variable sum holds the total cost of the laps. You can add that to the total_cost variable:
total_cost += sum
Hi friend in this program its better to add all of your costs in one variable.
in a list your list's elements are not adding together,
but with variables you can add your cost every time you get a cost like this:
cost_sum = 0
cost = input("Enter a cost: ")
cost_sum += cost

"View Chart" (option 2) option doesn't display the complete shopping cart list

The "for i in range(len(items)):" in elif == 2 part seems to have a problem. It wouldn't display the complete list of items added into my list from the first option 1 statement. I added a few items into my cart through the first statement, but it seems the the program could only display the first item in the list in the option 2 statement.
print("Welcome to the Shopping Cart Program!")
print(("Please select one of the following: "))
print("1. Add item \n2. View cart \n3. Remove item \n4. Compute total \n5. Quit")
items = []
prices = []
choice = 0
answer = int(input("Please enter an action: "))
while choice != 5:
if answer == 1:
item = input("What item you would like to add?: ")
price = float(input(f"What is the price of {item}: "))
items.append(item)
prices.append(price)
print(f"'{item}' has been added to the chart")
print(("Please select one of the following: "))
print("1. Add item \n2. View cart \n3. Remove item \n4. Compute total \n5. Quit")
answer = int(input("Please enter an action: "))
elif answer == 2:
print("The contents of your shopping cart are: ")
for i in range(len(items)):
new = items[i]
print(f"{i}. {new} - ${prices[i]:.2f}")
print(("Please select one of the following: "))
print("1. Add item \n2. View cart \n3. Remove item \n4. Compute total \n5. Quit")
answer = int(input("Please enter an action: "))
elif answer == 3:
remove = int(input("What item would you like to remove?: "))
new_remove = remove - 1
items.pop(new_remove)
print(("Please select one of the following: "))
print("1. Add item \n2. View cart \n3. Remove item \n4. Compute total \n5. Quit")
answer = int(input("Please enter an action: "))
elif answer == 4:
for i in range(len(items)):
total = 0
total += prices[i]
print(f"Your total is: ${prices:.2f}")
print(("Please select one of the following: "))
print("1. Add item \n2. View cart \n3. Remove item \n4. Compute total \n5. Quit")
answer = int(input("Please enter an action: "))
else:
print("Thank you, goodbye!")
exit()
The "for i in range(len(items)):" part seems to have a problem. It wouldn't display the complete list of items added into my list from the first option 1 statement.

Display a list of items without using a list

I am trying to create a program that inputs the price and tax rate and returns the item number, price, tax rate, and item price in an orderly format.
Here is the criteria:
The user can enter multiple items until the user says otherwise.
It calculates and display the total amount of purchased items on the bottom.
The price gets a 3% discount if the total amount is 1000 or more
I am not allowed to use arrays to solve this problem and I must separate the inputs from the outputs on the screen.
An example output is shown here:
Enter the price: 245.78
Enter the tax rate: 12
Are there any more items? (y/n) y
Enter the price: 34
Enter the tax rate: 10
Are there any more items? (y/n) y
Enter the price: 105.45
Enter the tax rate: 7
Are there any more items? (y/n) n
Item Price Tax Rate % Item Price
====================================
1 245.78 12% 275.27
2 34.00 10% 37.40
3 105.45 7% 112.83
Total amount: $425.51
Here is my code so far:
price= float(input('Enter the price: '))
taxRate= float(input('Enter the tax rate: '))
itemPrice = price * (1 + taxRate/100)
acc= 0
while True:
query=input('Are there any more items? (y/n)')
if query== 'y':
price= float(input('Enter the price: '))
taxRate= float(input('Enter the tax rate: '))
itemPrice = price * (1 + taxRate/100)
print(itemPrice )
acc+=1
elif query=='n':
break
print ("Item Price Tax Rate% Item Price")
print ("=========================================")
print( (acc+1) , format(price,'10.2f'), format(taxRate,'10.2f') ,
format(itemPrice,'14.2f') )
for num in range(0,acc):
print (acc, price, taxRate, itemPrice)
The output is shown as this:
Enter the price: 245.78
Enter the tax rate: 12
Are there any more items? (y/n)y
Enter the price: 34
Enter the tax rate: 10
37.400000000000006
Are there any more items? (y/n)y
Enter the price: 105.45
Enter the tax rate: 7
112.8315
Are there any more items? (y/n)n
Item Price Tax Rate% Item Price
=========================================
3 105.45 7.00 112.83
2 105.45 7.0 112.8315
2 105.45 7.0 112.8315
I just have a hard time trying to do this without using an array.. can anyone be of assistance?
You could build a string as a buffer for the output?
Like this:
out = ""
acc = 0
totalAmount = 0
query = 'y'
while query == 'y':
price = float(input('Enter the price: '))
taxRate = float(input('Enter the tax rate: '))
itemPrice = price * (1 + taxRate/100)
acc += 1
totalAmount += itemPrice
out += f"{acc:>4} {price:9.2f} {taxRate:11.2f}% {itemPrice:13.2f}\n"
query = input('Are there any more items? (y/n) ')
print("Item Price Tax Rate% Item Price")
print("=========================================")
print(out)
print(f"Total amount: ${totalAmount:.2f}")
if totalAmount >= 1000:
print(" Discount: 3%")
print(f"Total amount: ${totalAmount*0.97:.2f} (after discount)")

Program not taking in prices properly

Hi im pretty new to Python so I'm guessing im making a pretty obvious mistake here but basically what i'm trying to get my code to do here is to take in 5 products and their prices from the user, the products are working however when the user enters a price that is above 0 the message saying "Please enter a price above 0" is displayed, this is my code below, any help for a newbie is much appreciated thanks.
#Lists of products and prices
products = []
price = [] #declare lists
total = 0 #declare variable to hold total of prices
#function which is used to read in values to each list in turn
#range has been set to read in 5 values
def inputPrice():
for counter in range(0,5):
valid = False
print (counter+1, "Enter 5 Products:")
tempItems = input() #declare temp variable to hold input value
products.append(tempItems) #add this value into our list
#when reading in price if statement is added for validation
print (counter+1, "Enter their prices:")
tempCost = int(input())
if tempCost<=0: #validate input
print ("Incorrect price....")
print ("Please enter a price above 0")
else:
valid = True
price.append(tempCost)
Well the main key here is to loop if the condition didn't occur
products = []
price = [] #declare lists
def inputPrice():
for counter in range(1,6):
print ("Enter Product {} out of 5".format(counter))
tempItems = input() #declare temp variable to hold input value
while tempItems == '': #validate input
print ("Incorrect Product ...")
print ("Please enter a valid product")
tempItems = input()
#when reading in price if statement is added for validation
print ("Enter the price of Product {} out of 5".format(counter))
tempCost = int(input())
while tempCost <=0: #validate input
print ("Incorrect price....")
print ("Please enter a price above 0")
tempCost = int(input())
products.append(tempItems)
price.append(tempCost)
print('products' , products)
print('price' , price)
inputPrice()
Update Your Code add while loop to take prices from user
Lists of products and prices
products = []
price = [] #declare lists
total = 0 #declare variable to hold total of prices
#function which is used to read in values to each list in turn
#range has been set to read in 5 values
def inputPrice():
for counter in range(0,5):
valid = False
print (counter+1, "Enter 5 Products:")
tempItems = input() #declare temp variable to hold input value
products.append(tempItems) #add this value into our list
#when reading in price if statement is added for validation
while True:
print (counter+1, "Enter their prices:")
tempCost = int(input())
if tempCost<=0: #validate input
print ("Incorrect price....")
print ("Please enter a price above 0")
else:
break
else:
valid = True
price.append(tempCost)
inputPrice()

create student database in python

I'm a beginner in python. I have created a database for student in python. I'm not able to get the output for all iterations in dict.
my source code:-
n = int(raw_input("Please enter number of students:"))
student_data = ['stud_name', 'stud_rollno', 'mark1', 'mark2','mark3','total', 'average'] for i in range(0,n):
stud_name=raw_input('Enter the name of student: ')
print stud_name
stud_rollno=input('Enter the roll number of student: ')
print stud_rollno
mark1=input('Enter the marks in subject 1: ')
print mark1
mark2=input('Enter the marks in subject 2: ')
print mark2
mark3=input('Enter the marks in subject 3: ')
print mark3
total=(mark1+mark2+mark3)
print"Total is: ", total
average=total/3
print "Average is :", average
dict = {'Name': stud_name, 'Rollno':stud_rollno, 'Mark1':mark1, 'Mark2':mark2,'Mark3':mark3, 'Total':total, 'Average':average} print "dict['Name']: ", dict['Name'] print "dict['Rollno']: ", dict['Rollno'] print "dict['Mark1']: ", dict['Mark1'] print "dict['Mark2']: ", dict['Mark2'] print "dict['Mark3']: ", dict['Mark3'] print "dict['Total']: ", dict['Total'] print "dict['Average']: ", dict['Average']
if i give no of students as 2, I'm getting dict for 2nd database only and not for 1st one too.
output that i got
Please enter number of students:2
Enter the name of student: a
a
Enter the roll number of student:1
1
Enter the marks in subject 1:1
1
Enter the marks in subject 2:1
1
Enter the marks in subject 3:1
1
Total is:3
Average is :1
Enter the name of student:b
b
Enter the roll number of student:2
2
Enter the marks in subject 1:2
2
Enter the marks in subject 2:2
2
Enter the marks in subject 3:2
2
Total is:6
Average is :2
dict['Name']:b
dict['Rollno']:2
dict['Mark1']:2
dict['Mark2']:2
dict['Mark3']:2
dict['Total']:6
dict['Average']:2
Your current code overwrites dict for every i. In addition, you shouldn't use the name dict as this causes confusion with the data type dict in Python.
One solution for you is to use a list of dictionaries, something like the following:
n = int(raw_input("Please enter number of students:"))
all_students = []
for i in range(0, n):
stud_name = raw_input('Enter the name of student: ')
print stud_name
stud_rollno = input('Enter the roll number of student: ')
print stud_rollno
mark1 = input('Enter the marks in subject 1: ')
print mark1
mark2 = input('Enter the marks in subject 2: ')
print mark2
mark3 = input('Enter the marks in subject 3: ')
print mark3
total = (mark1 + mark2 + mark3)
print"Total is: ", total
average = total / 3
print "Average is :", average
all_students.append({
'Name': stud_name,
'Rollno': stud_rollno,
'Mark1': mark1,
'Mark2': mark2,
'Mark3': mark3,
'Total': total,
'Average': average
})
for student in all_students:
print '\n'
for key, value in student.items():
print '{0}: {1}'.format(key, value)
By adding the responses for each new student onto the end of the list, we track all of them in turn. Finally, we print them out using the keys and values stored in the dictionary. This prints, with your inputs:
Name: a
Rollno: 1
Average: 1
Mark1: 1
Mark2: 1
Mark3: 1
Total: 3
Name: b
Rollno: 2
Average: 2
Mark1: 2
Mark2: 2
Mark3: 2
Total: 6
stud = {}
mrk = []
print("ENTER ZERO NUMBER FOR EXIT !!!!!!!!!!!!")
print("ENTER STUDENT INFORMATION ------------------------ ")
while True :
rno = int(input("enter roll no.. :: -- "))
if rno == 0 :
break
else:
for i in range(3):
print("enter marks ",i+1," :: -- ",end = " ")
n = int(input())
mrk.append(n)
stud[rno] = mrk
mrk = []
print("Records are ------ ",stud)
print("\nRollNo\t Mark1\t Mark2\t Mark3\t Total")
tot = 0
for r in stud:
print(r,"\t",end=" ")
for m in stud[r]:
tot = tot + m
print(m,"\t",end=" ")
print(tot)
tot = 0

Categories