Michael Schultz
Michael Schultz

Reputation: 109

Changing while loop to for loop

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)

Upvotes: 0

Views: 71

Answers (2)

GLHF
GLHF

Reputation: 4035

Since you don't change your variables from float type to integer you can't do it, because you need range() function and range() only accepts integer type.

If you set your variables to an integer instead of float, you can use it in a for loop like;

d = 0.6
b  = 6 #bounce
h = 5 #height
t = 0.0
count = 0

t = h

for x in range(b):
    if count == b-1:
        t += h*d
    else:
         h *= d
         t += h*2

    count += 1
print (t)

Upvotes: 0

Marian
Marian

Reputation: 4079

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()

Upvotes: 1

Related Questions