Python From Beginner to Advanced

0% completed

Previous
Next
Python - if...else statement

The if-else statement in Python is used to make decisions in a program. If a condition evaluates to True, the code inside the if block executes. Otherwise, the code inside the else block runs. This allows programs to choose between two different paths based on conditions.

Syntax

if condition: # Code to execute if the condition is True else: # Code to execute if the condition is False
  • The if block runs when the condition is True.
  • If the condition is False, the else block executes.

Examples

Example 1: Checking Temperature

Python3
Python3

. . . .

Explanation

  1. The variable temperature is assigned 25.
  2. The condition temperature >= 30 is checked.
  3. Since 25 is less than 30, the condition is False, so the else block runs.

Example 2: Checking Pass or Fail

Python3
Python3

. . . .

Explanation

  1. The variable score is set to 45.
  2. The condition score >= 50 is checked.
  3. Since 45 is less than 50, the condition is False, so the else block runs.

The if-else statement helps in decision-making by executing different blocks of code based on a condition. It ensures that specific actions take place depending on given conditions, making the program dynamic and responsive to different inputs.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next