Python中的条件分支结构

分支结构概念:用于描述“如果满足什么条件,就怎么样,否则就怎么样”的语法。

在分支结构中,条件的结果必须为布尔值,条件结果为True,则执行响应条件下的代码块,否则程序向下运行。

分支结构语法格式:

一、单分支结构:
if 条件:
	条件成立执行的代码
#单分支结构示例
print("程序开始")
num = int(input("请输入一个整数:"))
if num >=0:
    print("该整数为正数。")
print("程序结束")
二、双分支结构
if 条件:
	条件成立执行的代码
else:
	条件不成立执行的代码
# 双分支结构 判断一个数字是不是偶数
x = int(input("请输入一个整数:"))
if x % 2 == 0 :
    print("这是个双数")
else:
    print("这是个单数")
三、多分支结构
if 条件1:
	条件1成立执行的代码
elif 条件2:
	条件2成立执行的代码
elif 条件3:
	条件3成立执行的代码
else:
	以上条件都不成立执行的代码
# 多分支结构示例
score = int(input("请输入你的成绩:"))
if score == 100:
    print("三亚7日游,爽歪歪!")
elif score >= 95 and score < 100:
    print("买个新手机,打王者很顺畅~")
elif score >= 90 and score < 95:
    print("看个电影犒劳下自己")
elif score >= 80 and score < 90:
    print("没事,再接再厉")
else:
    print("拖出去打一顿")
print("结束")
四、嵌套结构
if 条件1:
	#条件1为True时进入
	if 条件3:
		#条件3为True时进入
		代码块3...
	else:
		#条件3为False时进入
		代码块4...
else:
	#条件1为False时进入
	代码块2...
# 嵌套结构示例
x = int(input("请输入一个整数:"))
if x >= 0 :
    if x % 2 == 0:
        print("这个数字是偶数")
    else:
        print("这个数字是奇数")
else:
    print("这个数字是负数")

猜你喜欢

转载自blog.csdn.net/qq_29163727/article/details/108470133