NOT operator in python

Asked

Viewed 9,085 times

8

In java we have the operator not, we can use it like this:

if (!metodo()) {
    //código
}

I’m just meeting python now, and I’m having a little trouble:

I have a function that adds names to a list:

def adiciona_perfis():
    quantidade = 0 
    nome = raw_input("Digite seu nome ")
    nomes.append(nome)
    quantidade += 1

And another that checks the quantity variable:

def tem_vaga(quantidade):
    if quantidade == 3:
        return False
    return True

I wanted to call the tem_vaga() function inside the addi_profiles function. But using not, in Java for example, I could do so:

if (!tem_vaga(quantidade)) {
    //Código
}

How can I do this in Python?

  • 1

    Naldson, if any of the answers helped resolve the question, mark it as accepted by clicking the arrow below the chosen answer score!

4 answers

11


It’s up to not

Creates a file .py with the code below and wheel.

def tem_vaga(quantidade):
    if quantidade == 3:
        return False
    return True


def adiciona_perfis():
    quantidade = 3
    if (not tem_vaga(quantidade)):
        print("oi")


if __name__ == "__main__":
    adiciona_perfis()
  • Thank you, Ricardo!

6

Python also has the operator not:

def adiciona_perfis():
    quantidade = 0 
    nome = raw_input("Digite seu nome ")
    nomes.append(nome)
    quantidade += 1

    if not tem_vaga(quantidade):
      # Código...
  • Thank you very much!

  • @Naldson Have just one thing in the role tem_vaga, you compare yourself quantidade is equal to 3, why not check whether quantidade is greater or equal to 3? thus: if quantidade >= 3:.

3

Just to complement, a function where you just make a comparison and return only True or False, can be simplified this way:

def tem_vaga(quantidade):
    return quantidade == 3

In the above case you will use not when calling the function: if not tem_vaga(4): (...)

Or, using the operator not within the function:

def tem_vaga(quantidade):
    return not quantidade == 3

By the way, I believe you should be doing the quantity comparison is less than or equal to 3, ie: quantidade <= 3.

2

In your case, you could use the operator not or else check using the comparison operator == coming if it is False.

if tem_vaga() == False:
      // Não tem vaga

if not tem_vaga():
   // não tem vaga

Browser other questions tagged

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