在Python中,条件循环语句通常使用`if`、`elif`和`else`关键字来实现。以下是条件循环语句的基本结构:
if condition1:当条件1成立时执行的代码块elif condition2:当条件2成立时执行的代码块else:如果以上条件均不成立,则执行这部分代码块
其中,`condition1`、`condition2`等可以是任何表达式,任何非零、或非空(null)的值均为`True`。
循环语句则分为`for`循环和`while`循环:
`for`循环用于遍历序列(如列表、元组、字典、集合)中的元素。
`while`循环会在给定条件为`True`时重复执行代码块,直到条件变为`False`。
下面是一些示例:

条件语句示例:
x = int(input("Please enter an integer: "))if x < 0:x = 0print("Negative changed to zero")elif x == 0:print("Zero")else:print("More")
循环语句示例:
遍历列表并打印每个元素及其长度List_a = ['cat', 'window', 'defenestrate']for x in List_a:print(x, len(x))
无限循环示例:
var = 1while var == 1:num = input("Please enter a number: ")print("You entered:", num)当输入的数字不是1时退出循环if num != '1':breakelse:print("This is an even number")
请注意,Python中的缩进非常重要,它用来表示代码块。另外,`continue`和`break`语句可以用来控制循环的执行流程。
