Detailed explanation of Python flow control statements: if, else, elif, while, for
In programming, flow control statements are essential. They are used to Conditions determine the execution flow of a program. Python provides several commonly used flow control statements, including if, else, elif, while and for. This article explains these statements in detail and provides specific code examples.
if 条件: 代码块
The following is a simple example to determine whether a number is greater than 10:
num = 15 if num > 10: print("数字大于10")
if 条件: 代码块1 else: 代码块2
The following is an example to determine whether a number is even:
num = 9 if num % 2 == 0: print("数字为偶数") else: print("数字为奇数")
if 条件1: 代码块1 elif 条件2: 代码块2 else: 代码块3
The following is an example, evaluated according to the grade:
score = 85 if score >= 90: print("优秀") elif score >= 80: print("良好") elif score >= 70: print("中等") elif score >= 60: print("及格") else: print("不及格")
while 条件: 代码块
The following is an example to calculate the cumulative sum from 1 to 10:
sum = 0 num = 1 while num <= 10: sum += num num += 1 print("累加和为:", sum)
for 变量 in 序列: 代码块
The following is an example to calculate the sum of all elements in the list:
nums = [1, 2, 3, 4, 5] sum = 0 for num in nums: sum += num print("列表的和为:", sum)
Summary:
This article introduces the flow control statement in Python: if, else, elif, while and for. These statements can determine the execution flow of the program based on conditions, making the program more flexible and controllable. We demonstrate the usage of these statements through specific code examples, hoping to help readers have a deeper understanding.
The above is the detailed content of In-depth analysis of Python flow control statements: the use of if, else, elif, while, and for. For more information, please follow other related articles on the PHP Chinese website!