0

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)

4 Answers4

1
  • 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()
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
1

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)
FunkySayu
  • 7,641
  • 10
  • 38
  • 61
1

The major issues are

  1. You are missing a colon at the end of the if statement
  2. 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.

  1. The division is an integer division, so you won't get a decimal
  2. You need to multiply by 100 to get a percent

Instead specify a float and multiply by 100:

percent = 100 * float(carsAboveLimit)/len(carSpeeds)
  1. 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!

Keyan P
  • 920
  • 12
  • 20
0

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%
h7r
  • 4,944
  • 2
  • 28
  • 31