1. Pycharm2017.2.4编写工具安装
在介绍python的逻辑判断之前,先让我们安装一个python编程工具。方便以后我们更好的练习python。
图片1.png
图片2.png
图片3.png
图片4.png
调整字体大小
图片5.png
2. 条件判断
2.1. if 判断语句
2.1.1. 语法
if 条件:
【条件就是一个bool表达式 得到的结果要么是真,反之就是假】
代码块 【只有当条件为真的时候 代码 才会被执行】
2.1.2. if 和 比较运算符使用
案例: 判断是否是成年人
age = int(input()) 接受外界传递过来的值 ,并将String的值转换成int值
if age>=18:
print(“已经成年”) #缩进四个空格
print(“程序结束”)#不管满不满足条件都是要执行的
2.1.3. if 和 逻辑运算符使用
- or 或者
hasHouse or hasCart
案例: 有房子(house)或者有车(cart),两者有一样生活还不错
满足一个条件即可
if hasHouse == "Y" or hasCart == "Y":
print("生活还不错")
- and 并且
hasHouse and hasCart
案例: 是不是钻石王老五,两个条件都必须满足
if hasHouse == "Y" and hasCart == "Y":
print("生活还不错")
-
not 取非
案例:数字范围不再0和100之间
if not(num>0 and num<100):
print("您输入的数字是:%d"%num)
print("程序结束")
案例:判断数字在0-100范围内
num = int(input("请输入一个数字:\n"))
if num>0 and num<100:
print("您输入的数字是:%d"%num)
print("程序结束")
实例2:判断数字在0-100范围内
a = 30
if not (a<0 or a>100):
print("在0到100之间....")
2.2. if else判断
判断的结果最终只会有两个 :要不然是正确的。要不然是错误。
高富帅案例三个条件: height money handsome
语法:
if 条件:
print(满足条件展示信息)
else:
print(否则展示该信息)
print(程序结束)
案例l;
if height == "Y" and money == "Y" and handsome == "Y" :
print("三个条件都满足!优秀!")
else:
print("还需要再加油啊!")
print(程序结束)
2.3. if elif else 判断 (连续判断)
案例:年龄段评选
语法:
if 条件1:
print()
elif 条件2:
print()
elif 条件3:
print()
else: #以上条件都不满足的时候会执行
print()
print()#程序结束
示例:
age = int(input("请输入您的年龄:\n"))
if age>=1 and age <=10 :
print("儿童")
elif age>=11 and age <=20 :
#elif 后的条件都是 连续判断的条件 当轻重一个连续判断的条件满足要求
#那么剩余的其他条件就不会在执行
print("青少年")
elif age>=21 and age <=30 :
print("青年")
elif age>=31 and age <=50 :
print("中年")
elif age>=51 and age <=70 :
print("中老年")
elif age>=71 and age <=80 :
print("老年")
elif age>=81:
print("暮年")
else:
#以上所有的条件都不满足的时候会执行的代码
print("你输入的年龄不正确")
2.4. if嵌套
案例: 上公交车,并且有座位坐下
要求:输入公交卡当前的金额(money),只要超过2元,就可以坐公交车,如果空座位(seatCount)的数量>0,就可以坐下。
money= int(input("输入公交卡当前的金额:\n"))
if money > 2:
print("请上车")
#如果空座位(seatCount)的数量>0,就可以坐下。
seatCount = int(input("请输入车上的空座位数:\n"))
if seatCount > 0:
print("可以坐下")
else:
print("站着吧!")
else:
print("卡中余额不足,请充值")
今天先记这么多,明天继续!