logo

Expressões condicionais em Python

As instruções condicionais do Python realizam vários cálculos ou operações dependendo se uma determinada condição booleana é avaliada como verdadeira ou falsa. Em Python, as instruções IF lidam com instruções condicionais.

Aprenderemos como usar instruções condicionais em Python neste tutorial.

O que é a instrução If do Python?

Para tomar decisões, utilize a instrução if em Python. Possui um corpo de instruções que só é executado sempre que a condição da instrução if for atendida. A instrução else adicional, que inclui algumas instruções para a instrução else, será executada se a condição if for falsa.

A instrução if-else do Python é usada quando você deseja satisfazer uma instrução enquanto a outra é falsa.

Sintaxe Python da instrução if:

 if Statement else Statement 

Código

 # Python program to execute if statement a, b = 6, 5 # Initializing the if condition if a > b: code = 'a is greater than b' print(code) 

Saída:

 a is greater than b 

Como usar a condição else?

A 'condição else' é geralmente usada ao julgar uma afirmação com base em outra. Se a condição mencionada no bloco de código if estiver errada, o interpretador executará o bloco de código else.

Código

 # Python program to execute if-else statement a, b = 6, 5 # Initializing the if-else condition if a <b: code="a is less than b" print(code) else: print('a is greater than b') < pre> <p> <strong>Output:</strong> </p> <pre> a is greater than b </pre> <h2>When the else Statement does not Work</h2> <p>There could be a lot of situations where your &apos;otherwise condition&apos; doesn&apos;t produce the desired outcome. Due to a flaw in the program&apos;s logic, it will print the incorrect result. This typically occurs when there are more than two statements or conditions in a program.</p> <p>An illustration will make this notion easier for you to grasp.</p> <p>Since both variables, in this case, are identical (9, 9), the program&apos;s output that &apos;x is greater than y&apos; is FALSE. This is because it evaluates the first condition, or the if expression in Python, then prints the next condition (the else statement) by default if the first condition fails. The following step will examine how to fix this mistake.</p> <p> <strong>Code</strong> </p> <pre> # Python program when else condition does not work a, b = 9, 9 # Initializing the if-else condition if a <b: code="a is less than b" else: print(code) < pre> <p> <strong>Output:</strong> </p> <pre> a is greater than b </pre> <h2>How to use the elif Condition?</h2> <p>We can employ the &apos;elif&apos; clause to fix the issue caused by the &apos;else condition&apos; made earlier. You can instruct the software to print the third condition or alternative when the first two conditions fail or are erroneous by using the &apos;elif&apos; condition.</p> <p> <strong>Code</strong> </p> <pre> # Python program to show how to use elif condition a, b = 9, 9 # Initializing the if-else condition if a <b: code="a is less than b" elif a="=" b: else: print(code) < pre> <p> <strong>Output:</strong> </p> <pre> a is equal to b </pre> <h2>Python Nested if Statement</h2> <p>The following example demonstrates nested if Statement Python</p> <p> <strong>Code</strong> </p> <pre> # Python program to show the nested if-else conditions A = 100 B = 200 C = 300 # Initializing the if-else conditions if B &gt; A: if B &gt; C: print(&apos;B is the largest number&apos;) else: if A &gt; B: if A &gt; C: print(&apos;A is the largest number&apos;) elif C &gt; A: if C &gt; B: print(&apos;C is the largest number&apos;) else: print(&apos;All numbers are equal&apos;) if B % C == 0: if A % C == 0: print(&apos;C is a common factor of A and B&apos;) </pre> <p> <strong>Output:</strong> </p> <pre> C is the largest number </pre> <hr></b:></pre></b:></pre></b:>

Quando a instrução else não funciona

Pode haver muitas situações em que a sua 'condição contrária' não produz o resultado desejado. Devido a uma falha na lógica do programa, ele imprimirá o resultado incorreto. Isso normalmente ocorre quando há mais de duas instruções ou condições em um programa.

Uma ilustração tornará essa noção mais fácil de entender.

Como ambas as variáveis, neste caso, são idênticas (9, 9), a saída do programa de que 'x é maior que y' é FALSA. Isso ocorre porque ele avalia a primeira condição, ou a expressão if em Python, e então imprime a próxima condição (a instrução else) por padrão se a primeira condição falhar. A etapa a seguir examinará como corrigir esse erro.

Código

 # Python program when else condition does not work a, b = 9, 9 # Initializing the if-else condition if a <b: code="a is less than b" else: print(code) < pre> <p> <strong>Output:</strong> </p> <pre> a is greater than b </pre> <h2>How to use the elif Condition?</h2> <p>We can employ the &apos;elif&apos; clause to fix the issue caused by the &apos;else condition&apos; made earlier. You can instruct the software to print the third condition or alternative when the first two conditions fail or are erroneous by using the &apos;elif&apos; condition.</p> <p> <strong>Code</strong> </p> <pre> # Python program to show how to use elif condition a, b = 9, 9 # Initializing the if-else condition if a <b: code="a is less than b" elif a="=" b: else: print(code) < pre> <p> <strong>Output:</strong> </p> <pre> a is equal to b </pre> <h2>Python Nested if Statement</h2> <p>The following example demonstrates nested if Statement Python</p> <p> <strong>Code</strong> </p> <pre> # Python program to show the nested if-else conditions A = 100 B = 200 C = 300 # Initializing the if-else conditions if B &gt; A: if B &gt; C: print(&apos;B is the largest number&apos;) else: if A &gt; B: if A &gt; C: print(&apos;A is the largest number&apos;) elif C &gt; A: if C &gt; B: print(&apos;C is the largest number&apos;) else: print(&apos;All numbers are equal&apos;) if B % C == 0: if A % C == 0: print(&apos;C is a common factor of A and B&apos;) </pre> <p> <strong>Output:</strong> </p> <pre> C is the largest number </pre> <hr></b:></pre></b:>

Como usar a condição elif?

Podemos empregar a cláusula 'elif' para corrigir o problema causado pela 'condição else' feita anteriormente. Você pode instruir o software a imprimir a terceira condição ou alternativa quando as duas primeiras condições falharem ou forem errôneas, usando a condição 'elif'.

Código

 # Python program to show how to use elif condition a, b = 9, 9 # Initializing the if-else condition if a <b: code="a is less than b" elif a="=" b: else: print(code) < pre> <p> <strong>Output:</strong> </p> <pre> a is equal to b </pre> <h2>Python Nested if Statement</h2> <p>The following example demonstrates nested if Statement Python</p> <p> <strong>Code</strong> </p> <pre> # Python program to show the nested if-else conditions A = 100 B = 200 C = 300 # Initializing the if-else conditions if B &gt; A: if B &gt; C: print(&apos;B is the largest number&apos;) else: if A &gt; B: if A &gt; C: print(&apos;A is the largest number&apos;) elif C &gt; A: if C &gt; B: print(&apos;C is the largest number&apos;) else: print(&apos;All numbers are equal&apos;) if B % C == 0: if A % C == 0: print(&apos;C is a common factor of A and B&apos;) </pre> <p> <strong>Output:</strong> </p> <pre> C is the largest number </pre> <hr></b:>

Instrução if aninhada em Python

O exemplo a seguir demonstra a instrução if aninhada Python

Código

 # Python program to show the nested if-else conditions A = 100 B = 200 C = 300 # Initializing the if-else conditions if B &gt; A: if B &gt; C: print(&apos;B is the largest number&apos;) else: if A &gt; B: if A &gt; C: print(&apos;A is the largest number&apos;) elif C &gt; A: if C &gt; B: print(&apos;C is the largest number&apos;) else: print(&apos;All numbers are equal&apos;) if B % C == 0: if A % C == 0: print(&apos;C is a common factor of A and B&apos;) 

Saída:

 C is the largest number