Python if statement (if, elif, else) | note.nkmk.me (2024)

This article explains the basic syntax of Python's if statement (if ... elif ... else ...), including how to specify multiple conditions and negated conditions.

Contents

  • Python if statement syntax: if, elif, else
    • if
    • if ... else ...
    • if ... elif ...
    • if ... elif ... else ...
  • Conditions in if statements
    • Expressions that return bool (comparison operators, in operator, etc.)
    • Non-bool cases
  • Multiple conditions in if statements: and, or
  • Negation in if statements: not
  • How to write a condition across multiple lines

Python also provides a ternary operator for writing single-line conditional branching. See the following article for more information.

  • Conditional expression (ternary operator) in Python

Python if statement syntax: if, elif, else

The basic structure of a Python if statement is as follows.

if condition_1: # Execute if condition_1 is trueelif condition_2: # Execute if condition_1 is false and condition_2 is trueelif condition_3: # Execute if condition_1 and condition_2 are false, and condition_3 is true...else: # Execute if all preceding conditions are false

In Python, blocks are expressed with indentation (usually four spaces) rather than brackets.

  • Python indentation rules

In the following examples, the def statement is used to define functions, and f-strings are used to embed variables into strings.

  • Define and call functions in Python (def, return)
  • How to use f-strings in Python

if

In the case of if only, the specified process is executed if the condition evaluates to true, and nothing is done if it evaluates to false.

def if_only(n): if n > 0: print(f'{n} is positive')if_only(100)# 100 is positiveif_only(-100)

source: if_basic.py

It is not necessary to enclose the condition in parentheses (), but doing so will not cause an error.

Although the example shows the process inside the block as only one line, you can write a multi-line process as well.

if ... else ...

The else clause allows you to add a process for when the condition evaluates to false.

def if_else(n): if n > 0: print(f'{n} is positive') else: print(f'{n} is negative or zero')if_else(100)# 100 is positiveif_else(-100)# -100 is negative or zero

source: if_basic.py

if ... elif ...

The elif clause allows you to add processes for different conditions. elif corresponds to else if or elseif in other programming languages and can be used multiple times.

Conditions are checked in order from the top, and the block with the first condition determined to be true is executed. Nothing is done if all conditions are false.

def if_elif(n): if n > 0: print(f'{n} is positive') elif n == 0: print(f'{n} is zero') elif n == -1: print(f'{n} is minus one')if_elif(100)# 100 is positiveif_elif(0)# 0 is zeroif_elif(-1)# -1 is minus oneif_elif(-100)

source: if_basic.py

As described later, you can also specify a combination of multiple conditions in a single expression using and or or.

if ... elif ... else ...

The elif and else clauses can be used together in the same conditional branching structure. Note that else must be the last clause.

The process in the else clause is executed if all preceding conditions evaluate as false.

def if_elif_else(n): if n > 0: print(f'{n} is positive') elif n == 0: print(f'{n} is zero') else: print(f'{n} is negative')if_elif_else(100)# 100 is positiveif_elif_else(0)# 0 is zeroif_elif_else(-100)# -100 is negative

source: if_basic.py

Conditions in if statements

Expressions that return bool (comparison operators, in operator, etc.)

You can use expressions that return bool values (True or False) in if statement conditions. Comparison operators are typical examples of such expressions.

Python has the following comparison operators:

OperatorResult
x < yTrue if x is less than y
x <= yTrue if x is less than or equal to y
x > yTrue if x is greater than y
x >= yTrue if x is greater than or equal to y
x == yTrue if x is equal to y
x != yTrue if x is not equal to y
x is yTrue if x and y are the same object
x is not yTrue if x and y are not the same object

See the following article for the difference between == and is.

  • Difference between the == and is operators in Python

Python also allows chaining of comparison operators, such as a < x < b.

  • Chained comparison (a < x < b) in Python

You may also use in and not in to check whether a list or string contains a specific element or substring.

  • The in operator in Python (for list, string, dictionary, etc.)
def if_in(s): if 'a' in s: print(f'"a" is in "{s}"') else: print(f'"a" is not in "{s}"')if_in('apple')# "a" is in "apple"if_in('cherry')# "a" is not in "cherry"

source: if_basic.py

You can also specify methods or functions that return bool as a condition in the if statement. For example, the startswith() method checks if a string starts with a specific substring.

  • String comparison in Python (exact/partial match, etc.)
def if_startswith(s): if s.startswith('a'): print(f'"{s}" starts with "a"') else: print(f'"{s}" does not start with "a"')if_startswith("apple")# "apple" starts with "a"if_startswith("banana")# "banana" does not start with "a"

source: if_basic.py

Non-bool cases

You can use non-bool values, such as numbers or lists, and expressions that return those values as if statement conditions.

if 100: print('True')# Trueif [0, 1, 2]: print('True')# True

source: if_basic.py

In Python, the following objects are considered false:

Numeric values representing zero, as well as empty strings and empty lists, are considered false, while all other values are considered true.

This can be used to write simple conditions, such as checking if a list is empty, without retrieving the number of elements.

def if_is_empty(l): if l: print(f'{l} is not empty') else: print(f'{l} is empty')if_is_empty([0, 1, 2])# [0, 1, 2] is not emptyif_is_empty([])# [] is empty

source: if_basic.py

Remember, non-empty strings, including 'False', are considered true. To convert specific strings such as 'True' or 'False' to 1 or 0, you can use the distutils.util.strtobool() function. See the following article for more information.

  • Convert between bool (True/False) and other types in Python

Multiple conditions in if statements: and, or

To combine multiple conditions in an if statement using logical AND or OR, employ the and or or operators, respectively.

def if_and(n): if n > 0 and n % 2 == 0: print(f'{n} is positive-even') else: print(f'{n} is not positive-even')if_and(10)# 10 is positive-evenif_and(5)# 5 is not positive-evenif_and(-10)# -10 is not positive-even

source: if_basic.py

You can use and or or multiple times in a single expression.

def if_and_or(n): if n > 0 and n % 2 == 0 or n == 0: print(f'{n} is positive-even or zero') else: print(f'{n} is not positive-even or zero')if_and_or(10)# 10 is positive-even or zeroif_and_or(5)# 5 is not positive-even or zeroif_and_or(0)# 0 is positive-even or zero

source: if_basic.py

The order of precedence for Boolean operators is not > and > or (with not being the highest). For more details, see the following article.

  • Boolean operators in Python (and, or, not)

Negation in if statements: not

To specify the negation (NOT) in an if statement, use the not operator.

def if_not(s): if not s.startswith('a'): print(f'"{s}" does not start with "a"') else: print(f'"{s}" starts with "a"')if_not("apple")# "apple" starts with "a"if_not("banana")# "banana" does not start with "a"

source: if_basic.py

However, for operators such as == or >, it is recommended to use their opposite counterparts directly, like != or <=, rather than not.

How to write a condition across multiple lines

For long conditions using and or or, you can break them into multiple lines using a backslash \ or enclosing the entire expression in parentheses ().

Although written differently, the following three functions are equivalent.

def if_no_newline(): if too_long_name_function_1() and too_long_name_function_2() and too_long_name_function_3(): print('True') else: print('False')

source: if_basic.py

def if_backslash(): if too_long_name_function_1() \ and too_long_name_function_2() \ and too_long_name_function_3(): print('True') else: print('False')

source: if_basic.py

def if_parentheses(): if ( too_long_name_function_1() and too_long_name_function_2() and too_long_name_function_3() ): print('True') else: print('False')

source: if_basic.py

You can break lines as many times as needed using backslash \ or parentheses (), without indentation restrictions. This technique can be used anywhere in Python code, not just in if statements.

  • Write a long string on multiple lines in Python
Python if statement (if, elif, else) | note.nkmk.me (2024)

References

Top Articles
Wok Uberinternal
Minn Kota Paws
English Bulldog Puppies For Sale Under 1000 In Florida
Using GPT for translation: How to get the best outcomes
COLA Takes Effect With Sept. 30 Benefit Payment
Aadya Bazaar
Arrests reported by Yuba County Sheriff
How To Get Free Credits On Smartjailmail
What is the difference between a T-bill and a T note?
Best Fare Finder Avanti
Meritas Health Patient Portal
2016 Ford Fusion Belt Diagram
Alexander Funeral Home Gallatin Obituaries
3S Bivy Cover 2D Gen
Curver wasmanden kopen? | Lage prijs
Nearest Walgreens Or Cvs Near Me
Mail.zsthost Change Password
Yisd Home Access Center
Aes Salt Lake City Showdown
SN100C, An Australia Trademark of Nihon Superior Co., Ltd.. Application Number: 2480607 :: Trademark Elite Trademarks
Ontdek Pearson support voor digitaal testen en scoren
Vivaciousveteran
How To Find Free Stuff On Craigslist San Diego | Tips, Popular Items, Safety Precautions | RoamBliss
Table To Formula Calculator
Past Weather by Zip Code - Data Table
Prévisions météo Paris à 15 jours - 1er site météo pour l'île-de-France
Fedex Walgreens Pickup Times
How to Use Craigslist (with Pictures) - wikiHow
Half Inning In Which The Home Team Bats Crossword
Lil Durk's Brother DThang Killed in Harvey, Illinois, ME Confirms
Composite Function Calculator + Online Solver With Free Steps
67-72 Chevy Truck Parts Craigslist
Western Gold Gateway
Natashas Bedroom - Slave Commands
Die Filmstarts-Kritik zu The Boogeyman
Mars Petcare 2037 American Italian Way Columbia Sc
5A Division 1 Playoff Bracket
Gotrax Scooter Error Code E2
The Horn Of Plenty Figgerits
Sacramentocraiglist
Sams Gas Price San Angelo
Legs Gifs
Fine Taladorian Cheese Platter
Here’s What Goes on at a Gentlemen’s Club – Crafternoon Cabaret Club
Assignation en paiement ou injonction de payer ?
Superecchll
라이키 유출
Craigslist.raleigh
Used Curio Cabinets For Sale Near Me
Invitation Quinceanera Espanol
What Are Routing Numbers And How Do You Find Them? | MoneyTransfers.com
Latest Posts
Article information

Author: Roderick King

Last Updated:

Views: 6447

Rating: 4 / 5 (51 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Roderick King

Birthday: 1997-10-09

Address: 3782 Madge Knoll, East Dudley, MA 63913

Phone: +2521695290067

Job: Customer Sales Coordinator

Hobby: Gunsmithing, Embroidery, Parkour, Kitesurfing, Rock climbing, Sand art, Beekeeping

Introduction: My name is Roderick King, I am a cute, splendid, excited, perfect, gentle, funny, vivacious person who loves writing and wants to share my knowledge and understanding with you.