Understanding Python if Statements: Syntax, Examples, and Nested Conditions
This article explains Python's conditional statements, covering the if‑elif‑else syntax, important formatting rules, and multiple practical code examples—including simple if usage, dog age calculation, equality checks, a number‑guessing game, and nested conditions—to help beginners master flow control.
Python conditional statements execute code blocks based on the Boolean result (True or False) of one or more expressions, allowing programs to make decisions.
The general form of an if statement is:
<code>if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3</code>When condition_1 is True, statement_block_1 runs; if it is False, Python evaluates condition_2 . If condition_2 is True, statement_block_2 runs; otherwise the else block executes.
Key points to remember:
Each condition must end with a colon ( : ) to indicate the start of the block.
Indentation defines the block; statements with the same indentation belong to the same block.
Python does not have a switch‑case construct.
Simple if example:
<code>#!/usr/bin/python3
var1 = 100
if var1:
print("1 - if 表达式条件为 true")
print(var1)
var2 = 0
if var2:
print("2 - if 表达式条件为 true")
print(var2)
print("Good bye!")</code>Running this script outputs:
<code>1 - if 表达式条件为 true
100
Good bye!</code>Because var2 is 0 (False), its block is skipped.
Dog age calculation example:
<code>#!/usr/bin/python3
age = int(input("请输入你家狗狗的年龄: "))
print("")
if age < 0:
print("你是在逗我吧!")
elif age == 1:
print("相当于 14 岁的人。")
elif age == 2:
print("相当于 22 岁的人。")
elif age > 2:
human = 22 + (age - 2) * 5
print("对应人类年龄: ", human)
input("点击 enter 键退出")
</code>When the user enters 1 , the script prints that the dog is equivalent to a 14‑year‑old human.
Equality operator demonstration:
<code>#!/usr/bin/python3
print(5 == 6) # False
x = 5
y = 8
print(x == y) # False
</code>Both comparisons evaluate to False .
Number guessing game (high_low.py):
<code>#! /usr/bin/python3
number = 7
guess = -1
print("数字猜谜游戏!")
while guess != number:
guess = int(input("请输入你猜的数字:"))
if guess == number:
print("恭喜,你猜对了!")
elif guess < number:
print("猜的数字小了...")
elif guess > number:
print("猜的数字大了...")
</code>The script interacts with the user until the correct number is guessed, providing feedback for each attempt.
Nested if example (checking divisibility by 2 and 3):
<code># !/usr/bin/python3
num = int(input("输入一个数字:"))
if num % 2 == 0:
if num % 3 == 0:
print("你输入的数字可以整除 2 和 3")
else:
print("你输入的数字可以整除 2,但不能整除 3")
else:
if num % 3 == 0:
print("你输入的数字可以整除 3,但不能整除 2")
else:
print("你输入的数字不能整除 2 和 3")
</code>Running this with input 6 prints that the number is divisible by both 2 and 3.
These examples collectively demonstrate how to use Python's conditional statements to control program flow, handle user input, and build simple interactive applications.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.