Python, ascending order of numbers

Asked

Viewed 15,660 times

1

My goal in the code is to print an increasing order of integers. For example: User type 2 numbers and I want to print the ascending order.

Ex.:

n1 = int(input('Digite um número')) #O usuário digitou 9
n2 = int(input('Digite outro')) #O usuário digitou 2

Lsta=[n1,n2]

#O que deve ser impresso é [2,9] nessa ordem(o menor primeiro e depois o maior)

What would be the best way to do that?

Note: I am beginner in python

  • But you want to create a list of all the numbers from 2 to 9 or just a mathematical representation of the range, be it this [2,9] ?

  • type enter 4, 5 and 3 and print them in ascending order

  • You guys, you really helped me out^^

1 answer

1


Hello! I suggest using the Sorted function:

n1 = int(input('Digite um número ')) #O usuário digitou 9
n2 = int(input('Digite outro ')) #O usuário digitou 2

Lsta=[n1,n2]
print(sorted(Lsta))

Upshot:

inserir a descrição da imagem aqui

Editing:

According to the documentation and the tutorial, the function sorted by default sorts the list from smallest to largest (and not random) and returns the ordered value. However, this function unchanges the original list.

If it is in your interest that the list be changed, then the option to be used is the method sort(), that modifies the list and returns None. Does that mean that print(Lsta.sort()) will print None and not the modified list.

Here is an example:

n1 = int(input('Digite um número '))
n2 = int(input('Digite outro '))
n3 = int(input('Digite outro ')) 
n4 = int(input('Digite outro '))
n5 = int(input('Digite outro '))

Lsta=[n1,n2,n3,n4,n5]
print('Essa é a lista original:',Lsta)
print('Essa é a lista com sorted():',sorted(Lsta))
print('Essa é a lista após o sorted():',Lsta)
print('Resultado usando Lsta.sort():',Lsta.sort())
print('Essa é a lista após o .sort():',Lsta)

Upshot:

inserir a descrição da imagem aqui

I hope I’ve helped! :)

  • - Thank you. -

Browser other questions tagged

You are not signed in. Login or sign up in order to post.