StudyLover
  • Home
  • Study Zone
  • Profiles
  • Contact us
  • Sign in
StudyLover if-else
Download
  1. Python
  2. Unlocking Python: Foundations for Coding
Control Statements : Nested if-else
Unlocking Python: Foundations for Coding

Python if Condition

The if statement is a fundamental control flow structure in Python that allows you to execute different code blocks based on whether a specified condition is true or false.

Syntax

Python

if condition:

    # code to be executed if condition is true

How it works

1.    The if keyword is followed by a condition, which is an expression that evaluates to either True or False.

2.    If the condition is True, the indented code block following the if statement is executed.

3.    If the condition is False, the code block is skipped.

Example

Python

age = 18

 

if age >= 18:

    print("You are an adult.")

Indentation

Python relies on indentation to define code blocks. The code within an if block must be indented with the same number of spaces or tabs.

The else Statement

You can use the else statement to specify an alternative block of code to be executed if the condition is false.

Python

age = 17

 

if age >= 18:

    print("You are an adult.")

else:

    print("You are a minor.")

The elif Statement

The elif (short for "else if") statement allows you to check multiple conditions sequentially.

Python

age = 15

 

if age >= 18:

    print("You are an adult.")

elif age >= 13:

    print("You are a teenager.")

else:

    print("You are a child.")

Important Points

  • You can have multiple elif statements after an if statement.

  • The else statement is optional.

  • The conditions are evaluated from top to bottom, and the first condition that is True will execute its corresponding code block.

By understanding and effectively using the if statement, you can create programs that make decisions based on different conditions.

 

Control Statements Nested if-else
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website