Python Tutorials - Herong's Tutorial Examples - v2.15, by Herong Yang
"if" Statement for Conditional Execution
This section provides a quick introduction of 'if' statement, which selects a block of sub-statements to execute based on given conditions.
What Is "if" Statement? An "if" statement is a compound statement that selects a block of sub-statements to execute based on given conditions.
An "if" statements must have an "is" clause followed by multiple optional "elif" clauses and an optional "else" clause:
if condition: sub-statement sub-statement ... elif condition: sub-statement sub-statement ... ... else: sub-statement sub-statement ...
Here is a Python sample code, if_test.py, that shows you how to use "if" statements.
# if_test.py #- Copyright 2011 (c) HerongYang.com. All Rights Reserved. # from datetime import datetime today = datetime.now() weekDay = today.weekday() openHours = "open" if weekDay == 0: openHours = "closed" elif weekDay >= 1 and weekDay <= 5: openHours = "open from 9:00am to 9:00pm" elif weekDay == 6: openHours = "open from 9:00am to 5:00pm" else: openHours = "should never reach here" print(" Today is "+today.strftime("%A")) print(" The library is "+openHours)
If you run this sample code, you should get:
herong> python if_test.py Today is Saturday The library is open from 9:00am to 9:00pm
Note that Python uses indention to identify sub-statement blocks. There is no keywords or brackets to mark the beginning and the ending of a sub-statement block.
Table of Contents
Variables, Operations and Expressions
"pass" Statement - Do Nothing Statement
Expression Statement - One Expression Only
"=" Statement - Assignment Statement
"del" Statement - Delete Statement
"import" Statement to Load Modules
►"if" Statement for Conditional Execution
"while" Statement for Execution Loop
"for" Statement for Iterative Execution
"try" Statement to Catch Execution
"with" Statement for Context Manager
"match" Statement for Pattern Match
Function Statement and Function Call
List, Set and Dictionary Comprehensions
Packages and Package Directories
"pathlib" - Object-Oriented Filesystem Paths
"pip" - Package Installer for Python
SciPy.org - Python Libraries for Science
pandas - Data Analysis and Manipulation
Anaconda - Python Environment Manager