基础语法

包含:输入输出、字符串、编码、list、tuple、条件判断、模式匹配、for循环、while循环、dict、set等
输出结果都写在了注释中

# 你好世界
print('hello,world')
# hello,world


# 逗号表示空格
print('The quick brown fox','jumps over','the lazy dog')
# The quick brown fox jumps over the lazy dog


# 运算
print(100+200)
# 300
print(1024*768)
# 786432


# input()函数:
# 用于字符串输入
name = input()


# 转义字符
# 比如\n表示换行,\t表示制表符,字符\本身也要转义,所以\\表示的字符就是\
print('I\'m \"OK\"')
# I'm "OK"


# r''表示''内部的字符串默认不转义
print(r'\\\t\\')
# \\\t\\


# 返回布尔值
print(3>2)
# True


# and运算和not运算
print(True and False)
# False
print(True or False)
# True


# 默认输出浮点数
print(10/3,9/3,10//3,10%3)
# 3.3333333333333335 3.0 3 1


# ord()和chr()函数:
# ASCII和string的转换
a = ord('A')
b = ord('中')
c = chr(65)
d = chr(25991)
print(a,b,c,d)
# 65 20013 A 文


# len()函数:
# 实际长度
num = len('ABC')
print(num)
# 3


print('%5d-%05d' %(3,1))
#     3-00001
print('%.5f' %(3.141592653))
# 3.14159


s1 = 72
s2 = 85
r = ((85-72)/72)*100
print('%.1f%%' %(r))
# 18.1%


#list 列表
classmate = ['Michael','Bob','Tracy']
# append()函数:
# 末尾插入元素
classmate.append('Adem')
# insert()函数:
# 指定下标插入元素
classmate.insert(1,'Jack')
# pop()函数:
# 指定下标删除元素
classmate.pop(2)
print(classmate)
# ['Michael', 'Jack', 'Tracy', 'Adem']

# list里面的元素的数据类型也可以不同,也可以嵌套
l = ['Apple',123,True]
print(l)
# ['Apple', 123, True]


# tuple 元组
# tuple和list非常类似,但是tuple一旦初始化就不能修改
# 只有1个元素的tuple定义时必须加一个逗号,,来消除歧义
classmate = ('Michael','Bob','Tracy')

L = [
    ['Apple', 'Google', 'Microsoft'],
    ['Java', 'Python', 'Ruby', 'PHP'],
    ['Adam', 'Bart', 'Bob']
]
print(L[0][0],L[1][1],L[2][2])
# Apple Python Bob


# 条件判断
age = input()
age = int(age)
if age >= 18:
    print('Adult')
elif age >= 6:
    print('Teenager')
else:
    print('Kid')


# 模式匹配
score = input()
score = int(score)
match score:
    case 'A':
        print('score is A.')
    case 'B':
        print('score is B.')
    case 'C':
        print('score is C.')
    case _: # _表示匹配到其他任何情况
        print('score is %d.' %(score))

match age:
    case x if x<10:
        print('<10 years old:%d' %(age))
    case 10:
        print('10 years old')
    case 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18:
        print('11~18 years old')
    case 19:
        print('19 years old')
    case _:
        print('not sure')

args = ['gcc', 'hello.c', 'world.c']
# args = ['clean']
# args = ['gcc']

match args:
    # 如果仅出现gcc,报错:
    case ['gcc']:
        print('gcc: missing source file(s).')
    # 出现gcc,且至少指定了一个文件:
    case ['gcc', file1, *files]:
        print('gcc compile: ' + file1  + ',' + ','.join(files))
    # 仅出现clean:
    case ['clean']:
        print('clean')
    case _:
        print('invalid command.')
# gcc compile: hello.c,world.c


# for循环
names = ['Michael','Bob','Tracy']
for name in names:
    print(name)
# Michael
# Bob
# Tracy

# range()函数:
# 生成一个整数序列,左闭右开
sum = 0
for i in list(range(101)):
    sum += i
print(sum)
# 5050


# while循环
sum2 = 0
n = 99
while n > 0:
    sum2 += n
    n -= 2
print(sum2)
# 2500


# break
n = 1
while n <= 100:
    if n > 10: # 当n = 11时,条件满足,执行break语句
        break # break语句会结束当前循环
    print(n)
    n = n + 1
print('END')
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# END


# continue
n = 0
while n < 10:
    n = n + 1
    if n % 2 == 0: # 如果n是偶数,执行continue语句
        continue # continue语句会直接继续下一轮循环,后续的print()语句不会执行
    print(n)
# 1
# 3
# 5
# 7
# 9


# dict字典
# 使用键-值(key-value)存储,具有极快的查找速度
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
d['Adam'] = 67
d['Jack'] = 90
d['Jack'] = 88
print(d['Michael'],d['Adam'],d['Jack'])
# 95 67 88

# 通过in判断key是否存在
print('Tomas' in d)
# False

# get()函数:
# 查找key是否存在, 如果key不存在,可以返回None,或者自己指定的value
print(d.get('Thomas'))
# None
print(d.get('Thomas', -1))
# -1

# pop(key)函数:
# 删除key
d.pop('Bob')
print(d)
# {'Michael': 95, 'Tracy': 85, 'Adam': 67, 'Jack': 88}


# set集合
s = {1,2,2,3}
s2 = set([3,2,2,1])
print(s,s2)
# {1, 2, 3} {1, 2, 3}

# add(key)函数
# 添加key
s.add(4)
s.add(4)
print(s)
# {1, 2, 3, 4}

# remove(key)函数
# 删除key
s.remove(3)
print(s)
# {1, 2, 4}

# set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集、并集等操作
print(s&s2)
# {1, 2}
print(s|s2)
# {1, 2, 3, 4}
特性 列表 (List) 元组 (Tuple) 集合 (Set) 字典 (Dictionary)
可变性 可变 不可变 可变 可变
元素类型 任意类型(可包含可变/不可变对象) 任意类型(可包含可变/不可变对象) 必须为不可变对象(可哈希) 键必须为不可变对象,值可为任意类型
有序性 有序 有序 无序 有序(Python 3.7+)
允许重复元素 键唯一,值可重复
语法示例 [1, 'a', [2]] (1, 'a', [2]) {1, 2, 3} {'key1': 10, 'key2': 20}
适用场景 动态数据集合,需频繁增删改查 固定数据集合(如配置项、常量) 去重、快速成员检查、集合运算(交并差) 键值对映射,快速通过键查找值
是否支持索引 是(list[0] 是(tuple[0] 通过键访问(dict['key']
内存占用 较高(因预留空间) 较低(不可变,存储紧凑) 高(哈希表实现) 高(哈希表实现)
底层实现 动态数组 静态数组 哈希表 哈希表

廖雪峰的Python学习网站

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐