第4天 增量赋值 链式赋值 交叉赋值 解压赋值 逻辑运算符 短路运算 布尔值分类 if判断 格式化输出

增量赋值

age = 10
age = age + 1
age + = 1
age % = 3   取余
age // = 3  取整数
age ** = 3三次方
print(age)

链式赋值

x = 10
y = x
z = y

x = y = z = 10
print(x, y, z)
print(id(x),id(y),id(z))

交叉赋值

m = 10
n = 20
temp=m
m=n
n=temp
m = n  # 将n的值赋值给m,m=20
#print(id(m),id(n),id(temp))
#print(id(m), id(n), id(temp))

m = 20
n = 10
m, n = n, m
print(m, n)
print(id(n), id(m))

解压赋值

适用于取两头的值,下划线的值代表不想要的值
ccc = [11, 22, 33, 44, 55, 66]
k1 = ccc[0]
k2 = ccc[1]
k3 = ccc[2]
k4 = ccc[3]
k5 = ccc[4]
k6 = ccc[5]
k1, k2, k3, k4, k5, k6 = ccc
print(ccc) = print(k1, k2, k3, k4, k5, k6)
k1, k2, *_ = ccc
*_, last2, last1 = ccc
print(last1)
_, *k1, _ = ccc 取中间的值
print(_)

逻辑运算符

not: 紧跟其后的那个条件取反
and:连接左右两个条件,两个条件同时位ture,结果才为ture
or:但凡有一个条件为ture,最终结果就为ture
优先级,not > and > or,()最优先。

短路运算

(偷懒原则)
print(1 and  0 or  2) 结果为2
print(1 and 0 or 0 and 3 or not  2) 结果为false
(1 and 2) or (0 and 3 )or not  2 结果为2
比较运算符和逻辑运算符,结果都是为了得到ture和false。目的是为了充当已知条件用。
x = True
print(x and not 10 < 3) 结果为ture

布尔值分为两大类

1.显式的布尔值,直接定义的ture和fales。比如10 > 3,x = ture。

2.隐式的布尔值,所有的数据类型的值都可以充当隐式布尔值。
其中包含0,none,空对应的布尔值为fales,其余对应的布尔值都为真。

流程控制之if判断
什么是if判断?

 判断 条件:
           做xx
     否则:
           做xx

为何要用if判断?
为了让计算机像人一样根据条件的判断结果取做不同的事情

如何用if判断?

完整语法:
print("start...)
if 条件1:
    代码1
    代码2
    代码3
elif :
    代码1
    代码2
    代码3
elif :
    代码1
    代码2
    代码3
··········
else:
    代码1
    代码2
    代码3
print("end...)
if判断先运行代码先运行顶级代码,再运行子代码。
if判断可以包含多段子代码块,但是只会执行一个子代码块。
单分支
print("start...")
if条件1:
    代码1
    代码2
    代码3
print("end...")

双分支
print("start...")
if条件1:
    代码1
    代码2
    代码3
 else:
    代码1
    代码2
    代码3
print("end...")

多分枝
print("start...")
if条件1:
    代码1
    代码2
    代码3
elif:
    代码1
    代码2
    代码3
elif:
    代码1
    代码2
    代码3
.....
print("end...")

双分支输入账号密码案例

print("start...")
inp_name = input("name")
inp_pwd = input("pwd")
db_name = "nana"
db_pwd = "456"

if inp_name ==db_name  and  inp_pwd== db_pwd:
    print("pass")
else:
    print("error...")
print("end...")

多分支成绩查询案例

score = 90
if score >= 90:
    print("good")
elif score >= 80:
    print("fine")
elif score >= 70:
    print("ordinary")
else:
    print("poor")

接收用户输入

执行input()命令后,输入的内容等于系统自动加了""
inp_name = input("name") = "xx"
执行int()命令后,将纯数字组成的字符串转成整形
案例
score = input("输入成绩")
score = int(score)  #将纯数字组成的字符串转成整形
if score >= 90:
    print("good")
elif score >= 80:
    print("fine")
elif score >= 70:
    print("ordinary")
else:
    print("poor")
python2的raw_input()等同于python3的input
input()输入的内容不会加“”。

格式化输出

linux系统换行符\n
Windows系统换行符\n,\r
print("1111",end="")
print("2222")

格式化输出
name = input("your name:")
age = input("your age:")
msg = "my name is" + name + "my age is" + age
msg = "my name is %s my age is %s" % ("nana", "18")
msg = "my name is %s my age is %s" % (name, age)        # %s 数字字符串都可以接手
msg = "my name is %s my age is %d" % ("nana", 18)       # %d 只能接收数字
print("my name is %s my age is %s" % (name, age))

猜你喜欢

转载自blog.csdn.net/Yosigo_/article/details/111387415