Simple algorithm exercise - inputs and loop - python

"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.

Related

I have just started coding and am stuck solving this python problem

Write a program that always asks the user to enter a number. When the user enters the negative number -1, the program should stop requesting the user to enter a number. The program must then calculate the average of the numbers entered excluding the -1.
This is what I have come up with so far
num = int(input("How many number's are there?"))
total_sum = 0
avg = total_sum / num
for n in range (num):
number = float(input("Enter a number"))
while number <0:
print = ("Average is", avg)
number >0
print(number)
total_sum += number
avg = total_sum / num
print = ("Average is", avg)
I need it to stop at -1 one and still give an average of the numbers listed.
Easy.
emp = []
while True:
ques = int(input("Enter a number: "))
if ques != -1:
emp.append(ques)
continue # continue makes the code go back to beginning of the while loop
else:
if len(emp) != 0:
avg = sum(emp) / len(emp) # average is the sum of all elements in the list divided by the number of elements in said list
print(f"Average of all numbers entered is {avg}")
break
else:
print("Give me at least one number that's not -1")
continue # emp is empty we need at least one number to calculate the average so we go back to the beginning of the loop

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.')

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

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()

Python CD annual precentage

I am doing this assignment. when i input the number of months it is one printing one month. rather it be 5 months or 17 months its only printing 1 months total.
https://drive.google.com/file/d/0B_K2RFTege5uZ2M5cWFuaGVvMzA/view?usp=sharing
Here is what i have so far what am i over looking thank you
calc = input('Enter y or n to calculate your CDs worth?')
month= int(input('Select your number of months'))
while calc == 'y':
while month > 0:
amount = int(input('Please enter the amount:'))
percent= float(input('Please enter the annual percentage:'))
calc= amount + amount* percent/ 1200
print(calc)
You would want to use a for loop rather than while in this sense since you are doing a set amount of operations. You also were reusing calc and assigning calc to from a String to a float, generally a bad idea. The main problem is the formula builds upon the previously calculated number, it starts off with the initial amount entered, 10000 + 10000 * 5.75 / 1200 = 10047.91, then uses 10047.91 in the next calculation, instead of 10000, you never were reusing the previously calculated number, so you weren't getting the right answer. This should do it:
calc = input('Enter y or n to calculate your CDs worth?')
if calc == 'y':
month = int(input('Select your number of months'))
amount = int(input('Please enter the amount:'))
percent = float(input('Please enter the annual percentage:'))
for i in range(month):
if i == 0:
calcAmount = amount + ((amount * percent) / 1200)
else:
calcAmount = calcAmount + ((calcAmount * percent) / 1200)
print calcAmount

How do I keep a running total for every time the tuition increases and add those values together?

College Cost Estimator
def calculateTuitionIncrease(cost, increase, years):
#This function calculates the projected tuition increase for each year.
counter = 0
while counter <= years:
increasedCost = (cost)+(cost*increase)
return increasedCost
def calculateTotalCost(terms,tuition,creditHours,books,roomAndBoard,scholarships):
#This function will calculate the total cost of all your expenses.
totalBookCost = (books*terms)
totalTuitionCost = (tuition*creditHours)*(terms)
totalRoomAndBoard =(roomAndBoard*terms)
totalCost = (totalBookCost+totalTuitionCost+totalRoomAndBoard)-(scholarships)
return totalCost
def main():
#Variable declaration/initialization
years = 0
terms = 0
numberOfSchools = 0
tuitionCost1 = 0
tuitionCost2 = 0
tuitionCost3 = 0
tuitionCost = 0
bookCost = 0
roomAndBoard = 0
scholarships = 0
tuitionIncrease = 0
increasedCost = 0
creditHours = 0
overallCost = 0
#User inputs
years = int(input("Will you be going to school for 2, 4 or 6 years?"))
#If-statements for if user will be going to multiple schools.
if years == 4 or years == 6:
numberOfSchools = int(input("How many schools do you plan on attending during this time?"))
if numberOfSchools == 2:
tuitionCost1 = int(input("How much will you be paying per credit hour at the first school you'll be attending?"))
tuitionCost2 = int(input("How much will you be paying per credit hour at the second school you'll be attending?"))
tuitionCost = (tuitionCost1+tuitionCost2)/(2) #Finds average tuition between schools & assigns it to a variable
elif numberOfSchools == 3:
tuitionCost1 = int(input("How much will you be paying per credit hour at the first school you'll be attending?"))
tuitionCost2 = int(input("How much will you be paying per credit hour at the second school you'll be attending?"))
tuitionCost3 = int(input("How much will you be paying per credit hour at the third school you'll be attending?"))
tuitionCost = (tuitionCost1+tuitionCost2+tuitionCost3)/(3) #Finds average tuition cost between schools & assigns it to a variable
else:
tuitionCost = int(input("Please enter how much you will be paying per credit hour."))
terms = (years*2)
tuitionIncrease = float(input("Please enter the projected tuition increase per year in percentage form (ex. if increase is 7% enter .07)."))
creditHours = int(input("On average, how many credit hours will you be receiving per term?"))
roomAndBoard = int(input("Please enter what your price of room and board will be per term."))
bookCost = int(input("Please enter what your average book cost will be per term."))
scholarships = int(input("Please enter the total amount you will be recieving from grants and scholarships."))
#Calls function that calculates tuition increase
increasedCost = calculateTuitionIncrease(tuitionCost,tuitionIncrease,years)
#Calls function that calculates tuition increase
overallCost = calculateTotalCost(terms,tuitionCost,creditHours,bookCost,roomAndBoard,scholarships)
print ("Your total estimated college cost is", overallCost)
main()
Generally a running total or running average is something you calculate through several iterations of your code. However, I don't see any loops here.
Perhaps you mean that you'd like a sum of the costs of each school tuition.
In that case, you were almost there when you calculated the average. Create a variable that can hold the total cost as you get the values back from your functions.
As you get the results back from your function:
tuitionTotal = (tuitionCost1+tuitionCost2+tuitionCost3) * tuitionIncrease
It seems like you may be able to clean up the logic of your code a little bit as well. I'd suggest asking most of your questions up front, then doing all your calculations afterward.
Something like this might help:
tuitionCost = 0
COST_TEXT = "How much will you be paying per credit hour at school number "
...
for i in range(numberOfSchools):
tuitionCost += int(input(COST_TEXT+str(i+1)+"?"))
...
tuitionAverage = tuitionCost / (i+1)
tuitionTotal = tuitionCost * tuitionIncrease

Categories