简体   繁体   中英

how to make loops from smallest to largest number?

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.

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)):

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 = ' ')

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM