List input

Asked

Viewed 5,930 times

2

I have to receive input (10 integers) from the user and put them in a list but not allow repeated numbers to be entered. I tried but the program sees that the numbers are repeated does not insert any number

v = [ ]

for i in range(0,10):
x = int(input("Escreva um numero: "))
for i in v:
    if x == i:
        print("Nao pode escrever esse numero.")
    else:
        v.append(x)
print(v)

2 answers

2


The range(0,10) who has will ask 10 numbers but if one puts a repeated number, one will end up not asking for enough numbers because the repeated numbers have been discarded.

It is better to transform the for in a while that asks for numbers until it has the amount of elements required:

v = []
while len(v) < 10:
    x = int(input("Escreva um numero: "))
    if x in v:
        print("Nao pode escrever esse numero.")
    else:
        v.append(x)

print(v)

Example in Ideone

1

What we must do in this matter is proibir the insertion of any element, the value of which corresponds to the value of any other element which já exista na lista. For this I implemented the following code below.

To use this code we must execute it, then enter the amount of values we want to enter in the list. Then insert each of the values. Note that if a value is entered that already exists within the list the application will inform that that value already exists and request another. Note that, the application will only proceed with its execution if you insert different values to those that already exist within the list.

n = int(input('Digite a quantidade de valores: '))
valores = list()
for c in range(1, n + 1):
    x = int(input(f'Digite o {c}ª valor: '))
    while x in valores:
        print('\033[31mO valor já existe! Digite outro valor!\033[m')
        x = int(input(f'Digite o {c}ª valor: '))
    valores.append(x)

print()
print(f'\033[32mA lista gerada foi: {valores}\033[m')

See here the functioning of the algorithm.

If you think it best to put the list in ascending order you can use the following code...

n = int(input('Digite a quantidade de valores: '))
valores = list()
for c in range(1, n + 1):
    x = int(input(f'Digite o {c}ª valor: '))
    while x in valores:
        print('\033[31mO valor já existe! Digite outro valor!\033[m')
        x = int(input(f'Digite o {c}ª valor: '))
    valores.append(x)

valores.sort()
print()
print(f'\033[32mA lista gerada foi: {valores}\033[m')

See here the functioning of the algorithm.

Browser other questions tagged

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