条件
if语句
绝对值
def abs2(n):
if n<0:
n=-n
return n
if-else 语句
x=input("x")
x=float(x)
print("hello")
if x<10:
print("wa")
else:
print("ro")
print("goodbye")
x=10
hello
ro
goodbye
重新设计abs
def abs(n):
if n>0:
sign=+1
else:
sign=-1
return sign*n
if-elif-else
可以用多个elif
def getgrade(score):
if score>=90:
grade="A"
elif score>=80:
grade="B"
elif score>=70:
grade="C"
elif score>=60:
grade="D"
else:
grade="F"
if-else推导式
def abs(n):
return n if (n>=0) else -n
def abss(n):
if n>=0:
return n
else:
return -n
print("abs(5)=",abs(5),"and abs(-5)=",abs(-5))
abs(5)=5 and abs(-5)=5
match-case语句
def http_error(ststus):
match status:
case 400:
return "bad request"
case 404:
return "not found"
case 418:
return "i an a teapot"
case _:
return "something is wrong"
练习
def is_graduate(cet4,cet6):
if cet4>=425:
if cet6>=425:
return "yes"
else:
return "no"
else:
return "no"
cet4,cet6=input().split()
cet4=float(cet4)
cet6=float(cet6)
print(is_graduate(cet4,cet6))
改进
def is_graduate(cet4,cet6):
if cet4>=425 and cet6>=425
return "yes"
else:
return "no"
cet4,cet6=input().split()
cet4=float(cet4)
cet6=float(cet6)
print(is_graduate(cet4,cet6))
进阶
def is_graduate(cet4,cet6):
if cet4>=425 and cet6>=425
return "yes"
else:
return "no"
cet=input()
if " " in cet:
cet4,cet6=input().split()
cet4=float(cet4)
cet6=float(cet6)
else:
cet4=float(cet)
cet6=None
print(is_graduate(cet4,cet6))
清晰的代码风格
else部分
b=True
if b:
print("yes")
else:
print("no")
空白if部分
b=False
if not b:
print("no")
用嵌套if 而非and 判断
b1=True
b2=True
if b1 and b2:
print("both")
用if 而不是else控制
b=True
if b:
print("yes")
else:
print("no")
x=10
if x<5:
print("s")
elif x<10:
print("m")
elif x<15:
print("l")
else:
print("e")
c="a"
if(c>='A') and (c<='z'):
print('u')
elif(c>='a') and (c<='z'):
print('l')
else:
print('n')
使用trick
x=42
if x>0:
y=99
标签:cet4,cet6,return,else,abs,条件,print
From: https://www.cnblogs.com/aijingyn/p/17866148.html