Home > Mobile >  Loops with variables that count- trying to find out where this ends
Loops with variables that count- trying to find out where this ends

Time:02-25

I'm supposed to type the programs output. Input is 6, 3

target = int(input())
n = int(input())
while n <= target:
    print(n * 2)
    n  = 1 

My output - 6

My reasoning- 3 < 6 so the code will run through. 3 * 2 = 6 so 6 gets printed out. Then we do 6 = 1 which would be 7. 7 is not <= 6 so code shouldn't run through again.

The expected output: 
    6
    8
    10
    12

n = 1 is shorthand for n = n 1. The loop ends when n is greater than target.

Can someone please tell me where I am going wrong?

CodePudding user response:

print(n * 2) does not affect the value of n. Since we did not put n * 2 in the value of n, the value of n changes only by n = 1.

target = int(input())
n = int(input())
while n <= target:
    n = n * 2
    print(n)
    n  = 1

CodePudding user response:

This is the main difference between print and return statement.
Using return changes the flow of the program. Using print does not

def func(target,n):
    while n <= target:
        return (n * 2)
        n  = 1 
target = int(input())
n = int(input())
print(func(target,n))

See here

  • Related