Em Python, as instruções if, elif (contração de «else and if») e else são usadas para controlar o fluxo de execução e tomar decisões num programa.
Ao contrário de muitas outras linguagens de programação, as versões 3.9 e anteriores do Python não oferecem uma instrução formal de tipo case-switch; em vez disso, recorrem a várias instruções elif para cumprir um objetivo semelhante.
O Python 3.10 introduz uma variante da instrução case-switch chamada pattern matching, que será abordada em separado noutro conceito.
As condicionais usam expressões que têm de resultar em True ou False, quer devolvendo diretamente um bool, quer avaliando «truthy» ou «falsy».
x = 10
y = 5
# The comparison '>' returns the bool 'True',
# so the statement is printed.
if x > y:
print("x is greater than y")
...
>>> x is greater than y
Quando emparelhado com um if, um bloco de código else opcional é executado quando a condição if original for avaliada como False:
x = 5
y = 10
# The comparison '>' here returns the bool False,
# so the 'else' block is executed instead of the 'if' block.
if x > y:
print("x is greater than y")
else:
print("y is greater than x")
...
>>> y is greater than x
O elif permite várias avaliações/ramos.
x = 5
y = 10
z = 20
# The elif statement allows for the checking of more conditions.
if x > y > z:
print("x is greater than y and z")
elif y > x > z:
print("y is greater than x and z")
else:
print("z is greater than x and y")
...
>>> z is greater than x and y
As operações booleanas e as comparações podem ser combinadas com condicionais para testes mais complexos:
>>> def classic_fizzbuzz(number):
... if number % 3 == 0 and number % 5 == 0:
... say = 'FizzBuzz!'
... elif number % 5 == 0:
... say = 'Buzz!'
... elif number % 3 == 0:
... say = 'Fizz!'
... else:
... say = str(number)
...
... return say
>>> classic_fizzbuzz(15)
'FizzBuzz!'
>>> classic_fizzbuzz(13)
'13'
Em alternativa, o exemplo acima pode ser reescrito para usar apenas instruções if com returns.
No entanto, reescrever desta forma pode esconder que as condições se destinam a ser mutuamente exclusivas e pode levar a erros futuros ou a problemas de manutenção.
>>> def classic_fizzbuzz(number):
... if number % 3 == 0 and number % 5 == 0:
... return 'FizzBuzz!'
... if number % 5 == 0:
... return 'Buzz!'
... if number % 3 == 0:
... return 'Fizz!'
...
... return str(number)
>>> classic_fizzbuzz(15)
'FizzBuzz!'
>>> classic_fizzbuzz(13)
'13'
As condicionais também podem ser aninhadas.
>>> def driving_status(driver_age, test_score):
... if test_score >= 80:
... if 18 > driver_age >= 16:
... status = "Student driver, needs supervision."
... elif driver_age == 18:
... status = "Permitted driver, on probation."
... elif driver_age > 18:
... status = "Fully licensed driver."
... else:
... status = "Unlicensed!"
...
... return status
>>> driving_status(63, 78)
'Unlicensed!'
>>> driving_status(16, 81)
'Student driver, needs supervision.'
>>> driving_status(23, 80)
'Fully licensed driver.'
Embora o Python não tenha um operador ternário ? específico, é possível escrever conditional expressions numa única linha.
Estas assumem a forma <value if True> if <conditional test> else <value if False>.
Como estas expressões se podem tornar difíceis de ler, recomenda-se usar esta forma numa única linha apenas se encurtar o código e ajudar na legibilidade.
>>> def just_the_buzz(number):
... return 'Buzz!' if number % 5 == 0 else str(number)
>>> just_the_buzz(15)
'Buzz!'
>>> just_the_buzz(7)
'7'
Em Python, qualquer objeto pode ser testado quanto ao valor de verdade e, por isso, pode ser usado com uma condicional, uma comparação ou uma operação booleana.
Os objetos avaliados desta forma são considerados «truthy» ou «falsy» e usados num boolean context.
>>> def truthy_test(thing):
... if thing:
... print('This is Truthy.')
... else:
... print("Nope. It's Falsy.")
# Empty container objects are considered Falsy.
>>> truthy_test([])
"Nope. It's Falsy."
>>> truthy_test(['bear', 'pig', 'giraffe'])
'This is Truthy.'
# Empty strings are considered Falsy.
>>> truthy_test('')
"Nope. It's Falsy."
>>> truthy_test('yes')
'This is Truthy.'
# 0 is also considered Falsy.
>>> truthy_test(0)
"Nope. It's Falsy."