python之海象运算符

简介

海象运算符是一种语法糖,有一个:和一个=构成,语法格式如下:

(variable_name := expression)

一般海象运算符有三种用法,如下

if else

if else 中还是比较常用的

# if 语句中
a = 10
if a > 5 :
    print("hello")

if a:=10 > 5:
    print("hello :=")

打印

hello
hello :=

他会先进行赋值,然后再进行比较

while

一般使用while我们会进行无限次的循环,或者循环某个次数之后就停止

n = 3 # 循环三次
while n:
    print(n)
    n -= 1
# 使用海象运算符
while (n := n-1) + 1:
    print(n)

打印

2
1
0

观察上面的表达式,因为海象运算符会先进行赋值运算,所以我们要先加个1才行

文件读取

fp = open("hello.txt", "r")
while True:
    line = fp.readline()
    if not line:
        break
    print(line.strip())

while line := fp.readline():
    print(line)

fp.close()

你可能感兴趣的:(python,python)