Learn Python from Scratch: Using if and if‑else Statements
This tutorial explains Python's three program structures, then details the syntax and execution flow of single‑branch if statements and double‑branch if‑else statements with concrete code examples and their corresponding outputs.
Python programs are divided into three structural categories: sequential, selection (branch), and loop structures.
The selection structure enables conditional execution. The article describes the single‑branch if statement, its syntax ( if expression: followed by indented statements), and the execution flow: when the expression evaluates to True the block runs; otherwise it is skipped.
age = int(input("请输入你的年龄:"))
if age >= 18:
print("欢迎光临本会所!")
print("hello world")With an input of 15, only the "hello world" line is printed, showing that the if block was not executed.
The double‑branch if‑else statement adds an alternative block. Its syntax is if expression: block1 else: block2, ensuring exactly one of the two blocks runs.
age = int(input("请输入你的年龄:"))
if age >= 18:
print("您的年龄满足我们会所的要求,可以进入欢迎光临!")
else:
print("少儿不宜!不能进入")When the input is 15, the output is "少儿不宜!不能进入"; when the input is 21, the output confirms the age meets the requirement.
Lisa Notes
Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.
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.
