TCS DCA question : Mini grocery store in python - python

import pandas as pd
id_num=[101,102,103,104]
price = [40,50,60,70]
stock = [10,14,14,13]
new = pd.DataFrame(
{'id_num':id_num,
'price':price,
'stock':stock
})
try:
inp_num=int(input("enter the id number:"))
qua = int(input("enter the quantity:"))
except ValueError:
print("Invalid")
if([new['id_num']==inp_num]):
total = price*qua
print(total)
Explanation
Program : enter the id and stock value that customer wants to buy and calculate the price according the quantity Example input : 1 >
id = 101
quantity = 5 output :
total price = 200 2> id = 103 quantity = 20 output ; out of stock"

Here is the final solution
id_num=[101,102,103,104]
price = [40,50,60,70]
stock = [10,14,14,13]
try:
inp_num=int(input("enter the id number:"))
qua = int(input("enter the quantity:"))
except ValueError:
print("Invalid")
if inp_num in id_num:
ind = id_num.index(inp_num)
if qua <= stock[ind]:
total = price[ind]*qua
stock[ind] -= qua
print(total)
else:
print("out of stock")
else:
print("no product available")

import pandas as pd
def new_funct(new):
try:
inp_num=int(input("enter the id number:"))
qua = int(input("enter the quantity:"))
except ValueError:
print("Invalid")
list_of_value = new['id_num'].tolist()
if inp_num in list_of_value:
index_prod = list_of_value.index(inp_num)
if qua <= new['stock'][index_prod]:
total = new['price'][index_prod]*qua
new.at['stock', index_prod] = new['stock'][index_prod] - qua
print("total price =",total)
else:
print("out of stock")
else:
print("no product available")
return new
id_num=[101,102,103,104]
price = [40,50,60,70]
stock = [10,14,14,13]
new = pd.DataFrame({'id_num':id_num,'price':price,'stock':stock})
while True:
new_funct(new)

Related

How do find the top of a row using pandas

First of all I would just like to mention - I am a beginner, I am still learning. This code is probably an abomination and I might be missing something obvious, please be nice.
My question is this. I have written a for loop to find the highest earning employee but I would like for the user to select a start and end date for their earnings to be calculated.
So for example my program should be able to calculate an employees earning from 01/05/2021 to 09/05/2021.
The only thing I'm struggling with is how to reference the date, I've been googling for an hour but the responses are just too complicated for me.
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime as dt
df = pd.read_csv('Task_4a_data.csv', index_col='ID')
#main menu
def menu():
print("\t\t****MAIN MENU****")
print('1) Enter sales records')
print('2) Run reports')
x = int(input(""))
return x
#reports menu
def menu2():
print("**** Reports Dashboard ****")
print("1. Individual Employee Report")
print("2. Show employees with the highest sales value")###########
x = int(input(""))
return x
def ind_emp_check(df_r, id, date1, date2):
df_r = df_r.loc[df.index == id]
df_r = df_r.T[3:]
df_r.reset_index(inplace=True)
df_r['ID1'] = pd.to_datetime(df_r['index'], format='%d/%m/%Y')
date1 = pd.to_datetime(date1, format='%d/%m/%Y')
date2 = pd.to_datetime(date2, format='%d/%m/%Y')
mask = (df_r['ID1'] >= date1) & (df_r['ID1'] <= date2)
df_search = df_r.loc[mask]
print(df_search)
print('Total by id = {} is {}'.format(id, sum(df_search[id])))
plt.bar(df_search['index'], df_search[id])
plt.xticks(rotation=90)
plt.show()
y = menu()
while y == 1 or y == 2:
if y == 1:
try:
ID = int(input("Enter the Staff ID "))
if ID not in df.index.values:
print('yes')
date1 = input("Enter Date in dd/mm/yy: ")
day, month, year = date1.split("/")
date1 = datetime.date(int(year), int(month), int(day))
if datetime.datetime.strptime(date1.strftime('%d/%m/%Y'), '%d/%m/%Y') > datetime.datetime.strptime(
dt.today().strftime('%d/%m/%Y'), '%d/%m/%Y'):
print("Date is in the future")
else:
cost = float(input("Enter the cost : "))
df.loc[ID, date1.strftime('%d/%m/%Y')] = cost
# df.to_csv('test2.csv')
except:
print("\n\nError Occurred Please try again\n\n")
y = menu()
if y == 2:
x = menu2()
if x == 1:
try:
id = int(input("Enter the Employee Id : "))
s_date = input("Enter Starting Date in dd/mm/yyyy: ")
day, month, year = s_date.split("/")
s_date = datetime.date(int(year), int(month), int(day))
e_date = input("Enter End Date in dd/mm/yyyy: ")
day, month, year = e_date.split("/")
e_date = datetime.date(int(year), int(month), int(day))
s_date = datetime.datetime.strptime(s_date.strftime('%d/%m/%Y'), '%d/%m/%Y')
e_date = datetime.datetime.strptime(e_date.strftime('%d/%m/%Y'), '%d/%m/%Y')
ind_emp_check(df, id, s_date, e_date)
except:
print("\n\nError Occurred Please try again\n\n")
x = menu2()
elif x == 2:
s_date = input("Enter Starting Date in dd/mm/yyyy: ")
e_date = input("Enter End Date in dd/mm/yyyy: ")
total = 0
totals = []
for r in df.index:
for i in (df.loc[r]):
if PLACEHOLDER == e_date:
break
try:
total+=i
total = int(total)
except:
pass
totals.append(total)
total=0
largest_number = totals[0]
for number in totals:
if number > largest_number:
largest_number = number
print(largest_number)
else:
x = menu2()
else:
x = menu()
x = menu()```

Encountered "EOFError: EOF when reading a line" on PythonAnywhere

I was trying to run a script in PythonAnywhere (this is my first time using it), but it said my code had an EOF error. When I run it in flask_app.py, it works, but when I refresh the website and try it on the site itself, it gives me this error.
Error running WSGI application
EOFError: EOF when reading a line
File "/var/www/samtheconqueror_pythonanywhere_com_wsgi.py", line 16, in <module>
from flask_app import app as application # noqa
File "/home/SamtheConqueror/mysite/flask_app.py", line 11, in <module>
IVI = float(input("Enter the initial value of investment: "))
Is this because I am using flask?
I am trying to calculate the return on investment in the script.
Here is the code:
Num = 0
IVI = 0
FVI = 0
Dvi = 0
Com = 0
age = 0
loop1 = True
while loop1:
try:
IVI = float(input("Enter the initial value of investment: "))
loop1 = False
except ValueError:
print("Invalid.")
print("")
loop2 = True
while loop2:
try:
FVI = float(input("Enter the final value of investment: "))
loop2 = False
except ValueError:
print("Invalid.")
print("")
loop3 = True
while loop3:
try:
Num = int(input("Enter the number of shares purchased: "))
loop3 = False
except ValueError:
print("Invalid.")
print("")
Cost = IVI * Num
loop4 = True
while loop4:
try:
Dvi = float(input("Enter amount earned from dividends: "))
loop4 = False
except ValueError:
print("Invalid.")
print("")
loop5 = True
while loop5:
try:
Com = float(input("Enter the amount spent on commissions: "))
loop5 = False
except ValueError:
print("Invalid.")
ROI1 = (FVI - IVI) * Num + Dvi - Com
ROI2 = ROI1 / (IVI * Num)
ROI3 = ROI2 * 100
print(ROI3)
print_value = str(ROI3)
print("")
print("ROI = " + print_value + "%")
print("")
t_f = input("Calculate Annualized ROI(t/f)?")
loop6 = True
while loop6:
if t_f == "t":
loop6 = False
pass
elif t_f == "f":
exit()
else:
print("Invalid")
print("")
loop7 = True
while loop7:
try:
age = float(input("Enter number of years you have held this investment for: "))
loop7 = False
except ValueError:
print("Invalid.")
print("")
years = 1 / age
aROI = (1 + ROI2)
aROI0 = pow(aROI, years)
aROI1 = (aROI0 - 1) * 100
print_value2 = str(aROI1)
print("Annualized ROI = " + print_value2 + "%")

invoice (receipt) program in python. How to prevent overwriting old values

I'm a new learner for python and I'm trying to make a program that prints in invoice of all the items + their price + their quantity. each item is in separate line.
I have got tot he point where I print each item in a line, but I keep overwriting the old values by the last value entered. how can I prevent this?
this is the code:
print("This program prints your invoices."
"\nPlease enter the item identification, item cost and quantity sold when promted."
"\nEnter 'done' when no more items"
"\n=========================================")
saveqty= ()
savetprice=()
qtysum= 0 #quantity =qty for short
sumprice=0
list1 = []
totalprice=0
while True:
itemid = input('Item identification: ')
if itemid == "done":
break
if len(itemid)<3:
print("item identification should be at least 3 characters long, try again")
continue
else:
list11 = list[itemid]
list1 +=[itemid]
qtysold = input("Qty sold: ")
try:
qtysold =int(qtysold)
except ValueError:
print("must be an integer value, try again")
continue
qtysum+=qtysold
try:
itemprice = float(input("Item price: "))
savetprice= (itemprice)
except ValueError:
print("item price must be numerical value, try again")
continue
totalprices= (qtysold*itemprice)
totalprice+=totalprices
for elem in list1:
print(qtysold,'x ',elem, '# ', savetprice, 'SAR', '===', totalprices)
total = sumprice
itemtotal = qtysum
print("=========================================\nNo. of items purchased: ", itemtotal,"\nTotal price is: ", totalprice, "SAR")
Below is the code that fixes your problem
print("This program prints your invoices."
"\nPlease enter the item identification, item cost and quantity sold when promted."
"\nEnter 'done' when no more items"
"\n=========================================")
saveqty = ()
savetprice = ()
qtysum = 0 # quantity =qty for short
sumprice = 0
list1 = []
totalprice = 0
while True:
itemid = input('Item identification: ')
if itemid == "done":
break
if len(itemid) < 3:
print("item identification should be at least 3 characters long, try again")
continue
qtysold = input("Qty sold: ")
try:
qtysold = int(qtysold)
except ValueError:
print("must be an integer value, try again")
continue
qtysum += qtysold
try:
itemprice = float(input("Item price: "))
savetprice = (itemprice)
except ValueError:
print("item price must be numerical value, try again")
continue
totalprices = (qtysold * itemprice)
totalprice += totalprices
list1.append((itemid, qtysold, savetprice, totalprices))
for elem, qtysold, savetprice, totalprices in list1:
print(qtysold, 'x ', elem, '# ', savetprice, 'SAR', '===', totalprices)
total = sumprice
itemtotal = qtysum
print("=========================================\nNo. of items purchased: ", itemtotal, "\nTotal price is: ", totalprice, "SAR")
Output:
This program prints your invoices.
Please enter the item identification, item cost and quantity sold when promted.
Enter 'done' when no more items
=========================================
Item identification: 123
Qty sold: 5
Item price: 20
Item identification: 456
Qty sold: 3
Item price: 30
Item identification: done
5 x 123 # 20.0 SAR === 100.0
3 x 456 # 30.0 SAR === 90.0
=========================================
No. of items purchased: 8
Total price is: 190.0 SAR
Note: You need to save all the information (e.g., itemid, qtysold) in the while loop to list1 if you want to print them out later. Otherwise, qtysold and totalprices will always keep the last value when exiting the while loop. This explains the reason for the problem you are facing.

Line (39) IndexError: pop index out of range

This is my code:
#cart is a list, easy to append
cart=['S/n'," "*10, 'Items', " " * 14, "Quantity", " " * 8, "Unit Price", " " * 8, "Price"]
total_pricee = 0
pricee = 0
count=1
from datetime import datetime
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print( "Date & Time:",dt_string)
print('Welcome to tis program.Please use the numbers to navigate!')
def invalid_input(Quantitiy):
while Quantitiy > '5' or Quantitiy < '1':
Quantitiy = input("Please key in a valid quantity(Between 1 to 5):")
if Quantitiy < '5' and Quantitiy > '1':
New_Quan=Quantitiy
#This part of function checks if item quantity is between 1 and 5
return Quantitiy
break
while not Quantitiy.isdigit():
Quantitiy = input('Invalid input.Please enter a valid input:')
while Quantitiy.isdecimal() == False:
break
#This part of function checks that item quantity is not a decimal
return Quantitiy
def add_to_cart(name, Quantity, price):
global total_pricee, pricee,count,cart
#This function adds items to cart
cart.append('\n')
cart.append('{:<10s}'.format(str(count) + '.'))
cart.append('{:^10s}'.format(name))
cart.append('{:^30s}'.format(str(Quantity)))
cart.append('$'+str(price)+'0')
pricee = '{:.2f}'.format(float(Quantity) * price)
pricee
cart.append('{:^34s}'.format('$' +str(pricee)))
total_pricee += float(pricee)
count = count +1
print(name,"has been added to cart!")
def remove_from_cart(Item_number):
global count
while True:
if Item_number>(count-1):
print('Please key in a valid S/n!')
(Item_number)=int(input('Please enter the S/n of the item you want to remove:'))
if Item_number==2:
cart.pop(9)
cart.pop(9)
cart.pop(9)
cart.pop(9)
cart.pop(9)
cart.pop(9)
if Item_number<=(count-1):
x=(6*(Item_number-2))+9
cart.pop(x)
cart.pop(x)
cart.pop(x)
cart.pop(x)
cart.pop(x)
cart.pop(x)
print('Item has been sucsussfully removed from cart!')
if count==1:
print('Please add an item to cart first!')
while True:
print('[1] Water')
print('[2] rice')
print('[3] ice')
print('[0] View Cart and Check-out')
print("[4] Remove object from cart")
opt = input("Select option:")
if opt > '4' or opt < '0':
print("Select valid option!")
if opt == '3':
qunt = input("Please key in a quanity for your item:")
qunt =invalid_input(qunt)
nam3 = "Ice"
add_to_cart(nam3, qunt, 2.00)
if opt == '1':
qunt2 = input("Please key in a quanity for your item:")
qunt2=invalid_input(qunt2)
nam2 = " Water"
add_to_cart(nam2, qunt2, 3.00)
if opt == '2':
qunt1 = input("Please key in a quanity for your item:")
qunt1=invalid_input(qunt1)
nam1 = "Rice"
add_to_cart(nam1, qunt1, 5.00)
if opt == "0":
print(*cart)
print("Total price until now:", "$" + '{:.2f}'.format(total_pricee))
print('Would you like to check out?')
print('[1] Yes')
print('[2] No')
checkout=input("Please select an option:")
if checkout=='1':
print('You have bought',count,'items')
print("Please pay""$" + '{:.2f}'.format(total_pricee))
print('Thank you for shopping with us!')
exit()
if opt=="4":
print(*cart)
remove=input("Please key in the S/n of the item you want to remove:")
remove_from_cart(int(remove))
print(*cart)
I do not know why this error is occurring .I am a bit new to python and have not encounter such error before.Please tell me how to improve my code such that this error does not occur again. Thanks to anyone who helps!
For eg:
S/n Items Quantity Unit Price Price
1. Rice 3 $5.00 $15.00
2. Rice 4 $5.00 $20.00
3. Water 4 $3.00 $12.00
and user wants to remove the second item, it the output after the function has been carried out should be
S/n Items Quantity Unit Price Price
1. Rice 3 $5.00 $15.00
2. Water 4 $3.00 $12.00
I can't paste the formatted code in the comment, I will write it in the answer, I hope to understand.
The list is very inconvenient to do this operation
In [1]: import pandas as pd
In [5]: d = pd.DataFrame([['Rice', 3, '$5.0', '$15.0'], ['Water', 4, '$3.0', '$12.0']], columns=['Items', 'Quantity', 'Unit Price', 'Price'])
In [6]: d
Out[6]:
Items Quantity Unit Price Price
0 Rice 3 $5.0 $15.0
1 Water 4 $3.0 $12.0
In [7]: d.drop(0)
Out[7]:
Items Quantity Unit Price Price
1 Water 4 $3.0 $12.0
In [16]: d.append([{"Items": "Rice", "Quantity": 3, "Unit Price": "$5.0", "Price": "$20.0"}], ignore_index=True)
Out[16]:
Items Quantity Unit Price Price
0 Rice 3 $5.0 $15.0
1 Water 4 $3.0 $12.0
2 Rice 3 $5.0 $20.0
Here's my code, maybe for your reference :)
from itertools import repeat
class Cart():
def __init__(self):
self.header = ['S/N', 'Items', 'Quantity', 'Unit Price', 'Price']
(self.SN_width, self.item_width, self.quantity_width,
self.unit_price_width, self.price_width
) = self.widths =[13, 19, 16, 18, 20]
self.item_list = {}
def get_serial_no(self):
i = 1
while i in self.item_list:
i += 1
return i
def add(self, item, quantity, unit_price):
serial_no = self.get_serial_no()
self.item_list[serial_no] = (item, quantity, unit_price)
def delete(self, serial_no):
del self.item_list[serial_no]
lst = sorted(self.item_list.keys())
new_list = {i+1:self.item_list[key] for i, key in enumerate(lst)}
self.item_list = new_list
def sum_all(self):
all_price = 0
for item, quantity, unit_price in self.item_list.values():
all_price += quantity*unit_price
return all_price
def adjust(self, items):
line = ['']*5
for i in range(5):
if i == 0:
line[0] = items[0].center(self.widths[0])
elif i == 1:
line[1] = items[1].ljust(self.widths[1])
else:
line[i] = items[i].rjust(self.widths[i])
return ' '.join(line)
def __repr__(self):
keys = sorted(self.item_list.keys())
title = self.adjust(self.header)
seperator = ' '.join(list(map(str.__mul__, repeat('-'), self.widths)))
result = [title, seperator]
for key in keys:
lst = self.item_list[key]
items = [str(key), lst[0], '%.3f'%lst[1], '$%.3f'%lst[2],
'$%.3f'%(lst[1]*lst[2])]
line = self.adjust(items)
result.append(line)
return '\n'.join((' ', '\n'.join(result), ' ',
'Total price: $%.3f'%self.sum_all(), ' '))
cart = Cart()
new_items = [
('apple', 10, 1), ('orange', 5, 0.5), ('banana', 20, 0.2),
('avocado', 5, 0.2), ('cherry', 1, 20), ('grape', 1, 15), ('lemon', 5, 1)]
for item in new_items:
cart.add(*item)
while True:
print(cart)
try:
action = input('Add(A), Delete(D), Exit(E) :').strip().lower()
except:
continue
if action == 'a':
try:
item = input('Name of item: ').strip()
quantity = float(input('Quantiy: ').strip())
unit_price = float(input('Unit Price: ').strip())
except:
print('Wrong data for item !')
continue
cart.add(item, quantity, unit_price)
elif action == 'd':
key = input('Serial No. to be deleted: ').strip()
try:
key = int(key)
if key in cart.item_list:
cart.delete(int(key))
continue
except:
pass
print('Wrong serial No. !')
elif action == 'e':
break
else:
print('Wrong action !')
print('Bye !')
``

Return multiple values in a function

I am doing a University project to create a plan ordering ticket program, so far these are what I have done:
First, this is the function finding the seat type:
def choosingFare():
print("Please choose the type of fare. Fees are displayed below and are in addtion to the basic fare.")
print("Please note choosing Frugal fare means you will not be offered a seat choice, it will be assigned to the ticketholder at travel time.")
listofType = [""] * (3)
listofType[0] = "Business: +$275"
listofType[1] = "Economy: +$25"
listofType[2] = "Frugal: $0"
print("(0)Business +$275")
print("(1)Economy +$25")
print("(2)Frugal: $0")
type = int(input())
while type > 2:
print("Invalid choice, please try again")
type = int(input())
print("Your choosing type of fare is: " + listofType[type])
if type == 0:
price1 = 275
else:
if type == 1:
price1 = 25
else:
price1 = 0
return price1, listofType[type]
And this is a function finding the destination:
def destination():
print("Please choose a destination and trip length")
print("(money currency is in: Australian Dollars: AUD)")
print("Is this a Return trip(R) or One Way trip(O)?")
direction = input()
while direction != "R" and direction != "O":
print("Invalid, please choose again!")
direction = input()
print("Is this a Return trip(R) or One Way trip(O)?")
if direction == "O":
print("(0)Cairns oneway: $250")
print("(2)Sydney One Way: $420")
print("(4)Perth One Way: $510")
else:
print("(1)Cairns Return: $400")
print("(3)Sydney Return: $575")
print("(5)Perth Return: $700")
typeofTrip = [""] * (6)
typeofTrip[0] = "Cairns One Way: $250"
typeofTrip[1] = "Cairns Return: $400"
typeofTrip[2] = "Sydney One Way: $420"
typeofTrip[3] = "Sydney Return: $575"
typeofTrip[4] = "Perth One Way: $510"
typeofTrip[5] = "Perth Return: $700"
trip = int(input())
while trip > 5:
print("Invalid, please choose again")
trip = int(input())
if trip == 0:
price = 250
else:
if trip == 1:
price = 400
else:
if trip == 2:
price = 420
else:
if trip == 3:
price = 574
else:
if trip == 4:
price = 510
else:
price = 700
print("Your choice of destination and trip length is: " + typeofTrip[trip])
return price, typeofTrip[trip]
And this is the function calculating the total price:
def sumprice():
price = destination()
price1 = choosingFare()
price2 = choosingseat()
sumprice = price1 + price2 + price
print("How old is the person travelling?(Travellers under 16 years old will receive a 50% discount for the child fare.)")
age = float(input())
if age < 16 and age > 0:
sumprice = sumprice / 2
else:
sumprice = sumprice
return sumprice
The error I have:
line 163, in <module> main()
line 145, in main sumprice = sumprice()
line 124, in sumprice
sumprice = price1 + price2 + price
TypeError: can only concatenate tuple (not "int") to tuple
Can someone help me? I am really stuck.
I can't return all the
These functions return 2 values each: destination(), choosingFare(), choosingseat().
Returning multiple values at once returns a tuple of those values:
For example:
return price, typeofTrip[trip] # returns (price, typeofTrip[trip])
So while calculating the sum of all prices, you need to access price, price1, price2 from the tuples:
sumprice = price1[0] + price2[0] + price3[0]
Alternatively: You can edit the code to return list/ dictionary or some other data structure as per your convenience.
First let me explain what happends when you write. return price, typeofTrip[trip].
The above line will return a tuple of two values.
Now for sumprice I think what you want is sum of all prices. So you just want to sum first element of returned values.
This should work for your case.
sumprice = price1[0] + price2[0] + price3[0]

Categories