python for loop issue - python

I currently have this as an assignment. I have written the code below, but there seems to be an issue as the calculations keep on adding. Is there a way to restart the for loop?
There are 7 employees. Write a program with nested loops, to ask the yearly salary of each employee for 5 years. Your program should keep track of the highest salary, lowest salary, and calculate the average salary of each employee. After you collect each employees data, display the highest salary, lowest salary, and average salary for that employee.
totalsalary = 0
salaryhigh = 0
salarylow = 10000000
employee = 0
for employee in range(1,4):
print("Please enter the 5 year salaries of Employee#",employee,":")
for year in range(1,6):
salary = int(input('Enter you salary:'+""))
totalsalary = totalsalary + salary
if(salary > salaryhigh):
salaryhigh = salary
if(salary < salarylow):
salarylow = salary
avesalary = totalsalary/5
print('Total Salary entered for 5 years for Employee#',employee,':',totalsalary)
print("Average is:",avesalary)
print("Highest Salary entered is:",salaryhigh)
print("Lowest Salary entered is:",salarylow)
print("------------------------------------")

Your first three lines should be run for each employee, so they should be inside the outer for loop. The fourth line doesn't really do anything: your for-loop resets the employee number. Also, your for-loop does only three employees, but you state that there are seven employees. It's generally recommended that you set the number of employees at the beginning and then use that in the following code, so it's clear what the number represents and it's easier to keep track of and change the number. E.g.
number_of_employees = 7
for employee in range(0,number_of_employees):
...

Related

I want to sum the salary of each department how can i do it?

list_name=[]
list_dep=[]
list_salary=[]
name1='abdo'
list_name.append(name1)
dep1='front_end'
list_dep.append(dep1)
salary1=3000
list_salary.append(salary1)
name2='salm'
list_name.append(name2)
dep2='front_end'
list_dep.append(dep2)
salary2=5000
list_salary.append(salary2)
sum1=0
for department1 in list_dep:
if 'front_end' == department1:
sum1+= list_salary[department1.index('front_end')]
print("Front_end: "+str(sum1))
#I want to collect the price in each section of this program must print 8000 but its print 6000 how to solve this?
I want to sum the salary of each department how can i do it
#I hope my question and heal and was clear
Use a dictionary to hold the running totals for each department. You can use defaultdict to automatically initialize dictionary entries for each department.
from collections import defaultdict
total_salaries = defaultdict(int)
for department, salary in zip(list_dep, list_salary):
total_salaries[department] += salary
print(dict(total_salaries))
the current implementation will make this very hard to maintain and will cause duplication in list_dep as you have appended front_end twice one with dep1 and one with dep2 and the reason you got 6000 because when you ran list_salary[department1.index('front_end')] the department1.index('front_end') returned index 0 in both times so you added the first index in list_salary twice
I recommend changing the structure to use dictionary so it would be like so
list_employees = []
name1='abdo'
dep1='front_end'
salary1=3000
list_employees.append({
"name": name1,
"dep": dep1,
"salary": salary1
})
name2='salm'
dep2='front_end'
salary2=5000
list_employees.append({
"name": name2,
"dep": dep2,
"salary": salary2
})
now if you want to get the total salaries for a specific salary you can use the following
sum1 = 0
for employee in list_employees:
if 'front_end' == employee["dep"]:
sum1 += employee["salary"]
print("Front_end: "+str(sum1))
or if you want to get the salaries for all departments then you can do the following
list_salaries = {}
for employee in list_employees:
if employee["dep"] in list_salaries:
list_salaries[employee["dep"]] += employee["salary"]
else:
list_salaries[employee["dep"]] = employee["salary"]
print(list_salaries)

How do I query a certain list element in python after they meet some conditions using a loop?

I am trying to go through a list (which is set as the parameter in a function) to query the suburb taken as an input from the user. The query is then searched for in the list and if a match is found, the total sales from the suburb's stores are added and the average store sales for that suburb is calculated.
here is the list:
Hm001,6,Frankton,42305.67_
Hm002,10,Glenview,21922.22_
Hm003,7,Silverdale,63277.9_
Hm004,13,Glenview,83290.09_
Hm005,21,Queenwood,81301.82_
Hm006,14,Hillcrest,62333.3_
Hm007,7,Frankton,28998.8_
Hm008,19,Chartwell,51083.5_
Hm009,6,Glenview,62155.72_
Hm0010,8,Enderley,33075.1_
Hm0011,10,Fairfield,61824.7_
Hm0012,15,Rototuna,21804.8-
Hm0013,11,Fairfield,62804.7_
if follows the format: ID, Num of employees, suburb, and sale volume.
I have written the function below but I don't know what is wrong with the function.
def query_suburb_stats(records):
suburb = input("Enter a suburb name: ")
print(suburb)
sales = 0
avg_sales = 0
for match in records:
if suburb.lower() == match[2].lower():
sales += match[3]
avg_sales = avg_sales/sales
if suburb.lower() != records[2].lower():
print(f"No matching name for {suburb}")
else:
print(f"The total sale volume for the stores in {suburb} is: {sales}")
print(f"The average sales for {suburb} is: {avg_sales}")
Your code will work with the following changes:
def query_suburb_stats(records):
suburb = input("Enter a suburb name: ")
print(suburb)
matches = 0
sales = 0
avg_sales = 0
for match in records:
if suburb.lower() == match[2].lower():
matches += 1
sales += float(match[3])
if not matches:
print(f"No matching name for {suburb}")
else:
avg_sales = sales/matches
print(f"The total sale volume for the stores in {suburb} is: {sales}")
print(f"The average sales for {suburb} is: {avg_sales}")
With Glenveiw as input, it will output:
The total sale volume for the stores in Glenview is: 167368.03
The average sales for Glenview is: 55789.34333333333

i need to write a program to read three csv files

and i need to print out:
Every customer.
Output format: Customer: ,
Every product.
Output format: Product: ,
Total amount ordered per product.
Output format: amount:
Total money spent per product.
Output format: gross income:
Total money spent per customer.
Output format: money spent:
customers.csv:
id, name, address
1,"Knut","Knutveien 3"
2,"Lise","Liseveien 7"
products.csv:
id, name, price
1,"banana",5
2,"apple",10
orders.csv:
id, customerid, productid, amount
1,1,1,2
2,2,1,3
3,1,2,4
Python:
file_c = open('customers.csv')
reder_c = csv.reader(file_c)
for i in reder_c:
a = i[1]
b = i[2]
print(f'Customer: {a},{b}')
file_p= open('prudockt.csv')
reder_p = csv.reader(file_p)
for h in reder_p:
w = h[1]
t = h[2]
print(f'product: {w},{t}')
I would be grateful if you could help :)
Use pandas.read_csv(). Look here. (And read the pages #Prune commented.)

Counting entries in a CSV?

I'm just learning Python, and have been having a little bit of trouble with the list functionality of the language. I have a .csv file named purchases.csv and I need to do four things with it:
output the total number of "purchase orders" aka count the total number of entries in the csv
output the average amount of the purchases, showing three decimals.
output the total number of purchases made over 1,800
output the average amount of purchases made that are over 1,800 showing three decimals.
The output needs to look something like:
Total Number of Purchases: xxxx
Amount of Average Purchase: xxxx
Number of Purchase Orders over $1,800: xxxx
Amount of Average Purchases over $1,800: xxxx
So far I've written
import csv
with open('purchases.csv') as csvfile:
readCSV = csv.reader(csvfile,delimiter=',')
total_purchases=[]
for row in readCSV:
total=row[0]
total_purchases.append(total)
print(total_purchases)
my_sum=0
for x in home_runs:
my_sum=my_sum+int(x)
print("The total number of purchases was: ", my_sum)
To find the total number of purchases, but I've hit a wall and can't seem to figure out the rest! I'd love any help and guidance with this...I just can't figure it out!
You need an a series of separate similar for loops, but with if statements to only count the sum conditionally.
Assuming row[0] is your price column:
var sumAbove1800 = 0;
var countAbove1800 = 0;
var totalSum = 0;
var totalPurchases = 0;
for row in readCSV:
var price = float(row[0])
totalPurchases = totalPurchases + 1;
totalSum = totalSum + price;
if(price > 1800):
sumAbove1800 = sumAbove1800 + price;
countAbove1800 = countAbove1800 + 1;
Now to print them out with 3 decimal places:
print("Total Average Price: {:.3f}".format(totalSum / totalPurchases));
print("Total Transactions: {:.3f}".format(totalPurchases));
print("Total Average Price above 1800: {:.3f}".format(sumAbove1800 / countAbove1800 ));
print("Total Transactions above 1800: {:.3f}".format(countAbove1800 ));
Your question is a bit too vague, but here goes anyway.
Unless you are constrained by requirements as this appears to be homework / an assignment, you should give Pandas a try. It's a Python library that helps tremendously with data wrangling and data analysis.
output the total number of "purchase orders" aka count the total number of entries in the csv
This is dead easy with Pandas:
import pandas as pd
df = pd.read_csv('purchases.csv')
num = df.shape[0]
The first two lines are self-explanatory. You build an instance of a Pandas.DataFrame object with read_csv() and store it in df. For the last line, just know that Pandas.DataFrame has a member named shape with the format (number of lines, number of columns), so shape[0] returns the number of lines.
output the average amount of the purchases, showing three decimals.
mean = df['purchase_amount'].mean()
Access column 'purchase_amount' using brackets.
output the total number of purchases made over 1,800
num_over_1800 = df[df['purchase_amount'] > 1800].shape[0]
Slight twist here, just know that this is one way to set a condition in Pandas.
output the average amount of purchases made that are over 1,800
showing three decimals.
mean_over_1800 = df[df['purchase_amount'] > 1800].mean()
This should be self-explanatory from the rest above.

Creating a balance table on Python (edited)

I have this code which display the payment I need to make to student loan depending on different factors but I was wondering how could I display a table telling me for example... if my program says that I'll be making 36 payments of $153.02 to pay a loan of 5000 at 6.4% interest, how do I display a table telling me (payment 1 of 153 this is the remaining balance, this much goes to interest or to principal payment, then the same payment 2 this the new balance... and so on...) In other words a table telling me about those 36 payments and how my balance gets reduced with each payment.
IT DOESN'T HAVE TO BE AS A TABLE MAYBE JUST A LIST... LISTING PAYMENT AFTER PAYMENT UNTILL THE BALANCE IS 0 or -SOMETHING?
This is the code I have so far using python 2.7.3
def calcDebt (principal, interestRate, numPayments, freqPayment):
#This code will make different predictions to pay off student loan
#Input Meanings
'''
Inputs
- interestRate - The Interest Rate of a Loan
- numPayments - The Number of Payments Needed
- principal - The Original Student Loan Amount
- freqPayment - Frequency of Payments Based on Weekly, Monthly, Annually
Returns
- paymentAmount - The Payment Amount Will Be
'''
freqPayment_lookup = {'weekly': 52, 'monthly':12, 'annually':1}
interestRate = float(interestRate) / 100
x = interestRate/freqPayment_lookup[freqPayment]
y = (1.0 + x) ** numPayments
z = x/(y - 1.0)
paymentAmount = (x + z) * principal
return paymentAmount
def main():
a = input('Student Loan Amount: ')
i = input('Student Loan Interest Rate: ')
n = input('Number of Payments: ')
f = None
while f not in ['weekly', 'monthly', 'annually']:
if f:
f = raw_input('Sorry! That is NOT an Option. Please Enter weekly, monthly, or annually: ').lower()
else:
f = raw_input('How Often Do You Want To Make Your Payments? ').lower()
payment = calcDebt(a, i, n, f)
print 'Your %s payment will be %.2f' % (f, payment)
if __name__ == '__main__':
main()
raw_input('Please Press Enter to Exit')
Any ideas?
I would say the best thing for this is to use numpy! here is a general idea for the kind of code you would need:
import numpy as np
#this creates your table with numPayments rows and 4 columns
numPayments = 40
row_index = range(1,numPayments + 1)
real_row_index = []
for i in row_index:
real_row_index.append(str(i))
columns = ["payment number", "remaining balance", "interest amount", "principal amount"]
total_payments = np.chararray((numPayments,3), itemsize=20)
total_payments[:] = "none"
total_payments = np.insert(total_payments, 0, np.array((real_row_index)),1)
total_payments = np.insert(total_payments, 0, np.array((columns)),0)
for row in total_payments[1::,1::]:
#the 1 skips the lables so you don't mess with them
#row[0] will be the number payment column
#row[1] will be the remaining balance column
#row[2] will be the interest amount column
#row[3] will be the principal amount column
now that you have an array of tables set up in a for loop (which I will not finish for you), you can use it in you function to iterate through and for every payment, set the cell to the correct value for the column. So if you calculate the interest amount in a variable interest, you just need to throw this in your for loop to make the interest that belongs in the right place to go there:
row[2] = str(interest)
interest is iterating at the same pace row is, so they should match up if done correctly

Categories

Resources