Синтаксис оператора if
Давайте ще раз розглянемо конструкцію умовного оператора if
та розглянемо ще один приклад.
age = 18 if age == 18: print('Adult')
Обговоримо синтаксис.
Ключове слово для умовного оператора -
if
. Важливо зазначити, що регістр має значення. Тому використанняIf
з великої літери І призведе до помилки, оскільки це невірно;Після ключового слова
if
ми бачимо умову. Варто згадати, що умови можуть бути виражені різними способами, на які ми заглибимося згодом. У нашому прикладі ми перевіряємо, чи змінна дорівнює певному значенню, і для цього ми використовуємо оператор рівності;Потім, після умови, ми ставимо двокрапку;
Далі йде відступ, який вказує на код, що виконується всередині блоку if.
Тобто, це інструкція, яка виконується, якщо наші умови є 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.
Рішення
Дякуємо за ваш відгук!