How do I use the if and Else functions?

Asked

Viewed 3,024 times

3

I’m having trouble with my job if and else, I started my programming studies a short time ago and didn’t understand very well how to use.

It’s something like that?

número = 2
If número == 2:
Print("esse número é 2")
Else:
Print("esse número é diferente de 2")

1 answer

4

For starters, it’s good to know that if and else are not functions. They are what we call conditional selection structures. The example you showed is correct (except for the indentation and the uppercase initials on if and Else).

If you just want to do something if a condition is true, use the if

# código que vem antes
if 3 < 5:
    print("Três é menor que 5")
#código que vem depois

If you want to do something if a condition is true and something different if it is false, use the if ... else:

umaVerdade = True

if umaVerdade:
    print("É verdade")
else:
    print("Não é verdade")

If you have several cases to consider, also use the elif

entrada = input("Digite uma letra")

if entrada == "A" or entrada == "a":
    print("Você digitou a primeira letra do alfabeto português")
elif entrada == "Z" or entrada == "z":
    print("Você digitou a última letra do alfabeto português")
else:
    print("Você digitou uma coisa meio desinteressante")

Notice you have one else at the end. Before it can come how many elif are necessary to cover all cases with specific treatments.

  • Thank you, I was doubting that.

  • In his example not only identation - but the use of capital letters and minuscules is wrong too. if, else and all Python keywords are written in lower case letters.

  • True. Unfortunately I work with a variant of VB. This thing picks, rs.

Browser other questions tagged

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