Why does entering a value in a list become None?

Asked

Viewed 37 times

2

valores = []

valor1 = valores.append(int(input('Valor 1: ')))
valor2 = valores.append(int(input('Valor 2: ')))

if valor1 in valores > 0:
  print(valor1, 'é positivo')
else:
  print(valor1, 'é negativo')

if valor2 in valores > 0:
  print(valor2, 'é positivo')
else:
  print(valor2, 'é negativo')

When executing the code, we insert the two values and in the end both are negative because they are "None":

Valor 1: 10
Valor 2: 20
None é negativo
None é negativo

I wanted to understand why values are returning None, what is wrong.

  • You’re making valor1 = valores.append(...); the return of function append is None.

  • About your condition valor1 in valores > 0, read the discussion: https://answall.com/q/241769/5878

2 answers

3


This is because append returns None.

If you want to read the values and save them in the list, do these steps separately:

valores = []

# primeiro lê os valores
valor1 = int(input('Valor 1: '))
valor2 = int(input('Valor 2: '))

# depois insere na lista
valores.append(valor1)
valores.append(valor2)

# ou, se quiser, crie a lista diretamente com os valores
valores = [ valor1, valor2 ]

Another point is that it makes no sense:

if valor2 in valores > 0:

Since the value has already been entered in the list, you would not need to check if it is in the list. And anyway, that’s not how you verify that the value is greater than zero (actually, this expression does not do what you are imagining). It would be enough to just do:

if valor1 > 0:
  print(valor1, 'é positivo')
else:
  print(valor1, 'é negativo')

if valor2 > 0:
  print(valor2, 'é positivo')
else:
  print(valor2, 'é negativo')
  • thanks friend!! really was lack of attention my, thank you very much

2

Hi, your assignment in:

valor1 = valores.append(int(input('Valor 1: ')))
valor2 = valores.append(int(input('Valor 2: ')))

You’re wrong about the variables valor1 and valor2 there is nothing, so Python treats as None. Your logic on parole (if/else) also looks strange.

Version "corrected"

valor1 = int(input('Valor 1: '))
valor2 = int(input('Valor 2: '))

if valor1 > 0:
  print(valor1, 'é positivo')
else:
  print(valor1, 'é negativo')

if valor2 > 0:
  print(valor2, 'é positivo')
else:
  print(valor2, 'é negativo')

If you really need to use lists:

arr = []
arr.append(int(input('Valor 1: ')))
arr.append(int(input('Valor 2: ')))

for i in arr:
   if i > 0:  # como pode ver, não há tratamento para valor == 0 
      print(f'{i} é positivo.')
   else:
      print(f'{i} é negativo.')
  • thanks friend!! lack of attention my, thank you very much

Browser other questions tagged

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