if语句
一般形式如下所示:
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
- 如果 “condition_1” 为 True 将执行 “statement_block_1” 块语句
- 如果 “condition_1” 为False,将判断 “condition_2”
- 如果"condition_2" 为 True 将执行 “statement_block_2” 块语句
- 如果 “condition_2” 为False,将执行"statement_block_3"块语句
在Python中没有switch – case语句。
密码登录
import getpass
_username = 'sun'
_password = 'abc123'
username = input("username:")
password = getpass.getpass("password:")
# password = input("password:")
if _username == username and _password == password:
print("Welcome user {name} login...".format(name=username))
else:
print("Invalid username or password!")
import sys
age = int(input("请输入你家狗狗的年龄: "))
if age < 0:
print("你是在逗我吧!")
elif age == 1:
print("相当于 14 岁的人。")
elif age == 2:
print("相当于 22 岁的人。")
elif age > 2:
human = 22 + (age -2)*5
print("对应人类年龄: ", human)
input("点击任意键退出")
sys.exit(1)
if 嵌套
num=int(input("输入一个数字:"))
if num%2==0:
if num%3==0:
print ("你输入的数字可以整除 2 和 3")
else:
print ("你输入的数字可以整除 2,但不能整除 3")
else:
if num%3==0:
print ("你输入的数字可以整除 3,但不能整除 2")
else:
print ("你输入的数字不能整除 2 和 3")
输入一个数字:3
你输入的数字可以整除 3,但不能整除 2
三元操作
y = 8
x = 10 if y == 9 else 20
print(x)
20
计算最小值
def small(a,b,c):
return a if a <= b and a <= c else(b if b <= a and b <= c else c)
print(small(2,4,1))
print(small(2,2,3))
1
2
在列表推导式使用三元运算
alist = [ i**2 if i < 3 else i**4 for i in range(5) ]
print(alist)
[0, 1, 4, 81, 256]