Nibaga Nibaga - 1 month ago 7
Python Question

How to do this program without a counter?

lista = []
for i in range(5):
i = int(input("Digite um valor para o vetor: "))
lista = lista + [i]
x = int(input("Digite um valor para ver sua posição: "))
counter = 0
for j in range(5):
if lista[j] == x:
counter =+ 1
print(j)
if counter == 0:
print(x-1)


In the program you put any 5 numbers in the list, then you look for the position of the number you inputted in the list, if the number inputted is not in the list it will print x-1

For example List = [1, 2, 3, 4, 5]

x = 5 then it will print 5

x = 7 it will print 6

How do I make it print x-1 without counter? I tried using

else:
print(x-1)


but then it will print x-1 5 times, I only want to print it once

Answer

You don't need a counter at all, as you're only using it to check that there were no matches. You can use the for..else structure to check whether the loop completed without exiting from a break.

for j in range(5):
    if lista[j] == x:
        print(j)
        break
else:
    print(x-1)

If you want to print each index that matches your search query, I would move to a different approach:

>>> x = 1
>>> print(*(i for i,v in enumerate(map(int, input('Enter values separated by space:\n').split())) if v==x))
Enter values separated by space:
1 1 1 1 1
0 1 2 3 4
>>> print(*(i for i,v in enumerate(map(int, input('Enter values separated by space:\n').split())) if v==x))
Enter values separated by space:
2 2 1 10 1
2 4
>>> print(*(i for i,v in enumerate(map(int, input('Enter values separated by space:\n').split())) if v==x))
Enter values separated by space:
2 2 1 10
2