I want to code a function and get expected results like this (when i input number = 10):
10
9
8
7
6
5
4
3
2
1
And when i input number = -10 :
-10
-9
-8
-7
-6
-5
-4
-3
-2
-1
This is my code. Only works when number = 10. No result when im trying to input a = -10:
def function_while(number):
i=0
while i<number:
if True:
print(number-i)
else:
print(number 1)
i =1
function_while(number)
Is there any solution?
CodePudding user response:
I would suggest a for-loop over a while loop since you know the number of iterations needed:
def f(n):
sign = -1 if n < 0 else 1
for i in reversed(range(1, abs(n) 1)):
print(i*sign)
But, if you're set on the while loop:
def function_while(x):
sign = -1 if x < 0 else 1
number = abs(x)
i=0
while i<number:
print((number-i)*sign)
i =1
The trick is to use a variable, sign which is -1 if the input is negative, otherwise 1.
CodePudding user response:
Be pythonic, use a simple range
:
def f(number):
for i in range(number, 0, -1 if number>0 else 1):
print(i)
Example:
f(5)
5
4
3
2
1
f(-5)
-5
-4
-3
-2
-1