Skip to content
鼓励作者:欢迎打赏犒劳

python常用语法

变量

python
a = 100
b = 123.45
c = '123'
d = '100'
e = '123.45'
f = 'hello, world'
g = True
print(float(a))         # int类型的100转成float,输出100.0
print(int(b))           # float类型的123.45转成int,输出123
print(int(c))           # str类型的'123'转成int,输出123
print(int(c, base=16))  # str类型的'123'按十六进制转成int,输出291
print(int(d, base=2))   # str类型的'100'按二进制转成int,输出4
print(float(e))         # str类型的'123.45'转成float,输出123.45
print(bool(f))          # str类型的'hello, world'转成bool,输出True
print(int(g))           # bool类型的True转成int,输出1
print(chr(a))           # int类型的100转成str,输出'd'
print(ord('d'))         # str类型的'd'转成int,输出100

IF分支

python
height = float(input('身高(cm):'))
weight = float(input('体重(kg):'))
bmi = weight / (height / 100) ** 2
print(f'{bmi = :.1f}')
if bmi < 18.5:
    print('你的体重过轻!')
elif bmi < 24:
    print('你的身材很棒!')
elif bmi < 27:
    print('你的体重过重!')
elif bmi < 30:
    print('你已轻度肥胖!')
elif bmi < 35:
    print('你已中度肥胖!')
else:
    print('你已重度肥胖!')

循环语句

python
"""
从1到100的偶数求和
"""
total = 0
i = 2
while True:
    total += i
    i += 2
    if i > 100:
        break
print(total)

随机数

python
import random

red_balls = [i for i in range(1, 34)]
blue_balls = [i for i in range(1, 5)]
# 从红色球列表中随机抽出6个红色球(无放回抽样)
selected_balls = random.sample(red_balls, 6)
# 从蓝色球列表中随机抽出1个蓝色球(放回抽样)
blue_ball = random.choice(blue_balls)
# 多抽几个
blue_ball2 = random.choices(blue_balls,k=2)
print(selected_balls)
print(blue_ball)
print(blue_ball2)

字符串

python
xx = 'world'

s1 = f'hello {xx}'  # 占位符
s2 = r'\it \is \time \to \read \now' # 原样输出
s3 = """
    三十年河东,
    三十年河西。
"""
print(s1)
print(s2)
print(s3)


## 格式化输出
message_content ="""
律回春渐,新元肇启。
新岁甫至,福气东来。
{year}贺岁,欢乐祥瑞。
{year}敲门,五福临门。
{name}及家人拜年啦!
新春快乐,{name}年大吉!
""".format(year = "小米", name = "华为")
print(message_content)

格式化

python
print(format(3.14,'20')) #   数字默认右对齐  20是宽度
print(format('hello','20')) # 字符串默认左对齐
print(format('hello','*<20')) # <左对齐,大表示的填充符,20表示的是显示的宽度
print(format('hello','*>20')) # >右对齐
print(format('hello','*^20')) # ^居中对齐


#                 3.14
# hello               
# hello***************
# ***************hello
# *******hello********

如有转载或 CV 的请标注本站原文地址