How to sum specific integer values of Python List - python

I'm trying to sum integer values from the list using sum function. Unfortunately, it is adding all the values of the list but not those which I need from the user.
Here is my code:
tourist_attractions = []
distance = []
entry_cost = []
for i in range(3):
tourist_attractions.append (input("Enter Tourist place: "))
tourist_distance =(int(input("Enter distance: ")))
if tourist_distance > 50:
print("Invalid Entry")
continue
if tourist_distance <= 50:
distance.append(tourist_distance)
cost = (float(input("Enter cost: ")))
if cost > 100:
print("cost must be between 1-100")
continue
if cost > 0 or cost <= 100:
entry_cost.append(cost)
print()
for line in tourist_attractions:
print("Place:", line)
for line in distance:
print("Distance:", line)
for line in entry_cost:
print("Cost:", line)
print()
number_of_places_to_visit = int(input("Total number of places to visit: "))
x = 1
while x <= number_of_places_to_visit:
select_tourist_place = input("select tourist place, 0-3: ")
x = x + 1
if select_tourist_place == "0":
print(tourist_attractions[0], distance[0], entry_cost[0])
elif select_tourist_place == "1":
print(tourist_attractions[1], distance[1], entry_cost[1])
elif select_tourist_place == "2":
print(tourist_attractions[2], distance[2], entry_cost[2])
elif select_tourist_place == "3":
print(tourist_attractions[3], distance[3], entry_cost[3])
elif select_tourist_place == "4":
print(tourist_attractions[4], distance[4], entry_cost[4])
print("total cost: " , sum(entry_cost))
Result I am getting:
Enter Tourist place: London
Enter distance: 25
Enter cost: 15
Enter Tourist place: Manchester
Enter distance: 30
Enter cost: 15
Enter Tourist place: Scotland
Enter distance: 50
Enter cost: 20
Place: London
Place: Manchester
Place: Scotland
Distance: 25
Distance: 30
Distance: 50
Cost: 15.0
Cost: 15.0
Cost: 20.0
Total number of places to visit: 2
select tourist place, 0-3: 0
London 25 15.0
select tourist place, 0-5: 1
Manchester 30 15.0
total cost: 50.0
>>>
I can understand, at the moment it is summing up all the appended list of entry_cost and giving me the total of 50 which should be 15 from London and 15 from Manchester. Any help?

print("total cost: " , sum(entry_cost))
definitely states your are iterating over ALL entry costs. You would want to store the selected indices and sum over the entries of those indices.

Related

first python program, having trouble looping [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 months ago.
Improve this question
Basically i want my output from previous value to be new input.
print ("Welcome to Derivative Risk Calculator")
while True:
try:
deposit2 = float(input("\nEnter initial deposit: "))
RSK = float(input("Risk: "))
rate = float(input("Rate: "))
md = float(input("monthly deposits: "))
if deposit2<1:
print ("Not a valid amount, please try again.")
else:
break
except ValueError:
print ("You have not entered a number. Please enter a valid number")
for month in range(24):
amount = (((deposit2 * RSK) * rate) * 30 + md + deposit2)
new_amount = amount
print("%4d%21.2f" % (month, new_amount ))
Current output:
Enter initial deposit: 55000
Risk: 0.38
Rate: 0.025
monthly deposits: 10000
0 80675.00
1 80675.00
2 80675.00
3 80675.00
4 80675.00
5 80675.00
6 80675.00
7 80675.00
8 80675.00
9 80675.00
10 80675.00
11 80675.00
12 80675.00
13 80675.00
14 80675.00
15 80675.00
16 80675.00
17 80675.00
18 80675.00
19 80675.00
20 80675.00
21 80675.00
22 80675.00
23 80675.00
Desired output:
Enter initial deposit: 55000
Risk: 0.38
Rate: 0.025
monthly deposits: 10000
0 80675.00
1 113667.00
2 156063.00
3 210540.00
I basically want each output value of input for next process. For example 80675 becomes the new deposit2 value.
Please help me in this
You simply need to reassign deposit2 to amount for every iteration of the loop. Changing the value of variables is a very common thing to do, and there's nothing wrong with doing it. Also, the variable new_amount is not needed, you can simply just change deposit2 to amount once it is calculated. Here's your code, but fixed:
print ("Welcome to Derivative Risk Calculator")
while True:
try:
deposit2 = float(input("\nEnter initial deposit: "))
RSK = float(input("Risk: "))
rate = float(input("Rate: "))
md = float(input("monthly deposits: "))
if deposit2<1:
print ("Not a valid amount, please try again.")
else:
break
except ValueError:
print ("You have not entered a number. Please enter a valid number")
for month in range(24):
amount = (((deposit2 * RSK) * rate) * 30 + md + deposit2)
deposit2 = amount
print("%4d%21.2f" % (month, deposit2 ))
Set a new "amount" variable equal to the user input (deposit2) to
start and then just update it in the loop.
print ("Welcome to Derivative Risk Calculator")
while True:
try:
deposit2 = float(input("\nEnter initial deposit: "))
RSK = float(input("Risk: "))
rate = float(input("Rate: "))
md = float(input("monthly deposits: "))
if deposit2<1:
print ("Not a valid amount, please try again.")
else:
break
except ValueError:
print ("You have not entered a number. Please enter a valid number")
amount = deposit2
for month in range(24):
amount = amount * RSK * rate * 30 + md + amount
print("%4d%21.2f" % (month, amount))

Program to enter 5 student mark across 4 subjects and output highest average mark of student and subject

I am trying to write a program where i need to be able to enter 5 student marks across 4 different subjects and then output the highest average mark of both the student and the subject.
The desired input and output is :
Student 1 (courses 1-4): 50 60 70 60
Student 2 (courses 1-4): 100 90 87 90
Student 3 (courses 1-4): 70 100 90 90
Student 4 (courses 1-4): 30 65 50 50
Student 5 (courses 1-4): 58 50 74 43
The highest average mark of students: 91.75
The highest average mark of courses: 74.2
The current code I have works for calculating for one subject and not 4. How am I able to enter 4 grades per student to get my desired output.
see my code below:
m1 = int(input("Student 1 (courses 1-4): "))
m2 = int(input("Student 2 (courses 1-4): "))
m3 = int(input("Student 3 (courses 1-4): "))
m4 = int(input("Student 4 (courses 1-4): "))
m5 = int(input("Student 5 (courses 1-4): "))
avg = (m1 + m2+ m3+ m4 + m5) / 5;
avg1 =(m1 + m2+ m3+ m4 + m5) / 20;
print("The Highest average mark of students =", avg)
print("The Highest average mark of courses =", avg1)
This code does the job,
import pandas as pd
import numpy as np
# Part 1
student_num = 5
all_marks = []
for i in range(student_num):
marks = input(f"Student {i + 1} (courses 1-4): ")
all_marks.append(list(map(float, marks.split(" "))))
# Part 2
df = pd.DataFrame(all_marks, columns = ['Marks'])
course_avg = df.Marks.apply(np.mean)
student_avg = df.Marks.apply(np.mean, axis = 1)
The first part of the code converts the input into numbers and stores them into a list. This list is then converted into a data frame in Part 2. I firstly apply np.mean on the columns to find the average for each course, then on the rows to find the average for each student.
You can use idxmax() on both course_avg and student_avg to find the index of the maximum average and find the course/student with the highest average accordingly.
(It's better to store the values in a .xlsx or .csv file directly instead of inputing them through Python this way. Once you have the files, just pass the file path in pd.read_excel() or pd.read_csv() depending upon the format of the file.)
First, create a dictionary to take the inputs of marks for each student. Lets call it d_marks. Create a dictionary to get the average of all students. Let's call it avg_marks. Create a dictionary to get the total marks of all courses. Let's call it avg_course. After that get the max of them. Here's how you can do it:
d_marks = {}
avg_marks = {}
avg_course = {}
for i in range(1,6): # We loop for 5 students
d_marks[f'Student {i} (courses 1-4)'] = list(map(int, input(f"Student {i} (courses 1-4): ").split())) # Split the string and creates an integer list
avg_marks[f'Average of Student {i}'] = sum(d_marks[f'Student {i} (courses 1-4)']) / len(d_marks[f'Student {i} (courses 1-4)']) #Create average dictionary for Students
for j in range(1, len(d_marks[f'Student {i} (courses 1-4)'])+1):
if f'Course {j} sum' in avg_course: # if course sum already in dictionary then add it to previous.
avg_course[f'Course {j} sum'] += d_marks[f'Student {i} (courses 1-4)'][j-1]
else:
avg_course[f'Course {j} sum'] = d_marks[f'Student {i} (courses 1-4)'][j-1] # if course sum not in dictionary then create one.
print("The Highest average mark of students =", max(avg_marks.values()))
print("The Highest average mark of courses =", max(avg_course.values())/ len(d_marks))
Output:
Student 1 (courses 1-4): 50 60 70 60
Student 2 (courses 1-4): 100 90 87 90
Student 3 (courses 1-4): 70 100 90 90
Student 4 (courses 1-4): 30 65 50 50
Student 5 (courses 1-4): 58 50 74 43
The Highest average mark of students = 91.75
The Highest average mark of courses = 74.2

Why am I getting a logical error in a python implemented algorithm

Below is a text-based Python implementation algorithm about a task. The task is,
"Tickets can be purchased for a single passenger or a group of passengers. When making purchase, checks that the number of tickets for the required train journeys up and down a mountain is available. If the tickets are available, calculate the total price including any group discount. Update the screen display and the data for the totals."
This is the description of this task.
"An electric mountain railway makes four return trips every day. In each trip the train goes up the mountain at 9,11,13 and 15. The train returns from the top of the mountain at 10,12,14, and 16. Each train has 6 coaches with 80 seats. Passenger can only buy a return tickets; all tickets must be bought on the day of travel. The cost is $25 for the journey up and $25 for the journey down. Groups of between 10 and 80 passenger inclusive get a free ticket for every 10th passenger, provided they all travel together. Passenger must book their return train journey, as well as the departure train journey, when they buy their tickets. Passengers can return on the next trian down the mountain or a later train. The last train from the top of the mountain has two extra coaches on it.
The train times are displayed on a large screen, together with the number of tickets still available for each train. Every time a ticket is booked the display is updated. When a train is full, the word 'Closed' is displayed instead of the number of tickets available
When the ticket for 15 o'clock is 0 and when I try to book the ticket for 16 o'clock as there are extra tickets available it asks to enter the appropriate number of tickets rather than allowing me to book the ticket.
Could you please tell me why am I getting this error? Would you be able to fix the error, please? Thank you in advance!
FYI, I'm a beginner in this field trying to learn the basic.
train_up_time = [9,11,13,15]
train_down_time = [10,12,14,16]
train_up_ticket =[480]*4
train_down_ticket =[480,480,480,640]
train_up_money =[0.00]*4
train_down_money = [0.00]*4
cost = 25.00
index_up = 0
index_down = 0
ticket_cost = 0
ticket_counter = 0
print("The available time and tickets for the trip Up to the mountain ")
print("Available time\t\t Available tickets \t\t Total money of the trip / $ \n")
for i in range(0, 4):
print(train_up_time[ i ], "\t\t\t", train_up_ticket[ i ], "\t\t\t", train_up_money[ i ])
print("The available time and tickets for the trip Down from the mountain ")
print("Available time\t\t Available tickets \t\t Total money of the trip / $ \n")
for i in range(0, 4):
print(train_down_time[ i ], "\t\t\t", train_down_ticket[ i ], "\t\t\t", train_down_money[ i ])
selling_ticket = int(input("Would you like buy ticket for trip ? Enter 1 else -1. : " ))
while selling_ticket == 1:
time_up = int(input("What time would you like to buy for 9 11 13 15? : "))
while time_up != 9 and time_up != 11 and time_up != 13 and time_up != 15 :
print("Error! please select the appropraite time from the available.")
time_up = int(input("What time would you like buy for 9 11 13 15? : "))
time_down = int(input("What time would you like to return 10 12 14 16? : "))
while time_up > time_down or ( time_down != 10 and time_down != 12 and time_down != 14 and time_down != 16) :
print("Error! please select the appropraite time (you must not select the time below the departure)." )
time_down = int(input("What time would you like to return 10 12 14 16? : "))
for count in range(0,4):
if time_up == train_up_time[ count ]:
index_up = count
if time_down == train_down_time[ count]:
index_down = count
for i in range(0, 4):
if train_up_ticket [ index_up ] == "CLOSED":
train_up_ticket [ index_up ] = 0
if train_down_ticket[ index_down ] == "CLOSED" :
train_down_ticket[ index_down ] = 0
num_ticket = int(input("How many tickets would you like to buy? : "))
while num_ticket > train_up_ticket[ index_up ] or num_ticket > train_down_ticket [ index_down ] :
print("Error! Please recheck the availability of the trian ticket")
num_ticket = int(input("How many tickets would you like to buy? : "))
print("Every 10th passenger is FREE!")
train_up_ticket [ index_up ] = train_up_ticket [ index_up ] - num_ticket
train_down_ticket[ index_down ] = train_down_ticket[ index_down ] - num_ticket
if num_ticket >= 10:
ticket_cost = cost * (num_ticket - (num_ticket/10))
else:
ticket_cost = cost * num_ticket
print("Your trip cost: ", "$", ticket_cost)
print("You need to pay for both ways")
print("Therefore, your total trip cost including the discount is : ", "$", ticket_cost*2 )
train_up_money[ index_up ] = train_up_money[ index_up ] + ticket_cost
train_down_money[ index_down ] = train_down_money[ index_down ] + ticket_cost
if train_up_ticket [ index_up ] == 0:
train_up_ticket [ index_up ] = "CLOSED"
if train_down_ticket[ index_down ] == 0:
train_down_ticket[ index_down ] = "CLOSED"
print("The available time and tickets for the trip Up to the mountain ")
print("Available time\t\t Available tickets \t\t Total money of the trip / $ \n")
for i in range(0, 4):
print(train_up_time[ i ], "\t\t\t", train_up_ticket[ i ], "\t\t\t", train_up_money[ i ])
print("The available time and tickets for the trip Down from the mountain ")
print("Available time\t\t Available tickets \t\t Total money of the trip / $ \n")
for i in range(0, 4):
print(train_down_time[ i ], "\t\t\t", train_down_ticket[ i ], "\t\t\t", train_down_money[ i ])
selling_ticket = int(input("Would you like buy ticket for trip ? Enter 1 else -1. : " ))
There is a problem here:
while num_ticket > train_up_ticket[ index_down ] or num_ticket > train_down_ticket [ index_down ] :
I think it should be index_up for the first comparison.
I do not think there is any logical issue in the code. Here is the sample log from your program:
Would you like buy ticket for trip ? Enter 1 else -1: 1
What time would you like to buy for 9 11 13 15?: 15
What time would you like to return 10 12 14 16?: 16
How many tickets would you like to buy?: 480
Every 10th passenger is FREE!
Your trip cost: $ 10800.0
You need to pay for both ways
Therefore, your total trip cost including the discount is : $ 21600.0
The available time and tickets for the trip Up to the mountain
Available time Available tickets Total money of the trip / $
9 480 0.0
11 480 0.0
13 480 0.0
15 CLOSED 10800.0
The available time and tickets for the trip Down from the mountain
Available time Available tickets Total money of the trip / $
10 480 0.0
12 480 0.0
14 480 0.0
16 160 10800.0
Would you like buy ticket for trip ? Enter 1 else -1: 1
What time would you like to buy for 9 11 13 15?: 9
What time would you like to return 10 12 14 16?: 16
How many tickets would you like to buy?: 160
Every 10th passenger is FREE!
Your trip cost: $ 3600.0
You need to pay for both ways
Therefore, your total trip cost including the discount is : $ 7200.0
The available time and tickets for the trip Up to the mountain
Available time Available tickets Total money of the trip / $
9 320 3600.0
11 480 0.0
13 480 0.0
15 CLOSED 10800.0
The available time and tickets for the trip Down from the mountain
Available time Available tickets Total money of the trip / $
10 480 0.0
12 480 0.0
14 480 0.0
16 CLOSED 14400.0
Would you like buy ticket for trip ? Enter 1 else -1: 1
What time would you like to buy for 9 11 13 15?: 9
What time would you like to return 10 12 14 16?: 14
How many tickets would you like to buy?: 320
Every 10th passenger is FREE!
Your trip cost: $ 7200.0
You need to pay for both ways
Therefore, your total trip cost including the discount is : $ 14400.0
The available time and tickets for the trip Up to the mountain
Available time Available tickets Total money of the trip / $
9 CLOSED 10800.0
11 480 0.0
13 480 0.0
15 CLOSED 10800.0
The available time and tickets for the trip Down from the mountain
Available time Available tickets Total money of the trip / $
10 480 0.0
12 480 0.0
14 160 7200.0
16 CLOSED 14400.0
Would you like buy ticket for trip ? Enter 1 else -1:
I fix some line indentation and you can check my code:
train_up_time = [9,11,13,15]
train_down_time = [10,12,14,16]
train_up_ticket =[480]*4
train_down_ticket =[480,480,480,640]
train_up_money =[0.00]*4
train_down_money = [0.00]*4
cost = 25.00
index_up = 0
index_down = 0
ticket_cost = 0
ticket_counter = 0
selling_ticket = int(input("Would you like buy ticket for trip ? Enter 1 else -1: "))
while selling_ticket == 1:
time_up = int(input("What time would you like to buy for 9 11 13 15?: "))
while time_up != 9 and time_up != 11 and time_up != 13 and time_up != 15 :
print("Error! please select the appropraite time from the available.")
time_up = int(input("What time would you like buy for 9 11 13 15?: "))
time_down = int(input("What time would you like to return 10 12 14 16?: "))
while time_up > time_down or ( time_down != 10 and time_down != 12 and time_down != 14 and time_down != 16) :
print("Error! please select the appropraite time (you must not select the time below the departure)." )
time_down = int(input("What time would you like to return 10 12 14 16?: "))
for count in range(0,4):
if time_up == train_up_time[ count ]:
index_up = count
if time_down == train_down_time[ count]:
index_down = count
for i in range(0, 4):
if train_up_ticket [ index_up ] == "CLOSED":
train_up_ticket [ index_up ] = 0
if train_down_ticket[ index_down ] == "CLOSED" :
train_down_ticket[ index_down ] = 0
# print("time_up: {}, time_down: {}".format(time_up, time_down))
# print("index_up: {}, index_down: {}".format(index_up, index_down))
# print("train_up_ticket: {}, train_down_ticket: {}".format(train_up_ticket, train_down_ticket))
num_ticket = int(input("How many tickets would you like to buy?: "))
while num_ticket > train_up_ticket[ index_up ] or num_ticket > train_down_ticket[ index_down ]:
print("Error! Please recheck the availability of the trian ticket")
num_ticket = int(input("How many tickets would you like to buy?: "))
print("Every 10th passenger is FREE!")
train_up_ticket[ index_up ] = train_up_ticket[ index_up ] - num_ticket
train_down_ticket[ index_down ] = train_down_ticket[ index_down ] - num_ticket
# print("train_up_ticket: {}, train_down_ticket: {}".format(train_up_ticket, train_down_ticket))
if num_ticket >= 10:
ticket_cost = cost * (num_ticket - (num_ticket/10))
else:
ticket_cost = cost * num_ticket
print("Your trip cost: ", "$", ticket_cost)
print("You need to pay for both ways")
print("Therefore, your total trip cost including the discount is : ", "$", ticket_cost*2 )
train_up_money[ index_up ] = train_up_money[ index_up ] + ticket_cost
train_down_money[ index_down ] = train_down_money[ index_down ] + ticket_cost
if train_up_ticket [ index_up ] == 0:
train_up_ticket [ index_up ] = "CLOSED"
if train_down_ticket[ index_down ] == 0:
train_down_ticket[ index_down ] = "CLOSED"
print("The available time and tickets for the trip Up to the mountain ")
print("Available time\t\t Available tickets \t\t Total money of the trip / $ \n")
for i in range(0, 4):
print(train_up_time[ i ], "\t\t\t\t", train_up_ticket[ i ], "\t\t\t\t", train_up_money[ i ])
print("The available time and tickets for the trip Down from the mountain ")
print("Available time\t\t Available tickets \t\t Total money of the trip / $ \n")
for i in range(0, 4):
print(train_down_time[ i ], "\t\t\t\t", train_down_ticket[ i ], "\t\t\t\t", train_down_money[i])
# print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n")
selling_ticket = int(input("Would you like buy ticket for trip ? Enter 1 else -1: "))

Problem with getting right return from function

why does my code return wrong ticket prices? I am supposed to add a time factor as well, but can't get even this to work. This is what I am supposed to do:
"""
Price of one bus ticket
time 6-17, price 2.7, age 16-64
time 18-22, price 3.5, age 16-64
time 23 and 0-5, price 4, age 16-64
for ages 0-2 ticket is free at all times
time 6-17, price 1.7, ages 3-15 and 65 -->
time 18-22, price 2.5, ages 3-15 and 65 -->
time 23 and 0-5, price 3.0, ages 3-15 and 65 -->
"""
def calculate_ticket_price(age):
ticket_price = 0
while True:
if age >= 0 or age <= 2:
ticket_price = 1.0
if age <= 15 or age >= 3 or age >= 65:
ticket_price = 1.5
if age > 15 or age < 65:
ticket_price = 2.7
return float(ticket_price)
def main():
age = 5
price = calculate_ticket_price(age)
print(price)
if __name__ == '__main__':
main()
I think it’ll return the wrong price cause you’re using or where you need an and.
Your first if statement should be:
if ((age >= 0) and (age <= 2)):
Your second if statement should be:
if (((age <= 15) and (age >= 3)) or (age >= 65)):
Then your third one:
if ((age > 15) and (age < 65)):
def calculate_ticket_price(age, time):
while True:
if time >= 6 or time <= 17 and age > 15 or age < 65:
ticket_price = 2.7
elif time >= 18 or time <= 22 and age > 15 or age < 65:
ticket_price = 3.5
elif time >= 23 or time >= 0 or time <= 5 and age > 15 or age < 65:
ticket_price = 4.0
elif time >= 6 or time <= 17 and age <= 15 or age >= 3 or age >= 65:
ticket_price = 1.7
elif time >= 18 or time <= 22 and age <= 15 or age >= 3 or age >= 65:
ticket_price = 2.5
elif time >= 23 or time >= 0 or time <= 5 and age <= 15 or age >= 3 or age >= 65:
ticket_price = 3.0
else:
ticket_price = 0.0
return float(ticket_price)
def main():
age = 5
time = 12
price = calculate_ticket_price(age, time)
print(price)
if __name__ == '__main__':
main()
Made these edits. Should there be and between every >=, <= etc..?
You're using or when I think you want to be using and. For example, this condition:
if age >= 0 or age <= 2:
is going to be true for any positive number, since the first part will always match.
You also want to be using elif so that only one of these blocks will happen. Your last condition:
if age > 15 or age < 65:
ticket_price = 2.7
is going to happen any time the age is under 65 or over 15 (which is going to be every number), so I'd expect that your function just always returns 2.7.
A simpler way to write this function that follows the simple age-only rules you're trying to implement would be:
def calculate_ticket_price(age: int) -> float:
if age <= 2:
return 0.0 # infant price
elif age <= 15:
return 1.5 # youth price
elif age <= 65:
return 2.7 # adult price
else:
return 1.5 # senior price
In this very simple example, only the first condition that matches will return a value, so testing both sides of the range isn't necessary.
You can also check for an age to be within a particular range by writing an expression like 2 < age <= 15, or age > 2 and age < 15, or even age in range(2, 16).
Note that putting everything inside a while loop serves no purpose at all -- avoid having lines of code that don't do anything useful, since they're just one more place for bugs to appear. :)
As far as having the function account for both age and time, I notice that the fare table amounts to giving youth/seniors the same $1 discount regardless of what time it is, so I might simplify it down like this rather than have a different condition for each age/time combination:
def calculate_ticket_price(time: int, age: int) -> float:
# Infants ride free
if age <= 2:
return 0.0
# Youth and seniors get a $1.00 discount
discount = 1.0 if age <= 15 or age >= 65 else 0.0
if 6 <= time <= 17:
return 2.7 - discount
if 18 <= time <= 22:
return 3.5 - discount
if 0 <= time <= 5 or time == 23:
return 4.0 - discount
raise ValueError(f"invalid time {time}!")

For loop is not giving expected output using pandas DataFrame

I want to write a bill program where i want the cgst, sgst from the bill as output. All was going fine but i got stuck on a problem. I want separate names of product from the result of dataframe's output but i am getting only the name of only one product but the amount was sum of two...
Here's my code:
import pandas as pd
count = 0
num = int(input("Type number of items: "))
while count < num:
count += 1
print("-----------------------")
item = input("Enter Item Name: ")
SP = int(input("enter selling price of " + item + ": "))
gstrate = float(input("Enter GST rate: "))
cgst = SP * ((gstrate/2)/100)
sgst = cgst
amount = SP + cgst + sgst
data = pd.DataFrame({
'Item ': [item],
'Price': [SP],
'CGST': [cgst],
'SGST': [sgst],
'Amount payable': [amount],
})
print(data)
what i am getting is this example output:
Type number of items: 2
-----------------------
Enter Item Name: samsung
enter selling price of samsung: 2341
Enter GST rate: 34
-----------------------
Enter Item Name: iphone
enter selling price of iphone: 1234567
Enter GST rate: 15
Item Price CGST SGST Amount payable
0 iphone 1234567 92592.525 92592.525 1419752.05
```
What i want the output to be:
Type number of items: 2
-----------------------
Enter Item Name: iphone
enter selling price of iphone: 1000
Enter GST rate: 18
-----------------------
Enter Item Name: samsung
enter selling price of samsung: 1000
Enter GST rate: 18
Item Price CGST SGST Amount payable
0 iphone 1000 90.0 90.0 1180.0
1 samsung 1000 90.0 90.0 1180.0
As you can see, i am getting only name samsung not iphone and samsung saparatley
In each iteration of your loop you are creating a new data frame with only this loops data and overwitting any data that was in the last data frame. So when you finish your loops and print the dataframe all thats in it is the data from the last iteration of the loop since you created a new dataframe on each iteration.
Instead you could create the data frame before the loop and then just append to the data frame on each iteration of the loop
import pandas as pd
items = []
columns = ['Item', 'Price', 'CGST', 'SGST', 'Amount payable']
df = pd.DataFrame(columns=columns)
num = int(input("Type number of items: "))
for _ in range(num):
print("-----------------------")
item = input("Enter Item Name: ")
SP = int(input("enter selling price of " + item + ": "))
gstrate = float(input("Enter GST rate: "))
cgst = SP * ((gstrate/2)/100)
sgst = cgst
amount = SP + cgst + sgst
data = [item, SP, cgst, sgst, amount]
df_row = dict(zip(columns, data))
df = df.append(df_row, ignore_index=True)
print(df)
OUTPUT
Type number of items: 2
-----------------------
Enter Item Name: iphone
enter selling price of iphone: 1000
Enter GST rate: 18
-----------------------
Enter Item Name: samsung
enter selling price of samsung: 1000
Enter GST rate: 18
Item Price CGST SGST Amount payable
0 iphone 1000 90.0 90.0 1180.0
1 samsung 1000 90.0 90.0 1180.0

Categories