Python Tutorial - If Else Conditional Statement Part I

Python Exercise Lists

The code we saw earlier is executed sequentially, that is, the first statement is executed, then the second, third, and so on. all the way to the last statement, which is called a sequential structure.

However, in many cases, the code of the sequential structure is far from enough. For example, a door restricts the entry to adults only, and children do not have permission to use it because they are not old enough. At this time, the door program needs to make a judgment to see if the user is an adult and give a prompt.

In Python, you can use if else statements to evaluate conditions and then execute different code based on different results. This is called a selection structure or a branch structure.

The if else statement in Python can be subdivided into three forms, namely if statement, if else statement, and if elif else statement. Their syntax and execution flow are shown in the following:

Form 1:
if expression:
 Code block
Form 2:
if expression:
    Code block 1
else:
    Code block 2
Form 3:
f expression 1:
    Code block 1
elif expression 2:
    Code block 2
elif expression 3:
    Code block 3
... // other elif statements
else:
    Code block n
           

Of the above three forms, the second and third forms are interlinked. If the elif block in the third form does not appear, it becomes the second form. In addition, neither elif nor else can be used alone, they must appear with if and they must be paired correctly.

Explanation of Python Syntax Format:

  • An "expression" can be a single value or a variable, or it can be a complex statement composed of operators. The form is not limited as long as it can get a value. Regardless of the type of "expression" result, if else can determine whether it is true (true or false).
  • A "code block" consists of several statements with the same indentation.
  • There are semicolons at the end of if, elif, else statements; don't forget.

Once an expression is true, Python executes the code block behind it; if all expressions are not true, then the code block after else is executed; if there is no else part, nothing is executed.

The simplest implementation is the first form-there is only one if part. If the expression is true (true), the following code block is executed; if the expression is not true (false), nothing is executed.

For the second form, if the expression is true, then execute code block 1 immediately after if; if the expression is not true, execute code block 2 immediately after else.

For the third form, Python will determine whether the expression is true one by one from top to bottom. Once it meets a certain expression, it will execute the following block; at this time, the remaining code will not be executed. Regardless of whether the following expressions hold. If all expressions are not true, the code block following the else is executed.

In general, no matter how many branches, only one branch can be executed, or none can be executed, and multiple branches cannot be executed at the same time.

[Example] Use the first selection structure to determine whether the user meets the conditions:

age = int (input ("Please enter your age:"))
if age <18:
    print ("You are not yet an adult, access denies!")
#This statement does not belong to the code block of if
print ("Welcome to the ...")
           

The output is:

Please enter your age: 6
You are not yet an adult, access denies!
Welcome to the ...

It can be seen from the running results that if the input age is less than 18, the statement block after if is executed; if the input age is 18 or more, the statement block after if is not executed. The block here is print () statements indented four spaces.

[Example] Improve the above code, and exit the program when the age does not match:

import sys
age = int (input ("Please enter your age:"))
if age <18:
    print ("Warning: You are underage and access denies!")
    print ("Please come again when you have above age 18.")
    sys.exit ()
else:
    print ("You are an adult, you can enter.")
    print ("Time is precious, please don't waste too much time to come here.")
print ("Welcome to the ...")
           

The output is:

Please enter your age:15
Warning: You are underage and access denies!
Please come again when you have above age 18.

The exit () function of the sys module is used to exit the program.

[Example] Determine whether a person's figure is reasonable:

height = float (input ("Input height (meters):"))
weight = float (input ("input weight in kilograms:"))
bmi = weight / (height * height) #Calculate BMI index
if bmi <18.5:
    print ("BMI index is:" + str(bmi))
    print ("underweight")
elif bmi >= 18.5 and bmi <24.9:
    print ("BMI index is:" + str(bmi))
    print ("Normal range, keep attention")
elif bmi >= 24.9 and bmi <29.9:
    print ("BMI index is:" + str(bmi))
    print ("overweight")
else:
    print ("BMI index is:" + str(bmi))
    print ("Fat")
           

The output is:

Input height (meters):1.6
input weight in kilograms:52
"BMI index is: 20.3125"
print ("Normal range, keep attention"

It needs to be emphasized that Python is a very unique programming language. It recognizes code blocks by indentation. Several lines of code with the same indentation amount belong to the same code block, so you can't indent randomly. This can easily lead to syntax error. For more on indentation, go to "Python if else Indentation Requirements."

                               


More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression


More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises