文章目录
1、程序的组织结构
2、顺序结构
print('---------程序开始---------')
print('1.打开冰箱门')
print('2.把大象放进去')
print('3.关冰箱门')
print('---------程序结束---------')
3、对象的布尔值
# 测试对象的bool值,一下对象的 bool 值都是 False
print(bool(False))
print(bool(0))
print(bool(0.0))
print(bool(None))
print(bool(''))
print(bool([])) # 空列表
print(bool(list()))# 空列表
print(bool(()))# 空元组
print(bool(tuple()))# 空元组
print(bool({}))# 空字典
print(bool(dict()))# 空字典
print(bool(set()))# 空集合
4、分支结构
4.1、单分支 if 结构
money = 1000 # 余额
s = int(input("输入取款金额"))
# 判断余额是否充足
if money >= s:
money -= s
print('取款成功,余额为:',money)
4.2、双分支 if…else 结构
# 判断奇数还是偶数
num = int(input('输入一个整数'))
if num%2 == 0:
print('偶数')
else:
print('奇数')
4.3、多分支结构
值得注意的是,在 Python 中,可以写数学中的不等式,比如 0 <= score <60 ,这样写等价于 score >= 0 and score <60。但是在 Python 中是没有 与 && 这种运算符的。
# 输入一个成绩,判断成绩的等级
'''
90-100 A
80-89 B
70-79 C
60-69 D
0-59 E
<0 >100 无效
'''
score = int(input('输入成绩'))
if score >= 90 and score <= 100:
print('A')
elif score >= 80 and score < 90:
print('B')
elif score >= 70 and score < 80:
print('C')
elif score >= 60 and score < 70:
print('D')
elif 0 <= score < 60: # 在 Python 语言中可以这样写
print('E')
else:
print('分数无效!')
4.4、if 语句嵌套
# if 语句的嵌套
'''
会员,> 200 八折
<200 9折
非会员>200 九折
<200 95折
'''
answer = input('你是会员吗?y/n')
money = int(input('请输入金额: '))
if answer == 'y':
print("有会员卡!")
if money >= 200:
print('money = ',money*0.8)
else :
print('money = ',money*0.9)
else :
print("没会员卡!")
if money >= 200:
print('money = ',money*0.95)
else:
print('money = ',money)
4.5、条件表达式
其实这个条件表达式与其他语言的三目运算符是类似的。
# 从键盘录入2个数,比较大小
a = int(input('输入一个整数a'))
b = int(input('输入另一个整数b'))
# 一般if else
print('======一般的if else======')
if a >= b:
print('a big or equal to b.')
else:
print('a smell to b.')
# 使用条件表达式简写,类似于三目运算符 :
print('======简写if else 1======')
print('a big or equal to b.') if a >= b else print('a smell to b.')
print('======简写if else 2======')
print('a big or equal to b.' if a >= b else 'a smell to b.')
5、pass 空间语句
程序:
# pass 只是一个占位符,用在需要写但是还不会写语句的地方
answer = input('您是会员吗?y/n')
if answer == 'y':
print('是会员')
pass
print('pass .')
else:
print('不是会员')
pass
print('pass .')
输出:
您是会员吗?y/nn
不是会员
pass .