0

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)

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

you can't use a float in range function. It must be an integer. And if you use round() the result will change, check OP's variables first. This answer is far from what OP's want.
@GLHF That's true, thanks for pointing out. I guess I just read that b stands for bounces, which would naturally be int.
Also the result of your answer is not correct either, you should use range(b) instead of (b-1) and if - else statements.
@GLHF Actually the result is correct. Testing it in shell with both my and original code, using values d,b,h,t = 0.6, 20, 2.5, 2.5 gives 9.999634384155991 as the answer.
@hlfrmn but op's codes result is : 19.066879999999998 . How is your result is correct then?
|
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.