By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,946 Members | 744 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,946 IT Pros & Developers. It's quick & easy.

Find the percent of cars over the speed limit?

P: 6
In this program I am attempting to compute the percentage of cars that exceed the speed limit, I figured out how to create the list of cars, and I made it so the user picks the speed limit, but now I'm unsure how to print out the calculated percentage of cars over the speed limit. I know the equation should probably look something like the number of cars over the speed limit divided by numCars. I'm very new to programming so any form of help would be appreciated! :-)

Expand|Select|Wrap|Line Numbers
  1. numCars = int(input("Enter the number of cars: "))
  2.  
  3. carSpeeds = []
  4.  
  5. for i in range(numCars):
  6.     speed = int(input("Enter the car speed: "))
  7.     carSpeeds.append(speed)
  8.  
  9. carsAboveLimit = 0
  10.  
  11. speedLimit = int(input("Enter the speed limit: "))
  12.  
  13. for i in range(carSpeeds):
  14.     if speed > speedLimit
  15.     carsAboveLimit =+ 1
  16.     i = i +1
  17.  
  18. percent = int(carsAboveLimit)/len(carSpeeds)
  19.  
  20. print("The percentage of cars over the speed limit is", percent)
  21.  
  22.  
  23.  
  24.  
Feb 9 '15 #1

✓ answered by bvdet

You are almost there. for i in range(carSpeeds): won't work because carSpeeds is a list. The easiest way to create the list carsAboveLimit is to use a list comprehension.
Expand|Select|Wrap|Line Numbers
  1. carsAboveLimit = [speed for speed in carSpeeds if speed > speedLimit]

Share this Question
Share on Google+
1 Reply


bvdet
Expert Mod 2.5K+
P: 2,851
You are almost there. for i in range(carSpeeds): won't work because carSpeeds is a list. The easiest way to create the list carsAboveLimit is to use a list comprehension.
Expand|Select|Wrap|Line Numbers
  1. carsAboveLimit = [speed for speed in carSpeeds if speed > speedLimit]
Feb 9 '15 #2

Post your reply

Sign in to post your reply or Sign up for a free account.