一、条件语句
1.条件语句:通过一条或多条语句的执行结果(True或False)来决定执行额代码块。python程序语言指定任何非0或非空(null)的值为true,0或null为false。
2. if 语句
if 判断条件:
执行语句
else:
执行语句
例子如下:
#! /usr/bin/env python username = 'crystal'
password = '1234'
Username = input("username:")
Password = input("password:") if username == Username and password==Password:
print("Welcome user {name} login...".format(name=Username))
else:
print("Invalid username or password")
python不只是switch语句,如果需要做多个条件判断,只能用elif来实现。以下实例中用到 or 和 and 两个运算符
#! /usr/bin/env python num = 9
if num >=0 and num <=10: #判断值是否在0-10之间
print ("hello") #输出结果hello num = 10
if num <0 or num >10: #判断值是否在小于0或大于10的区间里
print ("hello")
else:
print ("undefine") #输出结果:undefine num = 8
#判断是否在0~5或者10~15之间
if (num >=0 and num <=5) or (num >=10 and num <=15):
print ("hello")
else:
print ("undefine")
备注:部分内容来自菜鸟课程:https://www.runoob.com/python/