if语句用于对条件进行判断。主要结构形式有如下三种:
这三种结构的使用方法如下实例所示:
month = 8
if month < 1 or month > 12:
print("Invalid number.")
if month < 3 or month == 12:
print("This is winter.")
elif month >= 3 and month < 6:
print("This is spring.")
elif month >= 6 and month < 9:
print("This is summer.")
else:
print("This is autumn.")
上述代码的运行结果如下:
This is summer.
while语句主要用于循环执行某项操作,while循环会一直运行,直到指定的条件不满足为止,使用方法如下实例所示:
num = 0
while num <= 5:
print("Current num is: " + str(num))
num += 1
上述代码的运行结果如下:
Current num is: 1
Current num is: 2
Current num is: 3
Current num is: 4
Current num is: 5
使用break语句可以直接退出循环,具体使用方法如下实例所示:
num = 0
while True:
print("Current num is: " + str(num))
num += 1
if num > 5:
break
print("Break from while loop")
上述代码的运行结果如下:
Current num is: 0
Current num is: 1
Current num is: 2
Current num is: 3
Current num is: 4
Current num is: 5
Break from while loop
使用continue语句跳出本次循环,继续执行后续循环,具体使用方法如下实例所示:
num = 0
while True:
num += 1
if num == 2:
continue
print("Current num is: " + str(num))
if num > 5:
break
print("Break from while loop")
上述代码的运行结果如下:
Current num is: 1
Current num is: 3
Current num is: 4
Current num is: 5
Current num is: 6
Break from while loop
for循环语句用于循环执行某项操作,具体使用方法如下实例所示:
for num in range(1,5):
print("Current num is: " + str(num))
上述代码的运行结果如下:
Current num is: 1
Current num is: 2
Current num is: 3
Current num is: 4