Python - get while loop to run a certain amount of times - python

I am trying to get a while loop to function dur amount of times, however when I run it it just sits there, I assume calculating, seemingly forever. It is a simple script that shouldn't take very long to run, so I assume I have messed up the while loop.
Here is the code:
#Compound interest calculator
print "Enter amounts without $, years or %"
loan = input("How many dollars is your loan? ")
dur = input("How many years is your loan for? ")
per = input("What percent is the interest on your loan? ")
percent = per / 100
count = 0
#First calculation of amount
first = loan * percent
count = count + 1
#Continued calculation occurs until count is equal to the duration set by the user
while count <= dur:
out = first * percent
#Prints output
output = out + loan
print str(output)

There are a number of problems with your code.
percent will always be 0, because you are using integer division. Try percent = per / 100.0 instead.
As others have noted, you have to increase count to end the loop.
Without changing either first nor percent in the loop, the calculated value of out will be the same in each iteration of the loop. Try first = first * percent instead.
Finally, you do not need the loop at all. Just do this:
output = loan * (1 + per/100.)**dur

You need to increment count in the while loop, otherwise the stop condition (count <= dur) will never happen.
while count <= dur:
# do something
count += 1
If you know in advance the number of times you want to do something you could also use:
for i in xrange(dur): # use range if python3
# do something
Also note that your code has another problem: you're not really calculating compund interest. At every step you recalculate first * percent instead of adding percent to the previous interest. You should do:
# First calculation of amount
out = loan * percent
count = count + 1
while count <= dur:
out *= (1.0 + percent)
count += 1

count never changes within the loop. Do this
while count <= dur:
out = first * percent
count += 1

Related

index element creates not needed input

I want to make a code that would propose a customer one or more of products to add to his shop list if he has total cart less than available budget (for example, he bought products for 120 dollars, and program should ask him if he want to add one or a couple of products (for example for 20 and 30 dollars) in list so budget gets close to 150 dollars limit)
My problem here is that somehow i += 1 creates an unwanted input() process which i cannot explain
I am a newbie in Python so maybe someone can propose the solving of problem or even better version of my code, i'll be greatful for every help!
https://ibb.co/vJwhMw0 link for image here
inp = 'bar'
product_list = ['bar', 'bread', 'milk', 'coconut']
product_price = [10, 24, 30, 25]
indx = product_list.index(inp)
price = product_price[indx]
budget = 150
total = 120
proposal_list = ''
i = 0
while total < budget:
if (product_price[i] + total) <= budget:
total += product_price[i]
proposal_list += product_list[i]
i = i + 1
print (f'You can also add: {proposal_list}')
There is some problems with your code. No unwanted input() is created it's just that your while loop is infinite because i never changes because the condition is never true at some point.
while total < budget:
if i >= len(product_price):
break
elif (product_price[i] + total) <= budget:
total += product_price[i]
proposal_list += product_list[i]
i += 1
You code got inside infinite loop right after this line:
while total < budget:
Once the code inside this line is executed
if (product_price[i] + total) <= budget:
total become equal 130. Condition total < budget is still true but condition
if (product_price[i] + total) <= budget:
is not.
You need to exit the while loop. You can't do it until you update total.

Currency converting issue I am facing now

I was trying to print the output under the 2nd for loop (enter the amount Of $20: ...), but I am getting 0. How to fix this issue? The user gets amount of $20 : 1, and amount of $2.00: 2, when they input 22 from keyboard.
Code:
denomitions={"$20.00":0,
"$10.00":0,
"$5.00":0,
"$2.00":0,
"$1.00":0,
"$0.25":0,
"0.10":0,
"0.5":0}
dividers = [2000,1000,500,200,100,25,10,5]
number = float(input("please enter the amount for change:").strip("$"))
#convert dollar to cents
change = int(number*100)
for i in range(len(denomitions)):
amount = int(change/dividers[i])
change= change- amount * dividers[i]
#print the result out
index= float(dividers[i] / 100.00)
print(index,":",amount)
#print the result out
for k in denomitions:
print("amount of "+str(k),amount)
denomitions={"$20.00":0,
"$10.00":0,
"$5.00":0,
"$2.00":0,
"$1.00":0,
"$0.25":0,
"0.10":0,
"0.5":0}
dividers = [2000,1000,500,200,100,25,10,5]
#add an empty list
amount_list = []
number = float(input("please enter the amount for change:").strip("$"))
#convert dollar to cents
change = int(number*100)
for i in range(len(denomitions)):
amount = int(change/dividers[i])
change= change- amount * dividers[i]
#print the result out
index= float(dividers[i] / 100.00)
print(index,":",amount)
#fill the list with the amount at index i
amount_list.append(amount)
#print the result out
i = 0
for k in denomitions:
#now you can retrieve the amount from the list if you keep the same index
print("amount of "+str(k), str(amount_list[i]))
i += 1
The problem is that in the second for loop, it picks up the amount equal to the last round of the previous for loop. At the end of the first loop amount = 0, therefore you will always get zero when printing amount in the second for loop.

python to calculate percent of cars over the speed limit

I'm trying to calculate the percent of cars that go over the speed limit using this code, except there are errors in the second loop and I'm not sure how to use a loop to increment the amount of cars over the speed limit. My end goal is to print out the percent of cars that go above the speed limit. I'm new to programming so any tips or help would be appreciated, thanks :-)
numCars = int(input("Enter the number of cars: "))
carSpeeds = []
for i in range(numCars):
speed = int(input("Enter the car speed: "))
carSpeeds.append(speed)
carsAboveLimit = 0
speedLimit = int(input("Enter the speed limit: "))
if speed > speedLimit
carsAboveLimit =+ 1
i = i +1
percent = int(carsAboveLimit)/len(carSpeeds)
print("The percentage of cars over the speed limit is", percent)
You're doing an euclidian division. The type of carsAboveLimit is int, and it's the same thing for len(carSpeeds).
If you want to get the percent, just multiply by a floating number (typically 1.) like this :
percent = 1. * int(carsAboveLimit)/len(carSpeeds)
The major issues are
You are missing a colon at the end of the if statement
The if statement is only execute once, you didn't put it in a loop
You could change the if statement to:
for car_speed in carSpeeds:
if car_speed > speedLimit:
carsAboveLimit += 1
What this does is go through each item in the list. Each time the value of car_speed becomes the next item in the list.
The division is an integer division, so you won't get a decimal
You need to multiply by 100 to get a percent
Instead specify a float and multiply by 100:
percent = 100 * float(carsAboveLimit)/len(carSpeeds)
If you don't format the final string you will get many trailing digits
You should try it without formating first to see what I mean, then you could change it to:
print "The percentage of cars over the speed limit is %0.2f%%" % percent
Other things
Note that the usual convention for variable in Python is to use underscores instead of camelCase. That is, try to use: speed_limit instead of speedLimit.
You don't need the i variable. My guess is you were trying to have a counter to keep track of the loop maybe? Either way it isn't necessary.
Good luck!
You are missing a colon after if speed > speedLimit
carsAboveLimit is already an int; you do not need to cast it so again.
=+ is not an operator; += is
For a percentage you need to multiply by 100. ie
pct = 100. * carsAboveLimit / len(carSpeeds)
I would suggest writing it like
def get_int(prompt):
while True: # repeat until we get an integer
try:
return int(input(prompt))
except ValueError:
# that wasn't an integer! Try again.
pass
def get_speeds():
while True:
speed = get_int("Enter a car speed (or 0 to exit): ")
if speed == 0:
break
yield speed
def main():
# get list of car speeds
car_speeds = list(get_speeds())
# get number of speeders
limit = get_int("What's the speed limit? ")
num_speeders = sum(1 for speed in car_speeds if speed > limit)
# show % of speeders
pct = 100. * num_speeders / len(car_speeds)
print("{:0.1f} % of them are speeding!".format(pct))
main()
The problem you are facing is one a) casting of float to be able to have a fractional part, since int/int -> int and int/float -> float.
>>> 1/2
0
>>> 1/float(2)
0.5
and b) of proper formatting of the result to be displayed as a percentage value (assuming you want 2 decimal digits):
>>> '%0.2f%%' % (1/float(2))
'0.50%'
Reference to the 2 points mentioned above you can find here and here.
Your code would be complete as follows (including some minor details as other users have mentioned -- colon at if block, increment operator, etc). Note the for loop that was missing in your code but was mentioned:
numCars = int(input("Enter the number of cars: "))
carSpeeds = []
for i in range(numCars):
speed = int(input("Enter the car speed: "))
carSpeeds.append(speed)
carsAboveLimit = 0
speedLimit = int(input("Enter the speed limit: "))
for speed in carSpeeds:
if speed > speedLimit:
carsAboveLimit += 1
i += i
percent = int(carsAboveLimit)/float(len(carSpeeds))
print("The percentage of cars over the speed limit is %0.2f%%" % percent)
With output:
Enter the number of cars: 3
Enter the car speed: 1
Enter the car speed: 2
Enter the car speed: 3
Enter the speed limit: 2
The percentage of cars over the speed limit is 0.33%

Beginner Python exercise

I'm having trouble solving problem 2 from this page
Here
Here's my code:
#Problem set 1 b
out_bal = float(raw_input("Enter the outstanding balance on your credit card: "))
ann_interest = float(raw_input("Enter the annual interest rate as a decimal: "))
min_pmnt = 10
months = 1
prev_bal = out_bal
month_interest = ann_interest / 12.0
updated_bal = prev_bal * (1 + month_interest) - min_pmnt
while out_bal > 0:
for i in range(1,13):
out_bal = updated_bal
prev_bal = out_bal
months += 1
if out_bal <= 0:
break
else:
min_pmnt = min_pmnt + 10
months = 0
print out_bal
print "RESULT"
print "Monthly payment to pay off debt in 1 year: $", min_pmnt
print "Number of months needed: ", months
print "Balance: ", round(out_bal, 2)
I want to take 1200 and .18 for the first two inputs, respectively. However when I do this the program gets caught in my while loop and keeps printing 1208.00.
When I read the code to myself it seems like it should be working. But I think I'm not using the prev_bal variable correctly.
Also, it's performing the math the way I expect it to the first time it goes through the loop but then it seems like it's not adding 10 to min_pmnt and going through the loop again. It seems like it's just using 10 over and over.
How can I write this so it does actually add 10 and perform the loop again?
Thanks!
Your problem is that updated_bal isn't changing, yet you are setting out_bal to it each time you iterate, and then conditioning the loop on out_bal becoming reduced in value.
It looks to me like you are thinking that updated_bal changes on each loop iteration, based on its component parts. In order for that to work, you would need to instead use a function that calculates an updated balance each time around.

Python average input not working

I am trying to get average times of the speed skaters with Python and my code will not work. I have searched all over trying to find an answer and I am completely stumped.
print("Enter the skater times in seconds. Input -1 to finish and calculate.")
count = 0
sum = 0.0
number = 1
while number != -1:
number = input("Enter skater time in seconds: ")
if number != 0:
count = count + 1
sum = sum + number
print ("The number of skaters was: ", count)
print ("The average skater time was:", sum / count)
The if clause must be:
if number > 0:
Otherwise you are considering the last one, whose value is -1
Edit
I think it has nothing to do with integer division. It is only the if clause.
You can add from __future__ import division and it will make all divisions be floats.

Categories