-
如果条件为真,执行语句1和2;否则(条件为假)执行语句3和4
if 条件:
语句1
语句2
else:
语句3
语句4
小知识:
if跟else段尾要加“:”,语句1、语句2、语句3和语句4要有同样的缩进(可以是4个空格);
条件可以是True和False,也可以是表达式如1<2、a=b、name=="alex" and pwd=="123"等等。
-
变形:如果条件1为真,执行语句1,结束;如果条件1为假,条件2为真,执行语句2,结束;如果条件1为假,条件2为假,条件3为真,执行语句3,结束;如果条件都为假,执行语句4.
if 条件1:
语句1
elif 条件2:
语句2
elif 条件3:
语句3
else:
语句4
例子:成绩在0-100分等级显示,90-100的为A;80-90的为B;60-80的为C;0-60的为D,其它成绩提示输入数值在0-100.
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 score=int(raw_input("Enter your score: ")) 4 if score>100: 5 print("Please enter the score between 0 and 100!") 6 elif score>=90: 7 print("Perfect!Your rating is level A!") 8 elif score>=70: 9 print("Wonderful!Your rating is level B!") 10 elif score>=60: 11 print("Great!Your rating is level C!") 12 elif score>=0: 13 print("Your rating is level D!But do not be discouraged!As long as you work hard,you will succeed.") 14 else: 15 print("Please enter the score between 0 and 100!")
-
嵌套使用:如果条件1为真,执行语句1,否则执行语句2;如果条件1、条件2都为真,执行语句3,否则执行语句4;如果条件都为真,执行语句5,否则执行语句6。
if 条件1:
语句1
if 条件2:
语句3
if 条件3:
语句5
else:
语句6
else:
语句4
else:
语句2
例子:用户名,密码,验证码来验证信息
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import getpass 4 name=raw_input("Enter your name: ") 5 if name=="me": 6 print("Your name is right: ") 7 pwd=getpass.getpass("Enter your password: ") 8 if pwd=="me123": 9 print("Your pwd is right: ") 10 captcha=raw_input("Enetr the captcha: ") 11 if captcha=="456": 12 print("The confirmation passes!") 13 else: 14 print("Check the captcha!") 15 else: 16 print("Your pwd is wrong: ") 17 else: 18 print("Your name is not nonexistent: ")