python to calculate percent of cars over the speed limit - python

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%

Related

How do you Multiply numbers in a loop in Python from a list of user inputs

I need to create something that can multiply values no matter how many values there are. My idea is to use a list and then get the sum of the list with the sum function or get the first value of the list and set it as the total and then multiply the rest of the list by that total. Does anyone have a way to do it?
Here was my original idea:
total = 0
while True:
number = float(input("Enter a number and I’ll keep multiplying until you enter the number 1: "))
if number == 1:
break
else:
total *= number
print(f"The total is: {total}")
however as you may have guessed it just automatically multiplies it to 0 which equals zero. I would also like the code to work for subtraction and division (Already got Addition working)
thanks!
Thanks to the comments I worked out that the way to do it is by changing the beginning total to a 1 when fixed it is this:
total = 1
while True:
number = float(input("Enter a number and I’ll keep multiplying until you enter the number 1: "))
if number == 1:
break
else:
total *= number
print(f"The total is: {total}")
Since you are multiplying, you must start with 1 cause anything multiplied by 0 is 0. And idk why you need sum()
total = 1
while True:
number = float(input("Enter a number and I’ll keep multiplying until you enter the number 1: "))
if number == 1:
print(f"The total is: {total}")
break
else:
total *= number

Why does my python code produce an infinite loop if the number is larger than or equal to 772000000000000?

I have a code that is supposed to produce the lowest monthly payment you need to make to payoff a balance within a year. It works perfectly for all numbers until (so far as I've tested) 772000000000000.
Here is the code (numbers I've tested are below with their results):
import time
balance = float(input("balance: "))
annualInterestRate = float(input("AIR: "))
# formulas for lower and higher binding for bisectional search
monthlyInterestRate = annualInterestRate / 12
lower = balance / 12
higher = (balance * (1 + monthlyInterestRate) ** 12) / 12
while True:
guess = ((higher - lower) / 2 + lower)
print('higher: %s' % higher)
print('lower: %s' % lower)
remaining = balance
for i in range(12):
unpaid = remaining - guess
remaining = unpaid + monthlyInterestRate*unpaid
if higher - lower <= .01 and remaining < 0:
result = lower
print("Lowest Payment: %s" % result)
break
elif higher - lower <= .01 and remaining >= 0:
result = higher
print("Lowest Payment: %s" % result)
break
elif remaining < -0.01:
higher = guess
print("remaining: %s" % remaining)
print(guess)
print('too high')
time.sleep(.5)
elif remaining > 0:
lower = guess
print("remaining: %s" % remaining)
print(guess)
print('too low')
time.sleep(.5)
As I said, this gives the correct result for every number I tested but then I tested 999999999999999 and I got an infinite loop, I narrowed down where the issues start happening by testing the following values all using .2 as the AIR, using different AIR can produce different but similar results depending on the number, but the following should give you a good idea of what's happening:
662000000000000 works
771999999999999 works
772000000000000 repeats higher and lower over and over again after some time
772100000000000 works
772200000000000 repeats higher and lower over and over again after some time
772300000000000 infinite loop
772400000000000 infinite loop
772500000000000 infinite loop
882100000000000 infinite loop
999999999999999 infinite loop
Feel free to try them yourself, I'm completely dumbfounded why this is happening?
If you use floats you have to consider that these cannot represent all possible decimal values. If the values get big enough the difference between two representable floating point values might just exceed your threshold. That leads to a situation where the bisection cannot progress because there is just no "middle" float between the values. For example with:
balance = float("772300000000000")
annualInterestRate = float("0.2")
It ends up in an infinite loop with:
higher: 70368815315719.6
lower: 70368815315719.58
So, let's examine this a bit:
>>> a = 70368815315719.6
>>> b = 70368815315719.58
>>> import numpy as np
>>> np.nextafter(a, 0) == np.float64(b)
True
>>> np.nextafter(b, np.inf) == np.float64(a)
True
So there's no float between a and b but:
>>> b - a
-0.015625
So this is bigger than your threshold. So nothing can change between loops which results in the infinite loop.
However, you can easily fix this by using an arbitary precision Fraction:
from fractions import Fraction
balance = Fraction("772300000000000")
annualInterestRate = Fraction("0.2")
... # rest of your code
All operations in your code preserve the Fraction (if you had used math functions or ** it could be different) and at least on my computer it eventually finishes with:
higher: 161683724083791631395206486083981108997/2297661589986627614146560
lower: 41391033365450653948925712865241263190149/588201367036576669221519360
Lowest Payment: 161683724083791631395206486083981108997/2297661589986627614146560
Note the / in the output which comes from the Fraction.

"'int' object is not iterable" when asking for a Number input (beginner)

I am planning to create a program which basically lists the Fibbonacci sequnce up to 10,000
My problem is that in a sample script that I wrote I keep getting the error 'int' object is not iterable
My aim is that you enter a number to start the function's loop.
If anyone would help out that would be great
P.S I am a coding noob so if you do answer please do so as if you are talking to a five year old.
Here is my code:
def exp(numbers):
total = 0
for n in numbers:
if n < 10000:
total = total + 1
return total
x = int(input("Enter a number: "), 10)
exp(x)
print(exp)
numbers is an int. When you enter the number 10, for example, the following happens in exp():
for n in 10:
...
for loops through each element in a sequence, but 10 is not a sequence.
range generates a sequence of numbers, so you should use range(numbers) in the for loop, like the following:
for n in range(numbers):
...
This will iterate over the numbers from 0 to number.
As already mentioned in comments, you need to define a range -- at least this is the way Python do this:
def exp(numbers):
total = 0
for n in range(0, numbers):
if n < 10000:
total = total + 1
return total
You can adjust behavior of range a little e.g. interval is using. But this is another topic.
Your code is correct you just need to change :
for n in numbers:
should be
for n in range(0, numbers)
Since you can iterate over a sequence not an int value.
Good going, Only some small corrections and you will be good to go.
def exp(numbers):
total = 0
for n in xrange(numbers):
if n < 10000:
total += 1
return total
x = int(input("Enter a number: "))
print exp(x)

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.

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

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

Categories