python基础002

python基础002,第1张

一.格式化方法
  1. 占位符
    语法:%[-w.p]type
    -,表示左对齐,默认右对齐
    w,表示宽度
    p,表示精度
    type,表示类型,d:整型 f:浮点型 s:字符串类型
# 代码
name = input("name:")
score = input("score:")
name_1 = input("name_1:")
score_1 = input("score_1:")
avg_score = (float(score) + float(score_1)) / 2

# 占位符的使用
print("姓名\t\t成绩")  # \t, 横向制表符
print('%-30s\t%3s\n%3s\t%3s\n平均成绩\t%8.2f\n' % (name, score, name_1, score_1, avg_score))

# 输入输出
name:xiaoxingxing
score:100
name_1:daxingxing
score_1:10
姓名		成绩
xiaoxingxing                  	100
daxingxing	 10
平均成绩	   55.00
  1. format
    语法:‘’{[:w.p]}‘.format(var)’ 此方法可以不用关注数据类型
# 代码
name = input("name:")
score = input("score:")
name_1 = input("name_1:")
score_1 = input("score_1:")
avg_score = (float(score) + float(score_1)) / 2

# format使用
print("{:70}\t{}\n{}\t{}\n平均成绩\t{:8.2f}\n".format(name, score, name_1, score_1, avg_score))

# 输入输出
name:daxingxing
score:100
name_1:xiaoxingxing 
score_1:10
daxingxing                                                            	100
xiaoxingxing 	10
平均成绩	   55.00
  1. f-string
    语法:f’{var[:w.p]}’
name = input("name:")
score = input("score:")
name_1 = input("name_1:")
score_1 = input("score_1:")
avg_score = (float(score) + float(score_1)) / 2

# f-string 用法
print(f'{name:7}\t{score}\n{name_1}\t{score_1}\n平均成绩\t{avg_score:10.2f}\n')

# 输入输出
name:daxingxing
score:100
name_1:xiaoxingxing
score_1:10
daxingxing	100
xiaoxingxing	10
平均成绩	     55.00
二.运算符 1.算术运算符

加,减,乘,除,取余,取模,幂运算 ……

print(1 * 2)
print("a" * 5)
print("a" + "b")
print(3 / 2)  # 商
print(5 // -2)
print(3 // 2)  # 整除 取模 向下取整
print(3 % 2)  # 取余
print(5 % -2)
print(2 ** 3)  # 幂运算
print(10 ** -2)
print(5 % -2)  # 求余公式 : r = a%b = a-b*(a//b)
print(-5 % 2)

# 输出结果
2
aaaaa
ab
1.5
-3
1
1
-1
8
0.01
-1
1
2.赋值运算符

= += -= *= /= //= %= **=

m, n = 10, 3
p = m
m += n
print(m)
p *= n
print(p)
p **= n
print(p)
m %= n
print(m)

# 输出
13
30
27000
1
3.比较运算符

= < <= == !=

a, b = 30, 20
c, d = '2021-3-9', "2020-3-9"
print(a == b)
print(a > b)
print(a < b)
print("a" <= "b")
print("a" != "b")
print(a >= b)
print(c == d)
print(c > d)
print(c < d)
print(c <= d)
print(c != d)
print(c >= d)

# 输出
False
True
False
True
True
True
False
True
False
False
True
True
4.逻辑运算符

and or not

a, b, c = 1, 1 ,0
print(a and b)
print(a and b and c)
print(a or b or c)
print(not a or c)

# 输出
1
0
1
0

5.优先级

算术运算符 > 移位运算符 > 位运算符 > 关系运算符 > 逻辑运算符(not > and > or) > 赋值运算符

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/884262.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-14
下一篇 2022-05-14

发表评论

登录后才能评论

评论列表(0条)

保存