How to put like this maximum and minimum gross pay and number - python

How to make it right1
How to put like this maximum and minimum gross pay and number

you can create a list of gross_pays and you can get the maximum and minimum from the list
NUM_EMPLOYEES = int(input('Enter number of employees : '))
def main():
hours = []
number = 1
for index in range (NUM_EMPLOYEES):
employee = int(input(f"Enter the hours worked by employee {number}:"))
number += 1
hours.append(employee)
pay_rate= float (input("Enter the hourly pay rate : "))
number = 1
gross_pay2 = []
for index in hours:
gross_pay = index * pay_rate
print (f"Goss pay for employee {number}: ${gross_pay}")
gross_pay2.append(gross_pay)
number += 1
maximum=gross_pay2.index(max(gross_pay2))+1
minimum=gross_pay2.index(min(gross_pay2))+1
print(f'Employee {maximum} gets maximum gross pay: {max(gross_pay2)}')
print(f'Employee {minimum} gets minimum gross pay: {min(gross_pay2)}')
main()

Related

Removing the loops (for, while) in Python

There is a code that calculates after how many years the deposit amount will reach the target amount, taking into account the specified interest rate (the fractional part is discarded).
deposit_amount = int(input('Input deposit amount: '))
annual_percentage = int(input('input annual percentage: '))
final_amount = int(input('Input final amount: '))
year = 0
while deposit_amount < final_amount:
year += 1
deposit_amount = deposit_amount * (100 + annual_percentage) // 100
print('After', year, 'years the amount will be:', deposit_amount)
Question: How to solve the same problem without using cycles? They gave a hint that you can use the "math" library.
Julien and accdias thank you!
Everything would be fine, but according to the condition of the problem, the answer should not be the sum, after n the number of periods, but the number of periods (n). While studying compound interest, I came across logarithms and solved the problem using them using the math library. Most likely, my teacher meant exactly this decision:
deposit_amount = int(input('Input deposit amount: '))
annual_percentage = int(input('input annual percentage: '))
final_amount = int(input('Input final amount: '))
years = ceil(log(final_amount / deposit_amount, annual_percentage))
print('After', years, 'years, your investments will reach the goal and amount to',
round(deposit_amount * annual_percentage**years), 'coins.')

Simple algorithm exercise - inputs and loop

"We want to calculate the amount to be paid by n consumers of electricity in a building. Write an algorithm that takes the cost of kWhour, the number of customers, and the consumption in kWh of each customer. Present the amount to be paid by each of the consumers. Present the total to be paid monthly by all customers in the building."
Ok, we need 2 inputs (number of consumers + cost of consume - kw/hour).
Then, we need to calculate the individual consume and then the total consume, in a month.
Here's what i've got so far (nothing):
costkwh = (input("Type the cost of KhW: ")) #kwh cost
n = int(input("Type the number of consumers: ")) #number of consumer
while n > 0:
consume = int(input('Type your Kw consume, in a month: '))
consumemonthly = (consume*costkwh)
print("Your monthly consume is ", consumemonthly)
Also, how should I do it with FOR loop?
It's my first week in programming so I apologize ya'll for this but its really frustrating... Thank you.
It can be done by initializing a separate variable before the while loop and adding each consumer's consumemonthly to it.
costkwh = (input("Type the cost of KhW: ")) #kwh cost
n = int(input("Type the number of consumers: ")) #number of consumer
totalConsumption = 0
while n > 0:
consume = int(input('Type your Kw consume, in a month: '))
consumemonthly = (consume*costkwh)
print("Your monthly consume is ", consumemonthly)
totalConsumption = totalConsumption + consumemonthly
print(totalConsumption)
If you choose to use a list instead you will need to loop over the list again to find the sum. But you will also retain each consumemonthly in the list just in case you want to do any other calculation based on that. Solution involving list will look like below:
costkwh = (input("Type the cost of KhW: ")) #kwh cost
n = int(input("Type the number of consumers: ")) #number of consumer
while n > 0:
consume = int(input('Type your Kw consume, in a month: '))
consumemonthly = (consume*costkwh)
print("Your monthly consume is ", consumemonthly)
consumemonthly_list.append(consumemonthly)
total_consumption = 0
for ele in range(0, len(consumemonthly_list)):
total_consumption = total_consumption + ele
print(total_consumption)
Hope it helps.

Calculation error at runtime in python loan calculator

I'm trying to build a loan calculator that takes in the amount owed and interest rate per month and the down payment put at the beginning and the monthly installments so it can output how many months do you need to pay off your debt. The program works just fine when I enter an interest_rate below 10% but if I type any number for example 18% it just freezes and gives no output. When I stop running the program it gives me these errors:
Traceback (most recent call last):
File "C:\Users\Khaled\PycharmProjects\interest_payment\main.py", line 35, in <module>
months_to_finish = get_months(price) # this returns the number of months from the counter var
File "C:\Users\Khaled\PycharmProjects\interest_payment\main.py", line 6, in get_months
price = price - installments
KeyboardInterrupt
This is my code:
def get_months(price):
counter = 0
price = price - down_payment
while price > 0:
price = price + price * interest_rate
price = price - installments
counter += 1
return counter
if __name__ == '__main__':
price = float(input("Enter price here: "))
interest_rate = float(input("Enter interest rate here: %")) / 100
while interest_rate < 0:
interest_rate = float(input('Invalid interest rate please try again: %')) / 100
down_payment = int(input("Enter your down payment here: $"))
while down_payment > price or down_payment < 0:
down_payment = int(input('Invalid down payment please try again: $'))
choice = input("Decision based on Installments (i) or Months to finish (m), please write i or m: ").lower()
if choice == 'm':
print('m')
elif choice == 'i':
installments = int(input("What's your monthly installment budget: ")) # get the installments
months_to_finish = get_months(price) # this returns the number of months from the counter var
print(f"It will take {months_to_finish} months to finish your purchase.")
else:
print('Invalid choice program ended')
These are the test values:
Enter price here: 22500
Enter interest rate here: %18
Enter your down payment here: $0
Decision based on Installments (i) or Months to finish (m), please write i or m: i
What's your monthly installment budget: 3000
With an initial principal of $22,500, an interest rate of 18%, a down payment of $0, and a monthly payment of $3,000, it will take an infinite number of months to pay off the loan. After one period at 18% interest, you have accrued $4,050 of interest. Since you're only paying $3,000 per period, you're not even covering the amount of new interest, and the total amount you owe will grow forever. You probably want to check somewhere that the monthly payment is greater than the first month's interest. You could modify your code like this:
if installments < (price - down_payment) * interest_rate:
print("The purchase cannot be made with these amounts.")
else:
months_to_finish = get_months(price)
print(f"It will take {months_to_finish} months to finish your purchase.")
l=[]
n=int(input())
i=0
for i in range(n):
l.append(str(input()))
def long(x):
if x>10:
return print(l[i][0]+str(len(l[i])-2)+l[i][-1])
def short(x):
if x<=10:
return print(l[i])
i=0
for i in range(len(l[i])):
long(len(l[i]))
short(len(l[i]))
continue

how can i make this program show a result for a negative number?

One of my school assignments is to create a program where you can input a minimum number of passengers, a max number of passengers, and the price of a ticket. As the groups of passengers increase by 10, the price of the ticket lowers by 50 cents. At the end it is supposed to show the maximum profit you can make with the numbers input by the user, and the number of passengers and ticket price associated with the max profit. This all works, but when you input numbers that result in a negative profit, i get a run time error. What am i doing wrong? I have tried making an if statement if the profit goes below 0, but that doesn't seem to work. here is my work for you all to see. A lead in the right direction or constructive criticism would be a great help.
#first variables
passengers = 1
maxcapacity = 500
maxprofit = 0
ticketprice = 0
fixedcost = 2500
#inputs and outputs
again = 'y'
while (again == 'y'):
minpassengers = abs(int(input("Enter minimum number of passengers: ")))
maxpassengers = abs(int(input("Enter maximum number of passengers: ")))
ticketprice = abs(float(input("Enter the ticket price: ")))
if (minpassengers < passengers):
minpassengers = passengers
print ("You need at least 1 passenger. Setting minimum passengers to 1.")
if (maxpassengers > maxcapacity):
maxpassengers = maxcapacity
print ("You have exceeded the max capacity. Setting max passengers to 500.")
print ("Passenger Run from", minpassengers, "to", maxpassengers, "with an initital ticket price of $",format (ticketprice, "7,.2f"), "with a fixed cost of $2500.00\n"
"Discount per ticket of $0.50 for each group of 10 above the starting count of", minpassengers, "passengers")
for n in range (minpassengers, maxpassengers + 10, 10):
ticketcost = ticketprice - (((n - minpassengers)/10) * .5)
gross = n * ticketcost
profit = (n * ticketcost) - fixedcost
print ("Number of \nPassengers", "\t Ticket Price \t Gross \t\t Fixed Cost \t Profit")
print (" ", n, "\t\t$", format (ticketcost, "7,.2f"), "\t$", format (gross, "5,.2f"), "\t$", format(fixedcost, "5,.2f"), "\t$", format (profit, "5,.2f"))
if (profit > maxprofit):
maxprofit = profit
maxpass = n
best_ticket = ticketcost
print ("Your max profit is $", format (maxprofit, "5,.2f"))
print ("Your max profit ticket price is $", format (best_ticket,"5,.2f"))
print ("Your max profit number of passengers is", maxpass)
again = input ("Run this again? (Y or N): ")
again = again.lower()
print ("\n")
This is happening because the condition profit > maxprofit never evaluates to True in the situation where your profit is negative, because maxprofit is set to 0 up at the top. This in turn means that best_ticket never gets assigned a value in this case, and so Python can't print it out later.
You could avoid this problem either by setting a default value for best_ticket earlier in the program:
best_ticket = 0
or by adding a condition that you only print out a best ticket price when best_ticket is set:
# Earlier in the program.
best_ticket = None
if best_ticket is not None:
print("Your max profit ticket price is $", format(best_ticket,"5,.2f"))
Also, FYI, the same problem will occur for the maxpass variable.
Your error is telling you the problem
NameError: name 'best_ticket' is not defined
You define best_ticket in this block
if (profit > maxprofit):
maxprofit = profit
maxpass = n
best_ticket = ticketcost
Regardless of the truth of that statement, you reference best_ticket below
print ("Your max profit ticket price is $", format (best_ticket,"5,.2f"))
Your error is probably because the variable you are outputting is defined in a spot that doesn't get executed.
if (profit > maxprofit):
maxprofit = profit
maxpass = n
best_ticket = ticketcost
So, whenever the if condition is False, best_ticket never gets assigned.
Try adding best_ticket = 0 at the top of your code.
ticketprice = abs(float(input("Enter the ticket price: ")))
best_ticket = -1 #nonsense value that warns you whats happening.

How do I get the sum of all numbers in a range function in Python?

I can't figure out how to take x (from code below) and add it to itself to get the sum and then divide it by the number of ratings. The example given in class was 4 ratings, with the numbers being 3,4,1,and 2. The average rating should be 2.5, but I can't seem to get it right!
number_of_ratings = eval(input("Enter the number of difficulty ratings as a positive integer: ")) # Get number of difficulty ratings
for i in range(number_of_ratings): # For each diffuculty rating
x = eval(input("Enter the difficulty rating as a positive integer: ")) # Get next difficulty rating
average = x/number_of_ratings
print("The average diffuculty rating is: ", average)
Your code doesn't add anything, it just overwrites x in each iteration. Adding something to a variable can be done with the += operator. Also, don't use eval:
number_of_ratings = int(input("Enter the number of difficulty ratings as a positive integer: "))
x = 0
for i in range(number_of_ratings):
x += int(input("Enter the difficulty rating as a positive integer: "))
average = x/number_of_ratings
print("The average diffuculty rating is: ", average)
try:
inp = raw_input
except NameError:
inp = input
_sum = 0.0
_num = 0
while True:
val = float(inp("Enter difficulty rating (-1 to exit): "))
if val==-1.0:
break
else:
_sum += val
_num += 1
if _num:
print "The average is {0:0.3f}".format(_sum/_num)
else:
print "No values, no average possible!"

Categories