python学习笔记
使用的是anaconda带的spyder,一体化做的很方便。课程是南大等的笔记
python笔记
1.0 输入输出
- input 输入
eval() 函数用来执行一个字符串表达式,并返回表达式的值。此处转换为int或元组,好处显而易见,当你只输入34时,eval帮你转化为整型,当你输入3,4时,eval把它转化为元组。就不用int或者tuple强制转换了,因为不确定你输入的是什么
In [13]:type(eval(input()))
"string","34"
Out[13]: tuple
In [15]:type(eval(input()))
"laove"
Out[15]: str
In [11]:type(eval(input()))
3
Out[11]: int
price = input('input the stock price of Apple: ')
input the stock price of Apple: 109
>>> price
'109'
>>> type(price)
<class 'str'>
>>> price = int(input('input the stock price of Apple: '))
>>> price = eval(input('input the stock price of Apple: '))
#input的输入是一个字符串。
#注意,利用input输入多个数时整数时,前面需要添加eval函数,参数直接用','分开。
y,z=eval(input("请输入2个整数,中间用逗号分开:"))
请输入2个整数,中间用逗号分开:123, 222
n,m=input("请输入2个字符串,中间用逗号分开:").split(',')
请输入2个字符串,中间用逗号分开:asf, fsf
print(n, m)
asf fsf
- print 输出
>>> myString = 'Hello, World!'
>>> print(myString)
Hello, World!
>>> # variable
>>> p = 3.14159
>>> myString = 'is a mathematic circular constant'
>>> print(p, myString)
3.14159 is a mathematic circular constant
# print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
默认用“ ”连接输出,也可以更改print中的sep,用其他连接方式
print(变量)
print(字符串)
1.1 字符串
python中定义变量接收字符串,可以用单引号’,双引号“,当字符串中出现单引号,可以在前面加转义字符” \ “,或者字符串用三引号接受
>>> message = "Meet me tonight"
>>> print(message)
Meet me tonight
>>> message = 'The clock strikes at midnight'
>>> print(message)
The clock strikes at midnight
>>> message = " I'm looking for someone to share in an adventure"
>>> print(message)
I'm looking for someone to share in an adventure
>>> message = ''' That's too bad'''
>>> print(message);
That's too bad
>>> movie_quote = """ One of my favorite lines from Godfather is :
... " I'm going to make him an offer he can't refuse. "
... Do you know who said this? """
>>> print(movie_quote)
One of my favorite lines from Godfather is :
" I'm going to make him an offer he can't refuse. "
Do you know who said this?
字符串的format输出和,字符串前用的r,u, f,等
sumA = 0
i = 1
while True:
sumA += i
i += 1
if sumA > 10:
break
print('i={},sum={}'.format(i, sumA))
print(f'i={i},sum={sumA}')
1.2 基本数据类型
- 不可变类型,内存中的数据不允许被修改:
- 数字类型 int, bool, float, complex, long(2.x)
- 字符串 str
- 元组 tuple
- 可变类型,内存中的数据可以被修改:
- 列表 list
- 字典 dict
- Python 中数据类型还可以分为 数字型和非数字型
- 数字型
- 整型 (int)
- 浮点型(float)
- 布尔型(bool) 真 True 假 False 0—— 非零即真
- 复数型 (complex) 主要用于科学计算,例如:平面场问题、波动问题、电感电容等问题
- 非数字型
- 字符串 列表 元组 字典
- 数字型
- 在 Python 中,所有非数字型变量都支持以下特点:
- 都是一个序列 sequence,也可以理解为容器
- 取值 []
- 遍历 for in
- 计算长度、最大/最小值、 比较、删除
- 链接 + 和 重复 *
- 切片
1.2.1 python2
- types of numbers: int , long, float, complex
- type() 可以用来查看变量类型
- #用来表示注释
- python会自动转型,int->long->float->complex
>>> # everything after a hash tag is a comment and is ignored by the interpreter
>>> a = 28
>>> type(a)
<type 'int'>
>>> a
28
>>> print(a)
28
>>> # c = 10l
>>> c = 10L
>>> type(c)
<type 'long'>
>>> e = 2.71821828
>>> type(e)
<type 'float'>
>>> # complex包括实部和虚部,real表示实部,imaginary表示虚部属性
>>> z = 3 + 5.7j
>>> type(z)
<type 'complex'>
>>> z.real
3.0
>>> z.imag
5.7
1.2.2 python3 关键字和表达式
- Types of numbers: int, float, numbers
- 不用担心溢出问题,python也会自动转型
1.3 算术运算符
1.3.1 Arithmetic in python2
- Numbers: int, long, float, complex
- Four operations: add subtract multiply and divide (+,-,*,/)
- The idea of narrower and wider types
>>> x = 5 # int
>>> y = 5L # long
>>> y
5L
>>> long(5)
5L
>>> z = long(y)
>>> z
5L
>>> z = long(x)
>>> z
5L
>>> x
5
>>> # ints are narrower than longs
... # longs are wider than ints
...
>>> # To convert a long to float just add a point 0 at the end
...
>>> x = 28L
>>> y = 28.0 # float
>>> z = float(28)
>>> x = 1.732
>>> 1.732 + 0j
(1.732+0j)
>>> complex(1.732)
(1.732+0j)
>>> float(1.732+0j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float
>>> a = 2 # int
>>> b = 3L # long
>>> c = 6.0 # float
>>> d = 12 + 0j #complex
>>> # Rule : Widen numbers so they're the same type
...
>>> #Addition
... a + b # int + long
5L
>>> # Subtraction
... c - b # float - long
3.0
>>> # Multiplication
... a * c # int * float
12.0
>>> # Division
... d / c # complex / float
(2+0j)
>>> 16/5
3
>>> 16%5
1
>>> # 在python2中16/5 得到 Quotient , 16%5 得到Remainder ,0不能为除数
... # 在python3中16/5 得到3.2,转型为float类型
1.3.2 Arthmetic in python3
- types of numbers: int, float, complex
- Operations: Addition Subtraction Multiplication Division
>>> x = 28
>>> x = 28 # int
>>> y = 28.0 # float
>>> float(28)
28.0
>>> z = float(x)
>>> z
28.0
>>> x #并没有改变x本身的类型
28
>>> 3.14 # float
3.14
>>> int(3.14) # 四舍五入成整数
3
>>> a = 2 # int
>>> b = 6.0 # float
>>> c = 12 +0j #complex number
>>> # Rule : Widen numbers so they're the same type
...
>>> # Addition
... a + b # int + float
8.0
>>> # Subtraction
... b - a # float - int
4.0
>>> # Multiplication
... a * 7 # int * int
14
>>> # Division
... c / b # complex / float
(2+0j)
>>> # 都是向更高范围转型
>>> 16/3 # 返回浮点型数据
5.333333333333333
>>> 16//3 # Quotient
5
>>> 16%3 # Remainder
1
1.4 Pythons interactive help features (dir and help)
>>> dir() # Short for "directory", Python displays a list of available objects When you press Enter
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', '...]
>>> help(pow)
# the first line confirms it is a function in the __builtin__ module
Help on built-in function pow in module builtins:
# the following lines show how to use the funtion, there are 3 inputs listed x, y, z
pow(x, y, z=None, /)
Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
Some types, such as ints, are able to use a more efficient algorithm when
invoked using the three argument form.
>>> pow(2,10)
1024
>>> pow(2,10,3)
1
>>> 2**10
1024
>>> 2**10%3
1
- 用dir()显示的模块都是默认不需要导入的,如__builtins__,模块,可以用help查看其中的函数使用,用help还可以查找其他模块,help(‘modules’)
>>> help('modules')
Please wait a moment while I gather a list of all available modules...
__future__ _tkinter glob runpy
_abc _tracemalloc grp sched
_ast _uuid gzip secrets
_asyncio _warnings hashlib select
_bisect _weakref heapq selectors
_blake2 _weakrefset hello setuptools
_bootlocale _xxtestfuzz hmac shelve
_bz2 ...
>>> import math
>>> dir() # 确定库,是否导入成功
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'math']
>>> dir(math)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
>>> math.sin(3.1415926/3)
0.8660253948528064
>>> math.sin(1)
0.8414709848078965
>>> help(radians)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'radians' is not defined
>>> help(math.radians)
Help on built-in function radians in module math:
radians(x, /)
Convert angle x from degrees to radians.
>>> math.sin(math.radians(60)) #角度转化为弧度值
0.8660254037844386
>>> math.sin(math.radians(30))
0.49999999999999994
1.5 True or False
0 is False while 1 is True
>>> True
True
>>> true
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined
>>> False
False
>>> 3 == 5
False
>>> str(True) # convert it to string
'True'
>>> int(True)
1
>>> 5 + True
6
1.6 datetime 操练
>>> dir() # 先看没有datetime模块
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'math']
>>> help('modules') # 查看所有模块
Please wait a moment while I gather a list of all available modules...
x
__future__ _tkinter glob runpy
_abc _tracemalloc grp sched
_ast ...
>>> import datetime # 导入datetime模块
>>> dir() # 查看是否导入成功
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'datetime', 'math']
>>> dir(datetime) # 查看datetime模块中类、属性等,包含date,time,datetime等类
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo']
>>> gvr = datetime.date(1956,1, 31)
>>> gvr
datetime.date(1956, 1, 31)
>>> print(gvr)
1956-01-31
>>> print(gvr.year)
1956
>>> print(gvr.month)
1
>>> print(gvr.max)
9999-12-31
>>> print(gvr.day)
31
>>> dt = datetime.timedelta(100) # timedelta类可用来修改日期的,正数代表加100天,负数(-100)代表减100天
>>> dt
datetime.timedelta(days=100)
>>> print(dt)
100 days, 0:00:00
>>> mill = datetime.date(2000,1,1)
>>> print(mill+dt)
2000-04-10
>>> #python Default format: yyyy-mm-dd,but you can specify a different format if you like
>>> print(gvr.strftime("%A, %B, %d, %Y")) # %A is the full name of the day(周几),%B month,%d, is the day of the month and %Y is the four-digit year
Tuesday, January, 31, 1956
>>> message = "GVR was born on {:%A, %B, %d, %Y}."
>>> print(message.format(gvr))
GVR was born on Tuesday, January, 31, 1956.
>>> launch_date = datetime.date(2017,3,30)
>>> launch_time = datetime.time(22,27,0)
>>> launch_datetime = datetime.datetime(2017,3,20,22,27,0)
>>> print(launch_date)
2017-03-30
>>> print(launch_time)
22:27:00
>>> print(launch_datetime)
2017-03-20 22:27:00
>>> print(launch_datetime.hour)
22
# 获取当前时间
>>> now = datetime.datetime.today()
>>> print(now)
2020-01-20 18:20:55.425133
>>> print(now.microsecond)
425133
# 把时间字符串转换为时间对象
>>> moon_landing = "7/20/1969"
>>> moon_landing_datetime = datetime.datetime.strptime(moon_landing,"%m/%d/%Y")
>>> print(moon_landing)
7/20/1969
>>> print(moon_landing_datetime)
1969-07-20 00:00:00
>>> print(type(moon_landing_datetime))
<class 'datetime.datetime'>
1.7 条件、循环和函数
1.7.1 小练习:输出2-100直接的素数
- for循环格式
iterable_object为可迭代对象
判断是否为迭代器(Iterator)和可迭代对象(Iterable)
from collections.abc import Iterator, Iterable
isinstance(range(10), Iterator)
Out[14]: False
isinstance(iter(range(10)), Iterator)
Out[15]: True
isinstance(range(10), Iterable)
Out[17]: True
# 迭代器用next访问下一个元素
x = iter(range(3))
next(x)
Out[24]: 0
next(x)
Out[25]: 1
next(x)
Out[26]: 2
next(x)
Traceback (most recent call last):
File "<ipython-input-27-92de4e9f6b1e>", line 1, in <module>
next(x)
StopIteration
- String, List, Tuple,Dictionary, File
for iter_var in iterable_object:
suite_to repeat
# 直接访问字符串
s = "Python"
for x in s:
print(x, end=" ")
P y t h o n
# 索引方式访问字符串
for x in range(len(s)):
print(s[x], end=" ")
P y t h o n
- for循环判断素数
import math
def isPrime():
primeList = []
for item in range (2,101):
for x in range(2, int(math.sqrt(item))+1):
if item%x == 0 and item != x:
print(f"{item} is not prime")
break
else:
primeList.append(item)
print(f"{item} is prime")
print(primeList)
isPrime()
输出:[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
- while循环格式
j = 1
sum = 0
while j<10:
sum += j
j+=1
1.7.2 条件语句缩减
x>0 则 t=1 否则 t=0
t = 1 if x> 0 else 0
1.7.3 一些函数的使用
1.7.3.1 range()
返回的是a 到 b-1的列表对象,c是步长
# 默认start也是0
range(start, end , step=1)
range(start, end)
range(end)
>>> list(range(3, 11, 2))
[3, 5, 7, 9]
#一共11-3 = 8 个元素的列表
list(range(3, 11))
Out[1]: [3, 4, 5, 6, 7, 8, 9, 10]
#一共11-0 = 11 个元素的列表
list(range(11))
Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1.7.3.2 enumerate()
1.8 异常
—小例子
# 保留字符串中的字母
coffeeList = ["32Latte", "_Americano30", "/34Cappuccino", "Mocha35"]
def cleanList(lst):
cleanedList = []
for item in lst:
for u in item:
if u.isalpha() != True:
item = item.replace(u,"")
cleanedList.append(item)
return cleanedList
print(cleanList(coffeeList))
# 这里是出错代码
def cleanList(lst):
cleanedList = []
for item in lst:
itemCopy = item[:]
for u in item:
if u.isalpha() != True:
itemCopy = itemCopy.strip(u) #删除会引起item的改变,需要再次循环多一个item【】副本
cleanedList.append(itemCopy)
return cleanedList