[Python] - 条件判断和循环语句

文章从简书转入,只因它已不再是以前的简书


image

Human life is ephemera, which makes it precious.
生命短暂,所以珍贵。


条件语句

Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码


if 语句

Python 中用 elif 代替了 else if,所以if语句的关键字为:if – elif – else

score = int(input("请输入你的分数: "))

if score < 60:
    print("you are fail")
elif score <= 80:
    print("you are well")
elif score < 100:
    print("you are so clever")
else:
    print("you are genius")

### 退出提示
input("点击 enter 键退出")

if 嵌套

if 语句 中包含 if 语句,成为 if 嵌套

格式:
if 表达式1:
    语句
    if 表达式2:
        语句
    elif 表达式3:
        语句
    else:
        语句
elif 表达式4:
    语句
else:
    语句
代码示例:
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")

循环语句

Python 中的循环语句有 for 和 while


while 循环
while 判断条件:
    语句

PS: 在Python中没有do..while循环

示例:用 while 来计算 1 到 100 的总和:
n = 100
sum = 0
counter = 1
while counter <= n:
    sum += counter
    counter += 1
print("1 到 %d 之和为: %d" % (n,sum)) # 1 到 100 之和为: 5050

无限循环

通过设置条件表达式永远不为 false 来实现无限循环

while True:
    num = int(input("输入一个数字  :"))
    print("你输入的数字是: ", num)

使用 CTRL+C 来退出当前的无限循环


while 循环使用 else 语句
count = 0
while count < 5:
   print (count, " 小于 5")
   count = count + 1
else:
   print (count, " 大于或等于 5")

for 语句

for循环可以遍历任何序列的项目,如一个列表或者一个字符串

格式:
for <variable> in <sequence>:
    <statements>
else:
    <statements>
代码示例:
names = ["Mazy", "Vivian", "Joy", "Eric"] 
for x in names:
    print(x) # Mazy、Vivian、Joy、Eric

range()函数

range()函数用来获取一个区间范围

使用 range() 函数来创建一个列表:
>>>list(range(5))
[0, 1, 2, 3, 4]
range(5) # 等效于 [0,1,2,3,4]
使用range指定区间的值
range(5,9) # 等效于 [5,6,7,8]
range() 当以指定数字开始并指定不同的增量(甚至可以是负数,有时这也叫做“步长”):
range(0, 10, 3) # 等效于 [0,3,6,9]

breakcontinue 语句及循环中的else子句

  • break 语句可以跳出 forwhile 的循环体

  • continue 语句被用来告诉Python跳过当前循环块中的剩余语句,然后继续进行下一轮循环

break示例:
for i in range(8):
    if i == 6:
        break
    print("当前数字为:",i)

输入结果为:到 数字 6 结束循环

当前数字为: 0
当前数字为: 1
当前数字为: 2
当前数字为: 3
当前数字为: 4
当前数字为: 5
continue示例:
for i in range(8):
    if i == 6:
        continue
    print("当前数字为:",i)

输入结果为:到 数字 6 跳出当前循环,继续下一个循环

当前数字为: 0
当前数字为: 1
当前数字为: 2
当前数字为: 3
当前数字为: 4
当前数字为: 5
当前数字为: 7

pass 语句

pass是空语句,是为了保持程序结构的完整性, 一般用做占位语句

示例:
class EmptyClass:
    pass # 不做任何处理

三元运算

result = 值1 if 条件 else 值2

如果条件为真:result = 值1

如果条件为假:result = 值2

示例:
score = int(input("请输入你的分数: "))
r = "及格" if score >= 60 else "不及格"
print(r) # 当输入的数字小于 60 时 r值为 "不及格"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值