【Python】【整理】廖雪峰Python教程代码整理——1、第一个Python程序

1. 第一个Python程序

命令行退出Python

exit()

数学运算

100 + 200

打印

print('打印内容')

单引号或双引号皆可。

1.1 使用文本编辑器

命令窗口执行Python文件

python test.py

1.2 Python代码运行助手

1.3 输入和输出

输出

print('输出内容')

或者

print('内容1','内容2')

逗号相当于一个空格。

输入

name = input(输入name:)

输入后转换类型

s = input('birth: ')
birth = int(s)

2. Python基础

2.1 数据类型和变量

转义字符

符号内容
""
\n换行
\t制表
\\
r’’''内不转义
print(’’’…’’’)换行
%%%

除法

符号含义
a/b精确除
a//b取整
a%b取余

2.2 字符串和编码

字符转编码(Unicode)

ord('A')

编码转字符

chr('65')

整数编码

'\u4e2d\u6587'

等价于

'中文'

bytes类型数据表示

x = b'ABC'

str转bytes

'ABC'.encode('ascii')
'中文'.encode('utf-8')

bytes转str

>>> b'ABC'.decode('ascii')
'ABC'
>>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
'中文'

忽略错误字节

>>> b'\xe4\xb8\xad\xff'.decode('utf-8', errors='ignore')
'中'

计算str包含多少个字符

>>> len(b'ABC')
3
>>> len(b'\xe4\xb8\xad\xe6\x96\x87')
6
>>> len('中文'.encode('utf-8'))
6

包含中文的*.py文件开头注释

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

格式化

>>> 'Hello, %s' % 'world'
'Hello, world'
>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)
'Hi, Michael, you have $1000000.'

占位符

占位符替换内容
%d整数
%f浮点数
%s字符串
%x十六进制数

补零和位数

print('%2d-%05d' % (3, 1))
print('%.2f' % 3.1415926)

结果:

 3-00001
3.14 

format

>>> 'Hello, {0}, 成绩提升了 {1:.1f}%'.format('小明', 17.125)
'Hello, 小明, 成绩提升了 17.1%'

2.3 list和tuple

2.3.1 list

>>> classmates = ['Michael', 'Bob', 'Tracy']
>>> classmates
['Michael', 'Bob', 'Tracy']
获取list中元素的个数
>>> len(classmates)
3
访问list中某个元素
>>> classmates[0]
'Michael'

或者

>>> classmates[-1]
'Tracy'
list末尾追加元素
classmates.append('Adam')
插入到指定的位置,比如索引号为1的位置:
>>> classmates.insert(1, 'Jack')
>>> classmates
['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']
删除list某元素
classmates.pop(1) 	//删除指定
classmates.pop()     //删除末尾
替换list某元素

直接赋值

一个list可有不同类型元素
list可多维可空

2.3.2 tuple

与list相比,[]改成()
不可修改
1个元素时
>>> t = (1,)
>>> t
(1,)
可嵌套list
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值