一.if判断
- 如果 条件满足,才能做某件事情,
- 如果 条件不满足,就做另外一件事情,或者什么也不做
注意:
- 代码的缩进为一个
tab
键,或者 4 个空格 - 在 Python 开发中,Tab 和空格不要混用!
1.判断逻辑图
2.if 语句的判断条件可以用>(大于)、<(小于)、==(等于)、>=(大于等于)、<=(小于等于)、!=(不等于)来表示其关系。
if 条件 and 条件: 满足条件后执行的代码块 else: 否则(不满足条件)执行的代码块
- if语句用于比较运算
#示例1 a = 0 if a > 0: print "a is not 0" else: print 'a is o' #示例2 a = raw_input("--->") if int(a) > 10: print "a > 10" else: print "a <= 10" #示例3 name = "XFS" if name == "xfs": print "True" else: print "False" #示例4 lis = [1,2,3] lis1 = [1,2,3] if lis == lis1: print "True" else: print "False"
- if语句用于比较运算中结合逻辑运算符
#示例1 a = 50 if a< 100 and a > 10: print "a is not 0" else: print 'a is false' #示例2 name = "zhangsanaa" if len(name) < 10 or len(name) == 10: print "ok" else: print "no" #示例3 phone = raw_input("请输入手机号:") if len(phone) == 11 and phone.startswith('1') and phone.isdigit(): print "手机号正确" else: print "手机号不正确"
- and的优先级大于or,有括号的运算最优先(
在不加括号时候,
and
优先级大于
or
)#示例1 a = 15 if a > 0 and a < 10 or a < 20: print "ok" else: print "no" # 示例2 a = 16 if a < 15 and (a > 10 or a > 20): print "ok" else: print "no"
- if语句结合成员关系运算符
list1 = ["a","b","c"] if "a" in list1: print "a in list1" else: print "a not in list1"
name = 'xiaoming' if 'xm' not in name: print 'xm is in name' else: print 'xm is not in name'
- if嵌套
#伪代码如下 if 今天发工资: 先还信用卡的钱 if 有剩余: 又可以happy了,O(∩_∩)O哈哈~ else: 噢,no。。。还的等30天 else: 盼着发工资
name = 'hello xiao mi' if 'hello' in name: if 'xiao' in name: if ' mi' in name: print name else: print '输入有误,重新输入' else: print '游戏结束---->' phone = raw_input('请输入手机号:') if phone.isdigit() == True: if phone.startswith('1'): if len(phone)==11: pass else: print '手机号必现为11位数' else: print '手机号必现以1开头' else: print '手机号必现为纯数字'
mysql = {"zhangsan":"123456","lisi":"234567","wangwu":"345678"} user = raw_input("账号:") pwd = raw_input("密码:") if user in mysql.keys(): if pwd == mysql.get(user): print "登录成功!" else: print "密码错误!" else: print "账号错误!"
- 占位符pass
a = 0 if a != 0: print "ok" else: pass
3.当判断条件为多个值时,可以使用以下形式。
- if语句执行有个特点,它是从上往下匹配,如果在某个判断上是True,把该判断对应的语句执行后,就忽略掉剩下的elif和else
if 判断条件 1: 执行语句 1…… elif 判断条件 2: 执行语句 2…… elif 判断条件 3: 执行语句 3…… else: 执行语句 4……
示例:
username = raw_input('请输入用户名:') pwd = raw_input('请输入密码:') if username == 'zhangsan' and pwd == '123456': print '登录成功' elif username != 'zhangsan' and pwd == '123456': print '用户名错误' elif username == 'zhangsan' and pwd != '123456': print '密码错误' else: print '用户名不能为空' """ 如果输入的年纪小于我的年纪 然后告诉你,输入的年纪太小 或者输入的年纪大于我的年纪 然后告诉你,输入的年纪太大 否则 告诉你,答对了 """ #猜年纪游戏 myage = 26 input_age = raw_input("--->") if int(input_age) < myage: print "too smaller!" elif int(input_age) > myage: print "too bigger!" else: print "you got it!" """ #成绩评级 score = int(input("Please input your score:")) if score > 90: print("A") elif score > 70: print("B") elif score > 60: print("C") else: print("滚!") """