Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Syntax of if Statement | Python if Statement
Conditional Statements in Python Clone
セクション 1.  2
single

single

bookSyntax of if Statement

メニューを表示するにはスワイプしてください

The if statement is a foundational tool in Python that allows us to make decisions in our code.

Let's break down the key components of the if statement syntax:

  • Keyword if: this keyword begins the conditional statement. Remember, it is case-sensitive—using If instead of if will cause an error;
  • Condition: the condition is an expression that evaluates to True or False. In this example, we check if a variable meets a certain requirement;
  • Colon :: the colon signals that the following indented block belongs to the if statement;
  • Indented Code Block: this block contains the code that runs only if the condition is True.

Example 1: Standart Execution

12345
steps_taken = 7500 step_goal = 10000 if steps_taken < step_goal: print(f"Keep going! You need {step_goal - steps_taken} more steps to reach your goal.")
copy

Explanation

  1. The condition steps_taken < step_goal checks if the number of steps taken is less than the daily goal;
  2. If the condition is True, the code inside the if block is executed;
  3. The message uses an f-string to dynamically include the number of steps remaining, making the output user-friendly and precise.

Example 2: When Nothing Executed

12345
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.")
copy

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 or False;
  • Execution: if the condition is True, the indented code block runs. Otherwise, the program skips it.
タスク

スワイプしてコーディングを開始

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.

解答

Switch to desktop実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  2
single

single

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

some-alt