Steve8what
Steve8what

Reputation: 21

Different output than expected

I just started programming and right now I'm stuck with a problem. I'm wondering how if functions really work.

a = [ 20.0, 8.0, 2.5 ]
b = 4
if b > len(a): 
    r = 2*b
r = b

I expected the output of 8, but the actual output is 4. How come? Because 4 > 3 and that should execute the if statement right?

Upvotes: 0

Views: 154

Answers (1)

Sheldore
Sheldore

Reputation: 39042

The problem is that you do not have an else statement which should be executed if your condition if b > len(a) is not True. So in your code, the if statement is first executed, the value of r becomes twice of b (r becomes 8) but then you come out of the if statement and again reassign b to r which is why your r becomes 4 again. I hope the concept is clear now.

The correct way would be

a = [ 20.0, 8.0, 2.5 ]
b = 4

if b > len(a):
     r = 2*b
else:
     r = b

Upvotes: 1

Related Questions