Python-分支和循环

    科技2026-02-20  5

    分支和循环

    小练习题目参考代码 条件表达式概念源代码三元操作符语法条件表达式改进代码 断言for循环语句range()语法 break语句用途例子 continue语句用途例子

    小练习

    题目

    按照 100 100 100分制, 90 90 90分以上成绩为 A A A 80 ∼ 90 80 \sim 90 8090 B B B 60 ∼ 80 60 \sim 80 6080 C C C 60 60 60以下为 D D D。现在要求写一个程序,当用户输入分数,自动转换为 A 、 B 、 C 、 D A、B、C、D ABCD的形式打印。

    参考代码

    score = int(input("please input your score:")) if score >= 90 and score <= 100: print("A") elif score >=80 and score < 90: print("B") elif score >=60 and score < 80: print("C") elif score >=0 and score < 60: print("D") else: print("Error!")

    条件表达式

    概念

    我们说“多少元”操作符的意思是这个操作符有多少个操作数,比如说“=”是个二元操作符,“+”是个一元操作符。

    源代码

    if x < y: small = x else: small = y

    三元操作符语法

    a = x if 条件 else y

    条件表达式改进代码

    small = x if x < y else y

    断言

    assert这个关键字成为“断言”,当这个关键字后面的条件为假的时候,程序自动崩溃并抛出AssertionError的异常。例如: 如果输入:assert 3 < 4,那么什么都不会发生 如果输入:assert 3 > 4,那么会抛出异常

    for循环语句

    Python的for循环语句特别智能,有种迭代器的感觉。例如:

    favorite = "FishC" for ch in favorite: print(ch,end='')

    输出FishC

    range()

    语法

    range([start,],stop[,step = 1]) 用中括号括起来的两个表示这两个参数是可选的。step = 1表示第三个参数的默认值是1。这个函数的作用是生成一个从start参数的值开始,到stop参数的值结束的数字序列。 只传递一个参数的range(),例如range(5),它会将第一个参数默认设置为0,生成[0,5)的所有数字。 例如:

    for i in range(5): print(i,end=' ') print() for i in range(2,9): print(i,end=' ') print() for i in range(1,10,2): print(i,end=' ')

    输出为

    0 1 2 3 4 2 3 4 5 6 7 8 1 3 5 7 9

    break语句

    用途

    break语句的作用是终止当前循环,跳出循环体

    例子

    bingo = "pbc is a handsome boy" answer = input("please input a sentence:") while(True): if answer == bingo: break amswer = input("You are wrong!please input a sentence again(when you are right,the game can be over!):") print("You are right!") print("Thank you very much!")

    continue语句

    用途

    终止本轮循环并进入下一轮循环

    例子

    for i in range(10): if i % 2 != 0: print(i,end=' ') continue i += 2 print(i,end=' ')

    输出:

    2 1 4 3 6 5 8 7 10 9

    这里for循环其实和C++不太一样,这里的循环就是i从0到9,每个都要进入一次。

    Processed: 0.013, SQL: 9