Python 笔记1 | Python基础

业务应用(多媒体、大数据、云计算、分布式、AI)
Python+Numpy+scikit-learn
编译型语言:源代码-编译器->机器代码
解释型语言:源代码-解释器->执行动作
交互模式:简单任务
脚本模式:批量任务、自动任务

一、Python语言

1.起步

交互式:

print('hello world!')

a = hello world!
print(a)

a = 100
print(a)

exit()//退出

Python语言开发环境
控制台,交互或脚本
IDLE工具,交互或脚本
集成环境,sublime-text

2.变量

变量名 = 值
动态类型语言
变量名表示一个标签,为变量赋值的过程本质上就是用在其所表示的标签和值之间建立绑定关系。

字符串字面值
“xxx”
‘xxx’
‘’‘xxx’’’
代码:string1.py

# 双引号字符串
print("The language 'Python' is named after\n\
\"Monty Python\", not the snake.")
# 单引号字符串
print('The language \'Python\' is named after\n\
"Monty Python", not the snake.')
# 三引号字符串
print('''The language 'Python' is named after
"Monty Python", not the snake.''')
# 原始字符串
print(r'The language \'Python\' is named after\n\
"Monty Python", not the snake.')

字符串操作
代码:string2.py

# 字符串大小写转换
name = 'wei min'
print(name)
# 单词首字母大写
print(name.title())
# 所有字符转大写
print(name.upper())
print(name)
name = name.upper()
print(name)
# 所有字母转小写
print(name.lower())
# 查看类型
print(type(name))
# 合并(拼接)字符串
first_name = 'wei'
last_name = 'min'
full_name = first_name + ' ' + last_name
print(full_name)

print('Hello, ' + full_name.title() + '!')
message = 'Hello, ' + full_name.title() + '!'
print(message)
# 用制表符合换行符添加空白
print('C/C++\tGo\tPython\tJava')
print('C/C++\nGo\nPython\nJava')
print('Languages:\n\tC/C++\n\tGo\n\tPython\n\tJava')
# 删除字符串首尾的空白字符
languages = '\n\t    C/C++ Go Python Java\n\t    '
print('[' + languages + ']')
# 删除首部空格
print('[' + languages.lstrip() + ']')
# 删除尾部空格
print('[' + languages.rstrip() + ']')
# 删除首尾空格
print('[' + languages.strip() + ']')
print('[' + languages + ']')

languages = languages.strip()
print('[' + languages + ']')

整数
代码:integer.py

# 整数类型用int表示
print(type(0))
# 加、减、乘、除和取余运算
print('3+4 =', 3 + 4)
print('3-4 =', 3 - 4)
print('3*4 =', 3 * 4)
print('3/4 =', 3 / 4)
print('3%4 =', 3 % 4)
# 幂运算
print('2**3 =', 2 ** 3)
print('2**(1/2) =', 2 ** (1/2))
print('2**(-1/2) =', 2 ** (-1/2))
print('(-2)**(1/2) =', (-2) ** (1/2))
print('(-2)**(-1/2) =', (-2) ** (-1/2))
# 优先级和小括号
print('1+2*3 =', 1 + 2 * 3)
print('(1+2)*3 =', (1 + 2) * 3)
# 除零异常
print('1/0 =', end=' ')
try:
	result = 1 / 0
except ZeroDivisionError as error:
	print('error:', error)
else:
	print(result)

浮点数
代码:float.py

# 浮点数类型用float表示
print(type(0.))
# 浮点数在计算机内部用近似值表
# 示,其小数位数可能是不确定的
print(0.1 + .2)
print(.15 * 2.)

数值型和字符串的转换
代码:str.py

my_lucky_number = 8888
# 将整数按十进制形式转换为字符串
print("My lucky number is " +
	str(my_lucky_number) + ".")
	
print("My lucky number is ",
	my_lucky_number, ".", sep="")

注释
单行注释:# 注释行
多行注释:
‘’’
注释行

‘’’
代码:comment.py

# 单行注释
'''
注释行1
注释行2
'''
import this
a = 10
b = a
print(id(a), id(b))
b = 20;
print(a)
print(id(a), id(b))

列表
代码:list.py

# 用方括号表示列表
bicycles = ['trek', 'cannondale', 'redline',
	'specialized']
print(type(bicycles))
print(bicycles)
# 通过索引访问列表中的元素
# 首元素的索引为0,其后依次递增
print("['%s', '%s', '%s', '%s']" % (
	bicycles[0], bicycles[1],
	bicycles[2], bicycles[3]))
# 尾元素的索引为-1,其前依次递减
print("['%s', '%s', '%s', '%s']" % (
	bicycles[-4], bicycles[-3],
	bicycles[-2], bicycles[-1]))
# 可象使用单个变量一样使用列表中的任意元素
message = 'My first bicycle was a ' + \
	bicycles[0].title() + '.'
print(message)
# 下标越界异常
# 正数下标的合理范围:[0, 长度-1]
try:
	message = 'My last bicycle was a ' + \
		bicycles[4].title() + '.'
except IndexError as error:
	print('error:', error)
else:
	print(message)
# 负数下标的合理范围:[-长度, -1]
try:
	message = 'My last bicycle was a ' + \
		bicycles[-5].title() + '.'
except IndexError as error:
	print('error:', error)
else:
	print(message)

列表的增删改操作
代码:modification.py

# 修改
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
# 追加
motorcycles.append('honda')
print(motorcycles)
motorcycles = []
print(motorcycles)
motorcycles.append('yamaha')
motorcycles.append('suzuki')
motorcycles.append('honda')
print(motorcycles)
# 插入
motorcycles.insert(0, 'ducati')
print(motorcycles)
# 删除
del motorcycles[2]
print(motorcycles)
# del语句的本质就是解除变量名与对象间的绑定关系
a = 100
print(a)
del a
try:
	print(a)
except NameError as error:
	print('error:', error)
# 从首尾弹出
first = motorcycles.pop(0)
print(first, motorcycles)
last = motorcycles.pop()
print(motorcycles, last)
# 删除第一个匹配元素
motorcycles.append('suzuki')
motorcycles.append('yamaha')
motorcycles.append('ducati')
print(motorcycles)
while 'yamaha' in motorcycles:
	motorcycles.remove('yamaha')
print(motorcycles)

列表的重组操作
代码:orgnizing.py

# 就地排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.sort()
print(cars)
cars.sort(reverse=True)
print(cars)
# 有序副本
scars = sorted(cars)
print(cars)
print(scars)
rcars = sorted(scars, reverse=True)
print(scars)
print(rcars)
# 逆序
rcars.reverse()
print(rcars)
# 尾元素索引 = 长度-1 / -1
ncars = len(cars)
print(ncars, cars[ncars-1], cars[-1])
cars.pop(0)
ncars = len(cars)
print(ncars, cars[ncars-1], cars[-1])
# 空列表长度为0,访问其中的任
# 何元素都会导致下标越界异常
cars = []
ncars = len(cars)
try:
	print(ncars, cars[ncars-1], cars[-1])
except IndexError as error:
	print('error:', error)

范围列表
range(起始, 终止, 步长) -> 列表
[起始, 终止)
for (int i = 0; i < 5; ++i) { … }
for i in range(0,5): …
代码:range.py

for number in [0, 1, 2, 3, 4]:
	print(number, end=' ')
print()
for number in range(5):
	print(number, end=' ')
print()
for number in range(1, 6):
	print(number, end=' ')
print()
for number in range(1, 10, 2):
	print(number, end=' ')
print()
odds = list(range(1, 10, 2))
print(odds)
# 平方表
squares = []
for number in range(1, 11):
	squares.append(number ** 2)
print(squares)
cubes = [number ** 3 for number
	in range(1, 11)]
print(cubes)
# 简单统计
print(max(cubes), min(cubes), sum(cubes))

遍历列表
代码:traversal.py

magicians = ['alice', 'david', 'carolina']
print(magicians)
# 基于索引的循环遍历
for i in range(len(magicians)):
	print(magicians[i], end=' ')
print()
# 根据索引判断是否为首尾元素
for i in range(len(magicians)):
	print(("['" if i == 0 else "'") +
		magicians[i],
		end= "', " if i < len(magicians) - 1
		else "']\n")
# 基于迭代的循环遍历
for magician in magicians:
	print(magician, end=' ')
print()

# 同时获取索引和元素
for i, magician in enumerate(magicians):
	print(("['" if i == 0 else "'") +
		magician,
		end= "', " if i < len(magicians) - 1
		else "']\n")
# 通过缩进控制循环范围
for magician in magicians:
	print(magician.title() +
		', that was a great trick!')
	print("I can't wait to see your next trick, " +
		magician.title() + '.')
print('Thank you, everyone. '
	'That was a great magic show!')

切片
用[起始索引:终止索引]的形式表示一个从起始索引开始到终止索引之前的元素范围。
代码:slice.py

#     0   1   2   3   4
#    -5  -4  -3  -2  -1
a = [10, 20, 30, 40, 50]
print(a)
# 1 2 3
print(a[1:4])
# -3
print(a[-3:-2])
# 1 2 3 4
print(a[1:])
# 0 1 2 3
print(a[:4])
# 0 1 2 3 4
print(a[:])
# 1 2 3 / 1
print(a[1:4][1:2])
# -6 ... 0 1 2 3 4 ... 10
print(a[-6:10])
# 空
print(a[4:1])
# 遍历切片
for b in a[1:4]:
	print(b, end=' ')
print()
# 修改元素本身:30->300
a[2] = 300
print(a)
# 修改切片副本:300->3000
a[2:3][0] = 3000
print(a)
# 修改切片本身:[300]->[3000]
a[2:3] = [3000]
print(a)

复制列表
代码:copy.py

# a \
#    > [...]
# b /
a = [10, 20, 30, 40, 50]
b = a
print('a:', a)
print('b:', b)
a.append(60)
b.pop(0)
print('a:', a)
print('b:', b)
# c -> [...]
# d -> [...]
c = [10, 20, 30, 40, 50]
d = c[:]
print('c:', c)
print('d:', d)
c.append(60)
d.pop(0)
print('c:', c)
print('d:', d)
e = ['123', 456, 7.89, True]
print(e)
for f in e:
	print(f, type(f))

元组
代码:tuple.py

# 用圆括号表示元组
dimensions = (320, 240)
print(dimensions, type(dimensions))
# 基于索引的循环遍历
for i in range(len(dimensions)):
	print(dimensions[i], end=' ')
print()
# 基于迭代的循环遍历
for dimension in dimensions:
	print(dimension, end=' ')
print()
# 不能修改元组的元素
try:
	dimensions[0] *= 2
	dimensions[1] *= 2
except TypeError as error:
	print('error:', error)
# 可以对元组整体赋值
# 其本质是引用新元组
dimensions = (dimensions[0] * 2,
	dimensions[1] * 2)
print(dimensions)
# 元组的元素不可修改,但其元素的元素未必不可修改
dimensions = ([320], [240])
print(dimensions)
dimensions[0][0] *= 2
dimensions[1][0] *= 2
print(dimensions)

二维容器
代码:matrix.py

'''
matrix = [
	[11, 12, 13, 14],
	[21, 22, 23, 24],
	[31, 32, 33, 34]]
'''
rows = 3
cols = 4
'''
matrix = []
for row in range(rows):
	r = []
	for col in range(cols):
		r.append((row + 1) * 10 + col + 1)
	matrix.append(r)
'''
matrix = [[(row + 1) * 10 + col + 1
	for col in range(cols)]
	for row in range(rows)]
'''
print(matrix)
'''
for row in range(rows):
	for col in range(cols):
		print(matrix[row][col],
			end=' ' if col < cols - 1 else '\n')

条件分支
if 条件表达式:
真块
elif 条件表达式:
真块
elif 条件表达式:
真块
else:
假块

你可能感兴趣的:(Python,python,字符串,变量)