Python 基础

目录

Python语言的特点

Python语言的使用场景

sublime text

PyCharm

注释

Python程序中的中文注释报错问题

数据类型

运算符

if条件语句

while循环

input(), raw_input()

函数

字符串

for循环

字符串常用函数

列表

列表中常用函数

两列表的=和copy函数

元组

元组中常用函数

字典

字典中常用函数

lambda表达式

map()

filter()

in, not in

常用内置函数

模块与模块之间的调用


 

Python语言的特点

1. 面向对象语言

2. 解释型语言 -- 执行效率低

3. 代码简洁,开发效率高

4. 丰富的函数库

 

 

Python语言的使用场景

1. web开发

2. 网络爬虫

3. 网络安全

4. 自动化运维

5. 数据分析

6. 人工智能

 

 

sublime text

http://www.sublimetext.com/

1. 运行代码ctrl+B或者Command+B

2. sublime text 3 安装package control问题:https://www.jianshu.com/p/5d3d20de0841

 

 

PyCharm

1. Mac下的Pycharm教程 https://www.jianshu.com/p/dc396a37ddee

2. pyCharm 专业版、教育版 和 社区版的区别详解及查看其版本 https://blog.csdn.net/shuiyixin/article/details/89530500

3. 调整代码格式快捷键:ctrl+alt+L或者command+option+L

 

 

注释

#表示单行注释
'''
    表示
    多行
    注释
'''
"""
    表示
    多行
    注释
"""

Python程序中的中文注释报错问题

1. 报错原因:运行时编译编码问题导致的

2. 解决方案:在py文件开始部分加上编码注解

# coding: utf-8

或者

# encoding= utf-8

(注意:=左边不能有空格)

 

 

数据类型

Python是弱类型的语言,在声明变量时不需要主动写数据类型,程序会自动根据变量值识别对应的类型。

type(参数)    # 用来识别参数的数据类型

eg.

# encoding=utf-8
a = 123	# 变量a,并赋值123,python会自动识别相应的数据类型
print(a)
print(type(a))	# int,即integer

a = 3.14	# 变量a,并赋值3.14,python会自动识别相应的数据类型
print(a)
print(type(a))	# float

a = "good morning!"	# 变量a,并赋值"good morning!",python会自动识别相应的数据类型
print(a)
print(type(a))	# str,即string

a = "中文"	# 变量a,并赋值"中文",python会自动识别相应的数据类型
print(a)
print(type(a))	# str,即string

 

 

运算符

+ 加号也可以用做字符串连接

* 乘还可以用来与字符串做运算

/ 普通除法运算

// 整除运算

% 取余数

** 幂运算

eg.

# coding: utf-8

a = 5
s1 = "Hello"
s2 = "World"

print(s1 + " " + s2)	# 如果+两端都是字符串,会做字符串连接的操作

# print(a + s1)	# 会报错,在python中不可以将字符串与数值做+运算,需要统一数据类型
print(str(a) + s1)	# 将a类型转换为str
# print(a + int(s1))	# 会报错,因为str s1无法转换成int

print(s1 * 3)	# 输出3个s1

 

 

if条件语句

if 条件1 :
    语句块1
elif 条件2 :
    语句块2
...
elif 条件n-1 :
    语句块n-1
...
else:
    语句块n

 

 

while循环

while 逻辑表达式 :
	循环体

 

 

input(), raw_input()

1. sublime text不能交互调试,缺少插件,使用Ctrl+B/Command+B该函数不能正常工作;pycharm中该函数能正常工作。

2. sublime text 3中的解决方案:

2.1. 安装SublimeREPL:确保package control已安装 --> Ctrl/Command+Option+P --> 输入install package并回车 --> 输入SublimeREPL并回车,进行安装

2.2 SublimeREPL默认运行python,而不是python3,如需修改https://blog.csdn.net/huangyixian2/article/details/82929927

2.3 运行程序时:Tools --> SublimeREPL --> Python --> Python - RUN current file

 

1. Python3中 input(提示文字):接收键盘输入的内容,接收的内容为字符串,如果需要其它数据类型,需要强制转换。

 (同时,SublimeREPL使用python3)

# encoding=utf-8

v = input("Python3中 input,输入一个数字,如9090:")
print(v)
print(type(v))

v = input("Python3中 input,输入一个数字,如3.14:")
print(v)
print(type(v))

v = input("Python3中 input,输入一个字符串,如aaa:")
print(v)
print(type(v))

v = input("Python3中 input,输入一个两边含引号的字符串,如\"a\":")
print(v)
print(type(v))

2. Python2中 raw_input(提示文字), input(提示文字):都能接收键盘输入的内容,raw_input接收的内容为字符串,input接受数字,或者两边含引号的字符串。

 (同时,SublimeREPL使用Python3)

#encoding=utf-8

v = raw_input("Python2中 raw_input,输入一个数字,如9090:")
print(v)
print(type(v))

v = input("Python2中 input,输入一个数字,如9090:")
print(v)
print(type(v))

v = raw_input("Python2中 raw_input,输入一个数字,如3.14:")
print(v)
print(type(v))

v = input("Python2中 input,输入一个数字,如3.14:")
print(v)
print(type(v))

v = raw_input("Python2中 raw_input,输入一个两边含引号的字符串,如\"a\":")
print(v)
print(type(v))

v = input("Python2中 input,输入一个两边含引号的字符串,如\"a\":")
print(v)
print(type(v))

v = raw_input("Python2中 raw_input,输入一个字符串,如aaa:")
print(v)
print(type(v))

v = input("Python2中 input,输入一个字符串,如aaa:")
print(v)
print(type(v))

 

 

函数

def 函数名([参数1,参数2…..]) :
	函数体
	[return 返回值]

1. 在函数中可以有参数,可以没有参数,可以有或没有返回值。调用函数时,使用“函数名([参数])”。

1.1 调用函数传递参数时,可以指定参数的位置,不一定按照默认位置来写

def fun1(x, y, z):
	print("x is " + str(x))
	print("y is " + str(y))
	print("z is " + str(z))

fun1(2, 7, 9)
print("************")
fun1(2, 7, z=9)
print("************")
fun1(2, z=9, y=7)
print("************")
fun1(y=7, z=9, x=2)

output:

x is 2
y is 7
z is 9
************
x is 2
y is 7
z is 9
************
x is 2
y is 7
z is 9
************
x is 2
y is 7
z is 9
[Finished in 0.0s]

1.2 在声明函数时,可以给参数设置默认值

def fun2(x = True, y = False):
	print("x is " + str(x))
	print("y is " + str(y))

fun2(False, True)
print("************")
fun2()
print("************")
fun2(x = False)
print("************")
fun2(y = True)

output:

x is False
y is True
************
x is True
y is False
************
x is False
y is False
************
x is True
y is True
[Finished in 0.0s]

2. 函数可以传递可变参数

2.1 *args:列表参数(不是数据结构中的列表)

def fun3(x, *args):
	print("x is " + str(x))
	print("args is " + str(args))
	if len(args) > 0 :
		print("args[0] is " + str(args[0]))

fun3(5, 6, 7, 8, 9)
print("************")
fun3(5)

output:

x is 5
args is (6, 7, 8, 9)
args[0] is 6
************
x is 5
args is ()
[Finished in 0.0s]

2.2 **kwargs:字典参数

def fun4(x, **kwargs):
	print("x is " + str(x))
	print("kwargs is " + str(kwargs))

fun4(2, color="r", rotation=45)
print("************")
fun4(2, name="Jack", age=20, department="computer science")
print("************")
fun4(2)

output:

x is 2
kwargs is {'color': 'r', 'rotation': 45}
************
x is 2
kwargs is {'name': 'Jack', 'age': 20, 'department': 'computer science'}
************
x is 2
kwargs is {}
[Finished in 0.0s]

3. 函数很好的体现了封装的思想,对内隐藏细节,对外暴露接口。

4. python中函数定义必须先写在前,再调用;和Java中不一样。

 

 

字符串

用双引号或单引号括起来的字符序列叫做字符串。

在Python中,字符串中的每一个字符都可以使用下标来找到,下标的作用类似索引,用来表示字符串中字符的位置。

len(字符串):可以返回当前字符串的长度。

切片:获取字符串中指定范围的字符,不会改变原字符串。字符串变量名[start:end] (start<=i<end)

# encoding=utf-8
s = "0123456"
print(s)
print(len(s))
print(s[:])		# 获取全部字符串
print(s[1])		# 获取第1个位置的字符
print(s[1:3])	# 获取第1个位置到第3个位置的字符串,注意不包括第3个位置的字符
print(s[1:])	# 获取第1个位置到末尾的字符串
print(s[:3])	# 获取从头到第3个位置的字符串,注意不包括第3个位置的字符
print(s[-1])	# 获取倒数第1个位置的字符
print(s[-3:-1])	# 获取倒数第3个位置到倒数第1个位置的字符串,注意不包括倒数第1个位置的字符
print(s[-3:])	# 获取倒数第3个位置到末尾的字符串
print(s[:-1])	# 获取从头到倒数第1个位置的字符串,注意不包括倒数第1个位置的字符
print(s[::-1])	# 逆序排列原字符串并返回
print(s)

 

 

for循环

for 变量 in 可迭代对象:
	循环体

(可迭代对象:字符串、列表、元组、数组、集合)

将可迭代对象中的每一个元素循环获取,每一次获取的元素都赋值给变量。

 

 

字符串常用函数

upper(): 将当前字符串转换成大写。
lower():将当前字符串转换成小写。

isupper(): 判断当前字符串是否全部为大写字母。
islower(): 判断当前字符串是否全部为小写字母。

startswith(参数): 判断当前字符串是否是以参数开头。
endswith(参数): 判断当前字符串是否是以参数结尾。

count(“参数”):判断参数在当前字符串中出现了几次。

find(参数):找到参数在当前字符串中第一次出现的位置,如果参数在当前字符串中不存在,那么返回-1。
rfind(参数):找到参数在当前字符串中最后一次出现的位置,如果参数在当前字符串中不存在,那么返回-1。
index(参数):与find类似,区别在于,如果参数在当前字符串中没有出现,报错。

strip([参数]):默认去除当前字符串两边空格,如果有参数,那么去除字符串左右两边的参数。
lstrip([参数]):语法规则同上,关注点在左边。
rstrip([参数]):语法规则同上,关注点在右边。
replace(old, new):将当前字符串中所有的old替换成new。

join(参数):将参数中的每一个元素用当前字符串连接。
split(参数):按照参数,将当前字符串拆分,拆分后形成一个列表。

# encoding=utf-8
s1 = "How are you dOing?"
s2 = "HOW?"
s3 = "you!"

print(s1.upper() + " " + s1.lower())
print(str(s1.isupper()) + " " + str(s1.islower()))
print(str(s1.upper().isupper()) + " " + str(s1.lower().islower()))
print(str(s2.isupper()) + " " + str(s2.islower()))
print(str(s3.isupper()) + " " + str(s3.islower()))

print("**********")

print(s1.startswith("H"))
print(s1.startswith("h"))
print(s1.endswith("?"))

print("**********")

print(s1.count("o"))
print(s1.count("O"))

print("**********")

print(str(s1.find("o")) + " " + str(s1.rfind("o"))) 
print(str(s1.find("%")) + " " + str(s1.rfind("%")))
print(s1.index("o"))
# print(s1.index("%"))

print("**********")

s4 = "aHELLOa"
print(s4)
print(s4.lstrip("a"))
print(s4.rstrip("a"))
print(s4.strip("a"))
print(s4.replace("a", ""))

print("**********")

s5 = "HelloWorld"
v1 = ",".join(s5)
print(v1)
print(type(v1))
v2 = v1.split(",")
print(v2)
print(type(v2))

#join函数的实现
s = ""
for item in s5:
	s += item + ",";
s = s[:-1]
print(s)

output:

HOW ARE YOU DOING? how are you doing?
False False
True True
True False
False True
**********
True
False
True
**********
2
1
**********
1 9
-1 -1
1
**********
aHELLOa
HELLOa
aHELLO
HELLO
HELLO
**********
H,e,l,l,o,W,o,r,l,d
<type 'str'>
['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']
<type 'list'>
H,e,l,l,o,W,o,r,l,d
[Finished in 0.0s]

 

 

列表

列表(list):
类似java中的List,其实就是一个集合(容器),可以将不同数据类型的元素装到列表中。
在实际开发中,更多情况下会将同样数据类型的元素装入列表中。

列表使用一对儿中括号[]将所有的元素括起来。

1. 列表同字符串类似,也存在索引与切片。

2. 列表中的元素能修改,而字符串中的字符不能修改。

#encoding=utf-8
l = [123, 3.14, "abc", True, ["a", "b", "c"]]

print(l)
print(l[0])
print(l[::-1])
print(l[4])
print(l[4][1])

print("**********")

l[0] = 234
print(l)
l[1:-2] = [2.718, "xyz"]
print(l)

print("**********")

# s = "abc"
# s[0] = "z"
# print(s)

output:

[123, 3.14, 'abc', True, ['a', 'b', 'c']]
123
[['a', 'b', 'c'], True, 'abc', 3.14, 123]
['a', 'b', 'c']
b
**********
[234, 3.14, 'abc', True, ['a', 'b', 'c']]
[234, 2.718, 'xyz', True, ['a', 'b', 'c']]
**********
[Finished in 0.0s]

3. 列表与字符串之间的转换

#encoding=utf-8
s = "Hello"

# 字符串转换成列表,将字符串中的每一个字符变成了列表中的每一个元素
v = list(s)
print(v)
print(type(v))

# 列表转换字符串,需求是:"Hello"
l = ["H", "e", "l", "l", "o"]
v = str(l)
print(v)
print(type(v))	# 此时字符串为'['H', 'e', 'l', 'l', 'o']'并不符合需求

# 列表是可迭代对象,可以使用for循环
v = ""
for item in l:
	v += str(item)
print(v)

output:

['H', 'e', 'l', 'l', 'o']
<type 'list'>
['H', 'e', 'l', 'l', 'o']
<type 'str'>
Hello
[Finished in 0.0s]

列表中常用函数

append(参数):将参数加入到当前列表的末尾。

clear():清空当前列表。空列表:[]

insert(位置,参数):在当前列表的指定位置,添加参数。

pop([参数]):如果没有参数,默认删除当前列表中最后一个元素,如果有参数,那么删除指定位置的元素。
del关键字:对列表中的元素进行删除,要配合索引来实现。

l = ["Hello"]
print(l)

l.append(3.14)
print(l)
l.append([1, 2, 3])
print(l)

l.insert(1, True)
print(l)

l.pop()
print(l)
l.pop(1)
print(l)

del l[1]
print(l)

l.clear()
print(l)

output:

['Hello']
['Hello', 3.14]
['Hello', 3.14, [1, 2, 3]]
['Hello', True, 3.14, [1, 2, 3]]
['Hello', True, 3.14]
['Hello', 3.14]
['Hello']
[]

Process finished with exit code 0

count(参数):判断参数在当前列表中出现的次数。

l = [123, "abc", "abc", 123, False, 123]
print(l.count(123))
print(l.count("abc"))

output:

3
2

Process finished with exit code 0

两列表的=和copy函数

1. = 为引用传递,并不是值传递:

2. copy函数,在堆中再创建内容相同的一份:

 

 

元组

元组:元组是用一对括号()括起来的,元组中的内容不可以被修改。类型名tuple。

1. 元组中同样有索引与切片。

2. 元组中的内容不可以修改(赋值,删除)。

tu = (123, 46, "abc", "hello", "tom", True,)

# 元组中的内容不可以被赋值,下行代码会报错
# tu[1] = "kite"

# 元组中的内容不可以删除,下行代码会报错
# del tu[1]

3. 元组与列表之间的转换,元组与字符串之间的转换

tu = (123, 46, "abc", True, )
print(tu)
print(type(tu))

print("*********")

l = ["h", "e", "l", "l", "o"]
print(l)
tu2 = tuple(l)
print(tu2)
print(type(tu2))

l = list(tu2)
print(l)
print(type(l))


print("*********")

s = "hello"
print(s)
tu2 = tuple(s)
print(tu2)
print(type(tu2))

s = str(tu2)
print(s)
print(type(s))

output:

(123, 46, 'abc', True)
<class 'tuple'>
*********
['h', 'e', 'l', 'l', 'o']
('h', 'e', 'l', 'l', 'o')
<class 'tuple'>
['h', 'e', 'l', 'l', 'o']
<class 'list'>
*********
hello
('h', 'e', 'l', 'l', 'o')
<class 'tuple'>
('h', 'e', 'l', 'l', 'o')
<class 'str'>

Process finished with exit code 0

元组中常用函数

count(参数):返回参数在当前元组中出现的次数。

index(参数, [start, stop]):判断参数在当前元组中第一次出现的位置,也可以在指定区间位置判断。

tu = (123, True, 123, 123, "abc", 123)

print(tu.index(123))
print(tu.index(123, 1))
print(tu.index(123, 3, 5))
print(tu.index(123, 5, 6))

output:

0
2
3
5

Process finished with exit code 0

 

 

字典

字典:”键-值对”形式(键key/name,值value)存储的,类型名为dict,通常根据一个键找到对应的值。
格式:{k1:v1, k2:v2, ...}

1. 默认情况下字典在for循环中获取的是key。

字典中常用函数

1.

keys():获取当前字典中所有的键。
values():获取当前字典中所有的值。
items():获取当前字典中所有的键和值。

2.

get(key):根据key获取value,如果找一个在当前字典中没有的key,会返回None。
使用索引也可以获取某一个key对应的值,如果找一个在当前字典中没有的key,会报错。

3.

如果需要修改某个key对应的值,可以直接用索引的方式去修改。

4.

popitem():删除最后一对key-value。
pop(key):根据key删除一对key-value。

5.

通过fromkeys方法创建一个字典。
第一个参数通过列表的形式建立所有key,此时value都是None;第二个参数写入value,第一个参数创建的所有key都会对应这一个value。

dic = {"name": "Jack", "age": "20", "department": "computer science"}
print(dic)
print(type(dic))

print("**********")

for item in dic:
    print(item)

print("**********")

print(dic.keys())
for item in dic.keys():
    print(item)

print("**********")

print(dic.values())
for item in dic.values():
    print(item)

print("**********")

print(dic.items())
for key, value in dic.items():
    print(key + ": " + value)

print("**********")

print(dic["name"])
# print(dic["keyNotExists"])

print(dic.get("name"))
print(dic.get("keyNotExists"))

print("**********")

dic["department"] = "software engineering"
print(dic)

print("**********")

dic.popitem()
print(dic)

dic.pop("age")
print(dic)

print("**********")

v = dict.fromkeys(["a", "b", "c"])
print(v)

v = dict.fromkeys(["a", "b", "c"], 0)
print(v)

output:

{'name': 'Jack', 'age': '20', 'department': 'computer science'}
<class 'dict'>
**********
name
age
department
**********
dict_keys(['name', 'age', 'department'])
name
age
department
**********
dict_values(['Jack', '20', 'computer science'])
Jack
20
computer science
**********
dict_items([('name', 'Jack'), ('age', '20'), ('department', 'computer science')])
name: Jack
age: 20
department: computer science
**********
Jack
Jack
None
**********
{'name': 'Jack', 'age': '20', 'department': 'software engineering'}
**********
{'name': 'Jack', 'age': '20'}
{'name': 'Jack'}
**********
{'a': None, 'b': None, 'c': None}
{'a': 0, 'b': 0, 'c': 0}

Process finished with exit code 0

 

 

lambda表达式

函数式编程思想

lambda 参数 : 返回值

eg.

# encoding=utf-8

def fun1(x):
	return x ** 2
print("函数:" + str(fun1(2)))

fun = lambda x : x ** 2
print("lambda表达式:" + str(fun(2)))

print("************")

def fun2(x, y):
	return x + y
print("函数:" + str(fun2(5, 6)))

fun = lambda x, y : x + y
print("lambda表达式:" + str(fun(5, 6)))

output:

函数:4
lambda表达式:4
************
函数:11
lambda表达式:11
[Finished in 0.0s]

map()

map(lambda, iterable):将iterable中的每一个元素放入lambda中处理,处理后的内容组成一个新列表并返回。

# encoding=utf-8

l = [20, 21, 22, 23, 24]

def test_map_add10(array):
	new = []
	for item in array:
		new.append(item + 10)
	return new

def test_map(array, func):
	new = []
	for item in array:
		new.append(func(item))
	return new

lAdd10 = test_map_add10(l)
print(l, lAdd10)

print("*********")

lAdd10 = test_map(l, lambda x : x+10)
print(l, lAdd10)
lSub20 = test_map(l, lambda x : x-20)
print(l, lSub20)
lMul100 = test_map(l, lambda x : x*100)
print(l, lMul100)

print("*********")

lAdd10 = list(map(lambda x : x+10, l))
print(l, lAdd10)
lSub20 = list(map(lambda x : x-20, l))
print(l, lSub20)
lMul100 = list(map(lambda x : x*100, l))
print(l, lMul100)

output:

[20, 21, 22, 23, 24] [30, 31, 32, 33, 34]
*********
[20, 21, 22, 23, 24] [30, 31, 32, 33, 34]
[20, 21, 22, 23, 24] [0, 1, 2, 3, 4]
[20, 21, 22, 23, 24] [2000, 2100, 2200, 2300, 2400]
*********
[20, 21, 22, 23, 24] [30, 31, 32, 33, 34]
[20, 21, 22, 23, 24] [0, 1, 2, 3, 4]
[20, 21, 22, 23, 24] [2000, 2100, 2200, 2300, 2400]
[Finished in 0.0s]

eg. 对于给定的列表l,处理数据,去除前面的国产或欧美字样

# encoding=utf-8

l = ["国产:A", "欧美:B", "日韩:C", "国产:D", "欧美:E", "国产:F"]

newL = list(map(lambda x : x[x.find(":")+1:], l))
print(l, newL)

output:

['国产:A', '欧美:B', '日韩:C', '国产:D', '欧美:E', '国产:F'] ['A', 'B', 'C', 'D', 'E', 'F']
[Finished in 0.0s]

filter()

filter(lambda, iterable):将iterable中的每一个元素放入lambda中过滤,过滤后的内容组成一个新列表并返回。

# encoding=utf-8

l = ["国产:A", "欧美:B", "日韩:C", "国产:D", "欧美:E", "国产:F"]

def test_filter_guochan(array):
	new = []
	for item in array:
		# if item[0:2] == "国产" :
		if item.startswith("国产"):
			new.append(item)
	return new

def test_filter(array, func):
	new = []
	for item in array:
		if func(item):
			new.append(item)
	return new

lGuochan = test_filter_guochan(l)
print(l, lGuochan)

lGuochan = test_filter(l, lambda x: x.startswith("国产"))
print(l, lGuochan)
lOumei = test_filter(l, lambda x: x.startswith("欧美"))
print(l, lOumei)

lGuochan = list(filter(lambda x: x.startswith("国产"), l))
print(l, lGuochan)
lOumei = list(filter(lambda x: x.startswith("欧美"), l))
print(l, lOumei)

output:

['国产:A', '欧美:B', '日韩:C', '国产:D', '欧美:E', '国产:F'] ['国产:A', '国产:D', '国产:F']
['国产:A', '欧美:B', '日韩:C', '国产:D', '欧美:E', '国产:F'] ['国产:A', '国产:D', '国产:F']
['国产:A', '欧美:B', '日韩:C', '国产:D', '欧美:E', '国产:F'] ['欧美:B', '欧美:E']
['国产:A', '欧美:B', '日韩:C', '国产:D', '欧美:E', '国产:F'] ['国产:A', '国产:D', '国产:F']
['国产:A', '欧美:B', '日韩:C', '国产:D', '欧美:E', '国产:F'] ['欧美:B', '欧美:E']
[Finished in 0.0s]

 

 

in, not in

判断某一个值或变量是否在一个可迭代对象中。

注:针对字典,是判断key而不是value

eg.

s = "HelloWorld"
li = [1, 2, 3, 4, 5]
tu = ("a", "b", "c", "d")
dic = {"name": "Jack", "age": 15, "department": "computer science"}
print("e" in s)
print("e" not in s)
print(1 in li)
print("a" in tu)
print("name" in dic)
print("Jack" in dic)

output:

True
False
True
True
True
False
[Finished in 0.0s]

 

 

常用内置函数

abs(数):绝对值。
max(iterable), min(iterable):最大值,最小值。如果是字典,则比较key,而不是value。
divmod(被除数, 除数):求模取余,返回(商, 余数)。
round(参数1[, 参数2]):四舍五入,参数1为数,参数2表示保留到小数点后几位,如果没有参数2则表示四舍五入到个位。

print(abs(-5))

print("*********")

print(max([0,1,2]), min([0,1,2]))
print(max((0,1,2)), min((0,1,2)))
print(max({0:"c", 1:"b", 2:"a"}), min({0:"c", 1:"b", 2:"a"}))

print("*********")

print(10//3, 10%3)
print(divmod(10, 3))

print("*********")

print(round(2.718))
print(round(2.718, 0))
print(round(2.718, 1))
print(round(2.718, 2))

output:

5
*********
2 0
2 0
2 0
*********
3 1
(3, 1)
*********
3
3.0
2.7
2.72
[Finished in 0.0s]

range([start,]end[,step]):快速生成一个整数数字序列。

tmp = []
for item in range(10):
	tmp.append(item)
print(tmp)

tmp = []
for item in range(0, 10):
	tmp.append(item)
print(tmp)

tmp = []
for item in range(0, 10, 1):
	tmp.append(item)
print(tmp)

tmp = []
for item in range(1, 10, 2):
	tmp.append(item)
print(tmp)

output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 5, 7, 9]
[Finished in 0.0s]

zip():将多个可迭代对象合并。

name = ["Jack", "Jane", "MoMo"]
age = [23, 21, 22]
department = ["software engineering", "digital media technology", "computer science"]

v = zip(name, age, department)
for item in v:
	print(item)

output:

('Jack', 23, 'software engineering')
('Jane', 21, 'digital media technology')
('MoMo', 22, 'computer science')
[Finished in 0.0s]

 

 

模块与模块之间的调用

模块:一个py文件可以说成是一个模块。

如果在一个模块中想要调用另一个模块中的函数,需要使用import关键字。

eg.

functions.py

def myMax(l):
	my_max = l[0]
	count = 1
	for item in l[1:]:
		if item > my_max:
			my_max = item
		elif item == my_max:
			count += 1
	return (my_max, count)

def myMin(l):
	my_min = l[0]
	count = 1
	for item in l[1:]:
		if item < my_min:
			my_min = item
		elif item == my_min:
			count += 1
	return (my_min, count)

main.py

import functions

l = [-1, 0, 3, 0, 0, -1, 1, 3, 2, 0, 0, 3, 3]
print(functions.myMax(l))
print(functions.myMin(l))

or

from functions import myMax
from functions import myMin

l = [-1, 0, 3, 0, 0, -1, 1, 3, 2, 0, 0, 3, 3]
print(myMax(l))
print(myMin(l))

output from main.py:

(3, 4)
(-1, 2)
[Finished in 0.0s]

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值