a = int(input("first number: "))
b = int(input("second number: "))
for x in range (a,b):
print(x, end = ' ')
I am making a program that would display a number from smallest to largest.
For example: the first number is 10 then the second number is 1.
My expected result is: 1,2,3,4,5,6,7,8,9.
The program that I did is not working if a is lower than b, but is working if the a is higher than b.
CodePudding user response:
If you want it to always go from min to max regardless of which one is min and which is max you could do something like this:
for x in range(min(a, b), max(a, b)):
CodePudding user response:
To count backwards, range has a step
parameter: when set to -1, it will count backwards.
a = int(input("first number: "))
b = int(input("second number: "))
step = -1 if a > b else 1
for x in range (a, b, step):
print(x, end = ' ')
CodePudding user response:
If you want to count backwards then you can specify an additional stepsize of -1 as an argument to the range function as follows:
In [1]: list(range(1,10))
Out[1]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
In [2]: list(range(10,1))
Out[2]: []
In [3]: list(range(10,1,-1))
Out[3]: [10, 9, 8, 7, 6, 5, 4, 3, 2]