Michael Schultz - 2 years ago 149
Python Question

# Ball Traveling Distance

I was wondering if this same code could be made with a

`for loop`
instead of a
`while`

``````d = 0.6
b  = 0.0
h = 0.0
t = 0.0
count = 0

h = float(input("enter height: "))
b = float(input("enter a number of bounces: "))

t = h

while count < b:
if count == b - 1:
t += h * d
#print(t)
else:
h = h * d
t += h * 2
#print(t)
count += 1
#print (t)
print(t)
``````

Answer Source

As GLHF reminded me, the `b` should be an int in order for the code below to work.
I see no reason for a variable `b`, representing a number of bounces to be a float. Moreover, in your original code you have a comparison between `count` (an int) and `b` (float from user input). In a case, where b is not a float with a `0` for the decimal part, the check would fail, so you might want to change the line to `b = int(input('Enter the number of bounces))`

``````for count in range(b-1): # generates a sequence from 0 to b-2
h *= d
t += h * 2
#print(t)
t += h * d
print(t)
``````

range()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download