Python From Beginner to Advanced

0% completed

Previous
Next
Python - if statement

Conditional statements are a fundamental part of programming, allowing the code to make decisions and react differently based on different inputs or states. In Python, conditional statements evaluate whether a condition is true or false, and then execute specific blocks of code accordingly. These decisions help control the flow of execution in a program, making it dynamic and responsive.

Python - If Statement

The if statement in Python is used for decision-making. It allows the program to execute a block of code only when a certain condition is met. This is useful for controlling the flow of execution based on specific conditions.

Syntax

if condition: # Code to execute if the condition is True

The condition is an expression that evaluates to either True or False. If the condition is True, the indented code block will be executed. Otherwise, the program will skip that block.

Understanding Indentation

Python uses indentation to define blocks of code. Unlike some other programming languages that use curly braces {} to indicate blocks, Python relies on consistent indentation.

Example of correct indentation

Python3
Python3

. . . .

If the indentation is incorrect, Python will raise an error:

Python3
Python3
. . . .

This will result in an IndentationError.

Example of "if" statement

Let's consider a real-world example:

Python3
Python3

. . . .

Explanation:

  1. The variable age is assigned the value 18.
  2. The condition age >= 18 is checked.
  3. Since age is 18, which is greater than or equal to 18, the condition evaluates to True.
  4. The indented block of code executes, printing: You are eligible to vote.

If age were less than 18, the condition would be False, and nothing would be printed.

This basic understanding of if statements will help in writing logic-driven programs effectively.

.....

.....

.....

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