'Loops with variables that count- trying to find out where this ends
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?
Solution 1:[1]
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
Solution 2:[2]
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))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Desty |
| Solution 2 |
