Python Day4

if 语句(statement)

Conditionals Make Decisions

def f(x):
    print("A", end="")
    if x == 0:
        print("B", end="")
        print("C", end="")
    print("D")
f(1)
#结果为 AD

一个更有意思的例子:

任务:实现一个函数,返回输入数字的绝对值

Python 内置了一个函数叫 abs() 用于绝对值计算,所以我们将函数命名成 abs1abs2……

def abs1(n):
    if n < 0:
        n = -n
    return n
​
print("abs1(5) =", abs1(5), "and abs1(-5) =", abs1(-5))
print("abs2(5) =", abs2(5), "and abs2(-5) =", abs2(-5))
print("abs3(5) =", abs3(5), "and abs3(-5) =", abs3(-5))
print("abs4(5) =", abs4(5), "and abs4(-5) =", abs4(-5))
​
"""
结果为
abs1(5) = 5 and abs1(-5) = 5
abs2(5) = 5 and abs2(-5) = 5
abs3(5) = 5 and abs3(-5) = 5
abs4(5) = 5 and abs4(-5) = 5
"""

if-else 语句(statement)

x = input("x=")
x = float(x)
print("hello")
if x < 10:
    print("wahoo!")
print("goodbye")
​
f(0)
f(1)
f(2)
​
"""
结果为
ABCG
ADEG
ADFG
"""

重新设计 abs()

def abs5(n):
    if n >= 0:
        return n
    else:
        return -n
    
def abs6(n):
    if n >= 0:
        sign = +1
    else:
        sign = -1
    return sign * n
​
print("abs5(5) =", abs5(5), "and abs5(-5) =", abs5(-5))
​
print("abs6(5) =", abs6(5), "and abs6(-5) =", abs6(-5))
"""
结果为:
abs5(5) = 5 and abs5(-5) = 5
abs6(5) = 5 and abs6(-5) = 5
"""

if-elif-else 语句

def f(x):
    print("A", end="")
    if x == 0:
        print("B", end="")
        print("C", end="")
    elif x == 1:
        print("D", end="")
    else:
        print("E", end="")
        if x == 2:
            print("F", end="")
        else:
            print("G", end="")
    print("H")
    
"""
结果为:
ABCH
ADH
AEFH
AEGH
"""

另一个更有意思的例子:

任务:实现一个函数,输入一元二次函数的各项系数,返回其解的个数。

提示:一元二次方程 ax2+bx+c=0 (a≠0)��2+��+�=0 (�≠0) 的根与根的判别式 有如下关系:

Δ=b2−4acΔ=�2−4��

  • 当 Δ>0Δ>0 时,方程有两个不相等的实数根;

  • 当 Δ=0Δ=0 时,方程有两个相等的实数根;

  • 当 Δ<0Δ<0 时,方程无实数根。

def numberOfRoots(a, b, c):
    # 返回 y 的实数根(零点)数量: y = a*x**2 + b*x + c
    d = b**2 - 4*a*c
    if d > 0:
        return 2
    elif d == 0:
        return 1
    else:
        return 0
​
print("y = 4*x**2 + 5*x + 1 has", numberOfRoots(4,5,1), "root(s).")
print("y = 4*x**2 + 4*x + 1 has", numberOfRoots(4,4,1), "root(s).")
print("y = 4*x**2 + 3*x + 1 has", numberOfRoots(4,3,1), "root(s).")
​
"""
结果为
y = 4*x**2 + 5*x + 1 has 2 root(s).
y = 4*x**2 + 4*x + 1 has 1 root(s).
y = 4*x**2 + 3*x + 1 has 0 root(s).
"""

再来一个例子:

实现传说中的“学生分数登记管理系统”

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"
    return grade
​
print("103 -->", getGrade(103))
print(" 88 -->", getGrade(88))
print(" 70 -->", getGrade(70))
print(" 61 -->", getGrade(61))
print(" 22 -->", getGrade(22))
​
"""
结果为:
103 --> A
 88 --> B
 70 --> C
 61 --> D
 22 --> F
"""

if-else 推导式(expression)

def abs7(n):
    return n if (n >= 0) else -n
​
print("abs7(5) =", abs7(5), "and abs7(-5) =", abs7(-5))
"""
结果为:
abs7(5) = 5 and abs7(-5) = 5
"""

match-case 语句

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something's wrong with the internet"
​
mystatus=400
​
print(http_error(400))
​
#结果为:Bad request

一个 case 也可以设置多个匹配条件,条件使用 隔开,例如:

...
    case 401|403|404:
        return "Not allowed"

随堂练习

背景:小 ϵ 是一名大四学生,他的学校毕业要求是通过大学英语六级考试,你能写个程序看看他能不能毕业嘛?

输入格式:1-2 个整数,以空格分隔,第一个数字代表 CET 4 成绩,第二个数字代表 CET 6 成绩,如果四级未通过则没有六级成绩。

输出格式:1 个字符串,Yes 代表能够毕业,No 代表不能毕业。

输入示例:

500 430

输出示例:

Yes

def IsGraduate(cet4,cet6):
    if cet4 >= 425 and cet6 >= 425:
        return "Yes"
    else:
        return "NO"
    
cet = input.split()
# "500 430"
# "500"
if " " in cet :
    cet4,cet6 = input.split()
    cet4 = float(cet4)
    cet6 = float(cet6)
else :
    cet4 = float(cet)
    cet6 = None

print(IsGraduate(cet4,cet6))

清晰的代码风格 Clarity and style

# 又混乱又有产生 bug 的风险:
c = 'a'
if (c >= 'A') and (c <= 'Z'):
    print('Uppercase!')
if (c >= 'a') and (c <= 'z'):
    print('lowercase!')
if (c < 'A') or ((c > 'Z') and (c < 'a')) or (c > 'z'):
    print ('not a letter!')
    
#结果为:lowercase!   
​
# 更好的做法:
c = 'a'
if (c >= 'A') and (c <= 'Z'):
    print('Uppercase!')
elif (c >= 'a') and (c <= 'z'):
    print('lowercase!')
else:
    print('not a letter!')

使用一些 trick(如用算数逻辑来代替布尔逻辑)

# 不清晰的:
x = 42
y = ((x > 0) and 99)
​
# 清晰的:
x = 42
if x > 0:
    y = 99

总结

  • Conditionals Make Decisions.

  • if-else 结构构成了 Python 分支控制,if 还能嵌套使用。

  • 合理的编写风格会让代码更易读,还能尽可能避免引入 bug。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值