Using range with for/in - python

#This program will calculate distance traveled
#ask for miles traveled
speed = int(input("Enter speed in mph: "))
#ask for hours traveled
hour = int(input("Enter hours traveled: "))
increment = 1
def main ():
print ('Hours\t Distance')
print ('----------------')
for hour in range(speed, hour, increment):
distance = speed * hour
print(hour, '\t' , distance)
main()
I know I'm looking right at the problem and just not seeing it. I can get the column headers and the separator to print, but the for statement will not run. Any suggestions?
Thank you in advance.

Your range needs to start at 0 (or maybe increment if you don't want 0), not speed
for hour in range(0, hour, increment):
distance = speed * hour
print(hour, '\t' , distance)
If you want to skip the 0, you probably need this
for hour in range(increment, hour+increment, increment):
distance = speed * hour
print(hour, '\t' , distance)

Related

Python function for calculating compound interest percentage

I'm new to programming, so any experienced programmer will probably be able to answer this question easily.
I am trying to write a Python function which will tell me what percentage compound interest is necessary to end up with a specific sum. For example, if I deposited $100, and after 17 years of compound interest I have $155, the function will tell me what percentage interest was I receiving. I wrote the following function, with 'start' being the original sum deposited, 'finish' the sum I ended up with, and 'years' the number of years it accrued interest. I designed it to give a result in decimal points, for example for 1.5% it will show 0.015.
Here's the code I wrote:
def calculate(start, finish, years):
num = start
percentage = 0
while num < finish:
percentage += 0.000001
for year in range(years):
num += num * percentage
return percentage
print(calculate(12000, 55000, 100))
It's giving an output of 0.00017499999999999962 (i.e. 0.017499999999999962%), which is totally wrong.
I can't understand where I've gone wrong.
You need to reset the num=start after every time you guess a percentage.
def calculate(start, finish, years):
num = start
percentage = 0
while num < finish:
num = start
percentage += 0.000001
for year in range(years):
num += num * percentage
return percentage
print(calculate(12000, 55000, 100))
However, you'd probably be better off solving this problem by simply re-arranging the compound interest formula:
A=P*(1+r/n)^(nt)
(where A = Final balance, P = Initial balance, r = Interest rate, n = number of times interest applied per time period, and t = number of time periods elapsed.)
The rearrangement gives:
r=n((A/P)^(1/nt)-1)
and putting this into python gives us:
def calculate(start, finish, years):
num = ((finish / start)**(1/years))-1
return num
print(calculate(12000.0, 55000.0, 100.0))
which gives the expected results.
You can do a one-liner if you understand how compound interest works
def calculate(start, finish, years):
return (finish/start)**(1/years) - 1
print(calculate(12000, 55000, 100) * 100, '%')

How to calculate number of zeroes from 1 to a user given number and calculate time it took?

So, basically, what I need is to calculate the number of zeroes from 1 to a user given number. I need to ask them for a number, use a for-loop within a function to calculate the number of zeroes within that amount of numbers, print that back to them and then using the time() function, print how long it took to calculate. The desired output should look like this:
What number do you want to count zeros to? 10000
The number of zeros written from 1 to 10000 is 2893.
This took 0.0105922222137 seconds.
-This is what I have so far, it's very disoriented because I'm trying to tackle different pieces at once, which I realize is probably not the best way to approach it
from time import time
start_time =time()
stop_time = time()
elapsed = stop_time - start_time
def Count():
i = 0'
count = 0'
for i in range(1,):
if i % 10 is 0
i = i + 1
x =
Num1 = input("What number do you want to count zeros to?: ")
print "The number of zeros written from 1 to {} is {}".format(Num1, x)
If anyone could be of assistance that would be very much appreciated.
The main trick with this problem is to start with counting the number of 0's, then move on to the timing. Think of the program structure as:
Begin Timer
Count 0's
End Timer
Display output
So to count the 0's, we might use loop over the range, which is just a list of numbers from the start to the end, so
range(0, 10)
is really just
[0,1,2,3,4,5,6,7,8,9]
Therefore, we can loop through from the start(in this case 0), to the end(in this case 10000), which might look something like:
end = 10000
count = 0
for number in range(1, end + 1):
count += str(number).count("0")
Then, we can add a timer using the time library, and print the result, so our code looks like this:
import time
start_time = time.time()
end = 10000
count = 0
for number in range(1, end + 1):
count += str(number).count("0")
print("The number of zeros written from 1 to " + str(end) + " is " + str(count) + ".")
print("This took %s seconds." % (time.time() - start_time))

Loop Table using distance = speed * time

The distance a vehicle travels can be calculated as follows:
distance = speed * time
Write a program that asks the user for the speed of a vehicle (in miles per hour) and how many hours it has traveled. The program should then use a loop to display the distance the vehicle has traveled for each hour of that time period. Here is an example of the output:
What is the speed of the vehicle in mph? 40
How many hours has it traveled? 3
Hour Distance Traveled
1 : 40
2 : 80
3 : 120
I've gotten everything done so far but can't manage to get the table to come out properly, as shown in the example table at the first hour (1) it should start at 40 but instead it starts at 120. Can someone help me fix the code? forgot to mention it should work for any value the user enters such as if someone was going 50 mph in 5 hours
g = 'y'
while g == 'Y' or g == 'y':
speed = int(input('Enter mph: '))
time = int(input('Enter hours: '))
if time <= 0 or speed <= 0:
print('Invalid Hours and mph must be greater than 0')
else:
for t in range(time):
distance = speed * time
print(t + 1,':', distance)
time = time * 2
g = 'n'
print('End')
Just change 2 things in your program. First, there's no need to double the time inside for loop, Second use variable t instead of time to calculate distance.
g = 'y'
while g == 'Y' or g == 'y':
speed = int(input('Enter mph: '))
time = int(input('Enter hours: '))
if time <= 0 or speed <= 0:
print('Invalid Hours and mph must be greater than 0')
else:
for t in range(time):
distance = speed * (t+1) // Use t+1 instead of time
print(t + 1,':', distance)
# time = time * 2 // No need to double the time
g = 'n'
print('End')
Input:
40
3
Output:
(1, ':', 40)
(2, ':', 80)
(3, ':', 120)
End
You need to remove the commas from the print line, and print out the numbers in string format and concat it to the string colon like:
print(str(t + 1) + ':' + str(distance))
You also need to increment the time by one not multiply by 2
time = time + 1
Your output distance also can be fixed by calculating it based on t instead of time
distance = speed * (t+1)

I am creating a running time calculator and am having trouble using functions

Here is my current code:
def get_input():
pace = str(input("Enter pace [mm:ss]: "))
distance = float(input("Enter distance [miles]: "))
mm, ss = int(pace.split(":")[0]), int(pace.split(":")[1])
return(pace, distance, mm, ss)
def calculate_time(pace, distance, mm, ss):
print(pace)
print(mm)
print(ss)
new_sec = mm * 60
full_sec = ss + new_sec
print(full_sec)
print(distance)
total_time_sec = full_sec * distance
print(total_time_sec)
seconds_per_mile = total_time_sec / 60
hours = int(seconds_per_mile // 60)
print(seconds_per_mile)
print(hours)
minutes = int((total_time_sec - (hours * 3600))//60)
print(minutes)
seconds = int(total_time_sec - ((hours * 3600) + (minutes * 60)))
print(seconds)
print(pace, full_sec, distance)
return(seconds, minutes, hours)
def display_time(pace, distance, mm, ss, seconds, minutes, hours):
if seconds < 10:
print(hours,":",minutes,":0",seconds, sep="")
else:
print(hours,":",minutes,":",seconds, sep="")
return()
def main():
pace, distance, mm, ss = get_input()
new_sec, full_sec, total_time_sec, seconds_per_mile, hours, minutes, seconds = calculate_time(pace, distance, mm, ss)
display_time(pace, distance, mm, ss, seconds, minutes, hours)
main()
I'm not terribly good at using functions. I don't believe I have a full understanding of returning stuff any whatnot, either.
This is the error I'm getting:
Traceback (most recent call last):
File "C:/Python33/homework 3 test.py", line 36, in <module>
main()
File "C:/Python33/homework 3 test.py", line 34, in main
new_sec, full_sec, total_time_sec, seconds_per_mile, hours, minutes, seconds = calculate_time(pace, distance, mm, ss)
ValueError: need more than 3 values to unpack
The point of the function is to get the user to input their pace and distance and output the time needed to run the distance.
For example:
Enter pace [mm:ss]: 8:15
Enter distance [miles]: 26.2
3:36:09
If anyone could explain what I'm doing wrong, I would greatly appreciate it. I don't necessarily want to know how to do it to the tee, but I am having a lot of trouble and need a bit of a boost.
Your code is a bit hard to read (check out PEP-8 (Style Guide for Python code)), but one obvious problem with your function calculate_time() is that it does
return(seconds, minutes, hours) # return a three-element tuple
but that main() tries to unpack that into six variables:
new_sec, full_sec, total_time_sec, seconds_per_mile, hours, minutes, seconds = calculate_time(pace, distance, mm, ss)
Some comments:
pace = str(input("Enter pace [mm:ss]: "))
mm, ss = int(pace.split(":")[0]), int(pace.split(":")[1])
is overly complex. input() already returns strings, and there's a nifty Python feature called a list comprehension that you could use here:
pace = input("Enter pace [mm:ss]: ")
mm, ss = [int(item) for item in pace.split(":")]

Loop not iterating

I'm running into a dilemma with a for i in range(x) loop not iterating. The purpose of my program is to simulate foxes and rabbits interacting with one another on an island and printing out the populations of each respective animal after each day. I know the equations are correct, the problem I am having is my loop will only run once for a large range.
My code:
def run_simulation():
print()
RABBIT_BIRTH_RATE = 0.01
FOX_BIRTH_RATE = 0.005
INTERACT = 0.00001
SUCCESS = 0.01
x = 0
y = 1
FOXES = eval(input("Enter the initial number of foxes: "))
print()
RABBITS = eval(input("Enter the initial number of rabbit: "))
print()
DAYS = eval(input("Enter the number of days to run the simulation: "))
print()
print("Day\t","Rabbits\t","Foxes\t")
print(0,"\t",RABBITS,"\t","\t",FOXES,"\t")
for i in range(DAYS):
RABBITS_START = round((RABBIT_BIRTH_RATE * RABBITS) - (INTERACT * RABBITS * FOXES))
FOXES_START = round((INTERACT * SUCCESS * RABBITS * FOXES) - (FOX_BIRTH_RATE * FOXES))
y = y + x
print (y,"\t",(RABBITS_START+RABBITS),"\t","\t",(FOXES_START+FOXES),"\t")
run_simulation()
When this is run with an example of 500 Foxes, 10000 Rabbits, and 1200 days, my output will look like
Day Rabbits Foxes
0 10000 500
1 10050 498
With the second output line repeating the remaining 1199 times.
Any help would be greatly appreciated I cannot figure out what I am doing wrong.
You set RABBITS and RABBIT_BIRTH_RATE at the beginning. Then, on every loop iteration, you set RABBITS_START to some formula involving these two numbers. You never change the value of RABBITS or RABBIT_BIRTH_RATE or FOXES or anything, so every time you run through the loop, you're just calculating the same thing again with the same numbers. You need to update the values of your variables on each iteration --- that is, set a new value for RABBITS, FOXES, etc.
The biggest issue for me is what you named your "change in rabbits/foxes". RABBITS_START sounds like an initial count for RABBITS, but it's not. This is why I renamed it to RABBITS_DELTA, because really it's calculating the CHANGE in rabbits for each day.
I think I got it. At the very least this behaves more like a simulation now:
def run_simulation():
RABBIT_BIRTH_RATE = 0.01
FOX_BIRTH_RATE = 0.005
INTERACT = 0.00001
SUCCESS = 0.01
x = 0
y = 1
FOXES = eval(str(input("Enter the initial number of foxes: ")))
RABBITS = eval(str(input("Enter the initial number of rabbits: ")))
DAYS = eval(str(input("Enter the number of days to run the simulation: ")))
print("Day\t","Rabbits\t","Foxes\t")
print(0,"\t",RABBITS,"\t","\t",FOXES,"\t")
count = 0
while count < DAYS:
RABBITS_DELTA = round((RABBIT_BIRTH_RATE * RABBITS) \
- (INTERACT * RABBITS * FOXES))
FOXES_DELTA = round((INTERACT * SUCCESS * RABBITS * FOXES) \
- (FOX_BIRTH_RATE * FOXES))
y = y + x
RABBITS += RABBITS_DELTA
FOXES += FOXES_DELTA
print (y,"\t",(RABBITS),"\t","\t",(FOXES),"\t")
count += 1
run_simulation()
I'm going to take a wild stab at trying to interpret what you mean:
for i in range(1, DAYS + 1):
rabbit_delta = ... # RABBITS_START
fox_delta = ... # FOXES_START
RABBITS += rabbit_delta
FOXES += fox_delta
print(i, "\t", RABBITS, "\t\t", FOXES, "\t")
edited based on others' answers. (Wild stab is less wild.)
See BrenBarn's answer for an explanation in prose.

Categories

Resources