Sintaxe do comando if
Vamos revisitar a construção da instrução if
e considerar outro exemplo.
age = 18 if age == 18: print('Adult')
Fale sobre a sintaxe.
A palavra-chave usada para o operador condicional é
if
. É essencial notar que ela é sensível a maiúsculas e minúsculas. Portanto, usarIf
com um 'I' maiúsculo resultará em um erro, pois é incorreto;Seguindo a palavra-chave
if
, encontramos uma condição. Vale mencionar que as condições podem ser expressas de várias maneiras, um tópico que exploraremos mais adiante. Em nosso exemplo, estamos verificando se uma variável é igual a um valor específico, e para fazer isso, empregamos o operador de igualdade;Então, após a condição, colocamos dois pontos;
Em seguida, temos um recuo de código que é executado dentro do bloco if.
Ou seja, esta é uma instrução que é executada se nossas condições forem True.
Example 2: When Nothing Executed
steps_taken = 10000 step_goal = 10000 if steps_taken < step_goal: print(f"Keep going! You need {step_goal - steps_taken} more steps to reach your goal.")
In this case, the condition steps_taken < step_goal
evaluates to False
because steps_taken
is equal to step_goal
. Since the condition is not met, the code block inside the if
statement is not executed, and nothing is printed to the console. This demonstrates that the code only runs when the condition evaluates to True
.
The image depicts the flow of an if statement:
Condition Check: the program evaluates whether the condition is
True
orFalse
;Execution: if the condition is
True
, the indented code block runs. Otherwise, the program skips it.
Swipe to start coding
Your Fitness Tracker needs to do more than just check steps! This time, it will motivate users to complete their workout by comparing their calories burned against daily goals.
Fill in the blanks in the code you've already been given.
Once you've completed this task, click the button below the code to check your solution.
Solução
Obrigado pelo seu feedback!