python快速入门

这一生的挚爱 提交于 2020-01-19 21:05:48

一、准备工作

1.1 安装

安装 Anaconda3

安装第三方库:

  • 方法一:pip install xxx.whl
  • 方法二:conda install xxx

备用第三方库安装包下载链接:https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyhook

1.2 Notebook快捷键

执行单元格:Shift+Enter

1.3 修改文件存储路径

查看文件存储路径,默认在C盘

import os
print(os.path.abspath('.'))

二、Python基础

2.1 初识Python

print ("hello world")

Python之歌

import this

2.2 数值运算

2.2.1 基本运算

print(10/3)
print(2**3)
print(1.3e5)
print(1.3e-5)
print(0xFF)

运行结果:

3.3333333333333335
8
130000.0
1.3e-05
255

2.2.2 常用类型

  • int
  • float
  • str
  • bool

定义变量不需要指定变量类型

a = 1
print(type(a))
a = 1.5
print(type(a))
b = '1.5'
print(type(b))
c = 1 < a < 2
print(c)
print(type(c))

运行结果:

<class ‘int’>
<class ‘float’>
<class ‘str’>
True
<class ‘bool’>

2.2.2类型转换

b = int(a)
c = float(a)
d = str(a)
a = 1.5
b = int(a)
print(b)
print(type(b))

运行结果:

1
<class ‘int’>

2.2.3 函数

  • abs
  • round
  • min
  • max
min(2,3,4,5)
max(2,3,4,5)

2.3 字符串操作

  • len
  • split
  • join
  • replace
  • upper
  • lower
  • strip
  • lstrip
  • rstrip
  • format
a = 'hello'
print(a)
b = 'hello' + 'python'
print(b)
print(a*3)
print(len(a))
c = '1 2 3 4 5'
print(c.split())
d = '1,2,3,4,5'
print(d.split(','))
e = ''
print(e.join(d))
print(b.replace('python','world'))
print(b)
f = 'aBc'
print(f.upper())
print(f.lower())
g = '   hello   '
print(g.strip())
print(g.lstrip())
print(g.rstrip())

运行结果:

hello
hellopython
hellohellohello
5
[‘1’, ‘2’, ‘3’, ‘4’, ‘5’]
[‘1’, ‘2’, ‘3’, ‘4’, ‘5’]
1,2,3,4,5
helloworld
hellopython
ABC
abc
hello
hello
 hello

print('{} {} {}'.format("a","b","c"))
print('{2} {1} {0}'.format("a","b","c"))
print('{a} {b} {c}'.format(a=1,b=2,c=3))
a = "a"
b = 4.5
c = 1
print('%s %f %d' %  (a,b,c))

a b c
c b a
1 2 3
a 4.500000 1

2.4 索引&切片

  • 从前数第一个索引为0
  • 从后数第一个索引为-1
  • 切片 : 左闭右开
name = 'My name is Zoie'
print(name[0])
print(name[-1])
print(name[0:7])
print(name[:2])
print(name[3:-3])
print(name[-4:])
print(name[:])
print(name[::2])

运行结果:

M
e
My name
My
name is Z
Zoie
My name is Zoie
M aei oe

2.5 列表list

  • 可以存放任何类型
  • 长度无限制
  • 可索引
  • len
  • del
  • [not] in
  • count
  • index
  • append
  • insert
  • remove
  • pop
  • sort 默认升序
     sort(reverse=True) 降序
     sort(reverse=False) 升序序
  • sorted
  • reverse
list1 = []
print(type(list1))
list2 = [1,'abc',3.5]
print(list2)
list3 = list()
print(list3)
list4 = list([1,'abc',3.5])
print(list4)
print(len(list4))
a = [123,456]
b = ['abc','def']
print(a+b)
print(a*3)
a[0] = 789
print(a)
a[:] = [0,1,'abc',2,3,4,5,6,7,8,9]
print(a)
del a[1]
print(a)
del a[6:]
print(a)
print('abc' in a)
print('abc' not in a)

<class ‘list’>
[1, ‘abc’, 3.5]
[]
[1, ‘abc’, 3.5]
3
[123, 456, ‘abc’, ‘def’]
[123, 456, 123, 456, 123, 456]
[789, 456]
[0, 1, ‘abc’, 2, 3, 4, 5, 6, 7, 8, 9]
[0, ‘abc’, 2, 3, 4, 5, 6, 7, 8, 9]
[0, ‘abc’, 2, 3, 4, 5]
True
False

a = [1,2,[3,4]]
print(a[2])
print(a[2][1])
a = ['apple','apple','1']
print(a.count('apple'))
print(a.index('1'))
a.append('abc')
print(a)
a.append(['a','b'])
print(a)
a.insert(1,'python')
print(a)
a.remove(['a','b'])
print(a)
a.remove('apple')
print(a)
print(a.pop(1))
print(a)

[3, 4]
4
2
2
[‘apple’, ‘apple’, ‘1’, ‘abc’]
[‘apple’, ‘apple’, ‘1’, ‘abc’, [‘a’, ‘b’]]
[‘apple’, ‘python’, ‘apple’, ‘1’, ‘abc’, [‘a’, ‘b’]]
[‘apple’, ‘python’, ‘apple’, ‘1’, ‘abc’]
[‘python’, ‘apple’, ‘1’, ‘abc’]
apple
[‘python’, ‘1’, ‘abc’]

a = [1,2,4,8,2,3]
a.sort()
print(a)
b = [1,2,3,8,2,3]
c = sorted(b)
print(b)
print(c)
c.reverse()
print(c)

[1, 2, 2, 3, 4, 8]
[1, 2, 3, 8, 2, 3]
[1, 2, 2, 3, 3, 8]
[8, 3, 3, 2, 2, 1]

2.6 字典dict

  • key-value
  • 无序
  • key一般是字符串,value任何数据类型都可以
  • get
  • pop
  • update
  • [not] in
  • keys
  • values
  • items
a = {}
print(type(a))
b = dict()
print(b)
print(type(b))
a['first'] = 123
print(a)
a['second'] = 456
print(a)
a['second'] = 789
print(a)
c = {'first':123, 'second':456}
print(c)
print(c['first'])
c['third'] = [1,2,3]
c['forth'] = 'abc'
print(c)

<class ‘dict’>
{}
<class ‘dict’>
{‘first’: 123}
{‘first’: 123, ‘second’: 456}
{‘first’: 123, ‘second’: 789}
{‘first’: 123, ‘second’: 456}
123
{‘first’: 123, ‘second’: 456, ‘third’: [1, 2, 3], ‘forth’: ‘abc’}

dicts = {}
a = {'abc':123, 'def':456}
b = {'ghi':789, 'jkl':222}
dicts['dict1'] = a
dicts['dict2'] = b
print(dicts)
c = dict([('a',123),('b',456)])
print(c)
c['a'] += 1
print(c)
print(c['a'])
print(c.get('a'))
print(c.get('c','meiyou'))
print(c)
print(c.pop('a'))
print(c)
del c['b']
print(c)

{‘dict1’: {‘abc’: 123, ‘def’: 456}, ‘dict2’: {‘ghi’: 789, ‘jkl’: 222}}
{‘a’: 123, ‘b’: 456}
{‘a’: 124, ‘b’: 456}
124
124
meiyou
{‘a’: 124, ‘b’: 456}
124
{‘b’: 456}
{}

dict1 = {'a':123, 'b':456}
dict2 = {'a':111, 'c':789}
dict1.update(dict2)
print(dict1)
print(dict2)
print('a' in dict1)
print('a' not in dict1)
print(dict1.keys())
print(dict1.values())
print(dict1.items())

{‘a’: 111, ‘b’: 456, ‘c’: 789}
{‘a’: 111, ‘c’: 789}
True
False
dict_keys([‘a’, ‘b’, ‘c’])
dict_values([111, 456, 789])
dict_items([(‘a’, 111), (‘b’, 456), (‘c’, 789)])

2.7 集合set

  • 去重
set1 = set()
type(set1)
print(set1)
set2 = set([123,123,123,456])
print(set2)
list1 = [123,123,123,456]
set3 = set(list1)
print(set3)
set4 = {1,1,1,2,3}
print(set4)

set()
{456, 123}
{456, 123}
{1, 2, 3}

set1 = {1,2,3,4}
set2 = {3,4,5,6}
print(set1.union(set2))
print(set2.union(set1))
print(set1 | set2)
print(set1)
print(set1.intersection(set2))
print(set2.intersection(set1))
print(set1 & set2)
print(set1.difference(set2))
print(set2.difference(set1))
print(set1 - set2)
print(set2 - set1)
a = {1,2,3,4}
b = {2,3}
print(a.issubset(b))
print(b.issubset(a))
print(b <= a)
print(a <= b)

{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4}
{3, 4}
{3, 4}
{3, 4}
{1, 2}
{5, 6}
{1, 2}
{5, 6}
False
True
True
False

a = {1,2,3}
a.add(4)
print(a)
a.update([4,5,6])
print(a)
a.remove(4)
print(a)
print(a.pop())
print(a)

{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 5, 6}
1
{2, 3, 5, 6}

2.8 赋值机制

a = 1000
b = a
print(id(a))
print(id(b))
print(a is b)

a = 1000
b = 1000
print(id(a))
print(id(b))

a = 1
b = 1
print(id(a))
print(id(b))

2380999961616
2380999961616
True
2380999961296
2380999961840
140728256992064
140728256992064

2.9 判断结构

a = 100
if a > 200:
    print(200)
elif a < 100:
    print(100)
else:
    print(a)
print('over')
    
abc = [1,'abc',2]
if 'abc' in abc:
    print('ok')

100
over
ok

2.10 循环结构

a = 0
while a < 5:
    print (a)
    a += 1

0
1
2
3
4

a = set(['a','b','c'])
while a:
    e = a.pop()
    print(e)

a = set(['a','b','c'])
for i in a:
    print(i)

b
c
a
b
c
a

a = ['a','b','c']
for i in range(len(a)):
    print(a[i])

a
b
c

三、Python高级

3.1 函数

def add1(a,b):
    print(a+b)
add1(1,2)

def add2(a,b):
    return a+b
ab = add2(1,2)
print(ab)

def add3(a=10,b=20):
    print(a+b)
add3()
add3(1)
add3(1,2)
add3(b=2)

def add4(a,*args):
    for i in args:
        a += i
    return a
print(add4(0,1,2,3,4))

def add5(a,**kwargs):
    for k,v in kwargs.items():
        print(k,v)
add5(0,x=1,y=2)

def add6(a,*args):
    b = 0
    for i in args:
        b += 1
        a += i
    return a,b
a,b = add6(0,1,2,3,4)
print(a,b)

3
3
30
21
3
12
10
x 1
y 2
10 4

3.2 模块与包

%%writefile test.py

test_v =10

def test_f(a):
    print(a)

test_f(2)

Writing test.py

%run test.py

2

import test

2

test

<module ‘test’ from ‘C:\Users\42091\test.py’>

print(test.test_v)
test.test_f(3)

10
3

import test as tt
print(tt.test_v)
tt.test_f(3)

10
3

from test import test_v,test_f
print(test_v)
test_f(3)

10
3

from test import *
print(test_v)
test_f(3)

10
3

import os
os.remove('test.py')
os.path.abspath('.')

‘C:\Users\42091’

3.3 异常处理模块

  • try
  • except
  • finally
  • raise
import math

for i in range(10):
    try:
        num = input('input a number: ')
        if num == 'q':
            break
        result = 1/math.log(float(num))
        print(result)
    except ValueError:
        print('number must > 0')
    except ZeroDivisionError:
        print('log(number) must not = 0')
    except Exception:
        print('unknown error')

input a number: 0
number must > 0
input a number: 1
log(number) must not = 0
input a number: 2
1.4426950408889634
input a number:

class MyError(ValueError):
    pass

mylist = ['a','b','c']
while True:
    instr = input()
    if instr not in mylist:
        raise MyError('Invalid number: %s' % instr)

a
d
---------------------------------------------------------------------------
MyError Traceback (most recent call last)
<ipython-input-1-cf3f6206e33c> in <module>
   6 instr = input()
   7 if instr not in mylist:
----> 8 raise MyError(‘Invalid number: %s’ % instr)
MyError: Invalid number: d

try:
    print('hello')
finally:
    print('over')

hello
over

3.4 文件操作

%%writefile readfile.txt
hello python
hello world
txt = open('readfile.txt')
txt_read = txt.read()
print(txt_read)
txt = open('readfile.txt')
txt_lines = txt.readlines()
print(type(txt_lines))
print(txt_lines)
for i in txt_lines:
    print(i)
txt.close()

hello python
hello world


<class ‘list’>
[‘hello python\n’, ‘hello world\n’]
hello python


hello world

open文件三种模式

  • w 覆盖
  • a 追加
  • r 读
txt = open('writefile.txt','w')
txt.write('hello python')
txt.write('\n')
txt.write('hello world')
txt.close()
txt = open('writefile.txt','a')
txt.write('hello python')
txt.write('\n')
txt.write('hello world')
txt.close()
txt = open('errorfile.txt','w')
try:
    for i in range(10):
        r = 10/(i-5)
        txt.write(str(i)+'\n')
except Exception:
    print('error: ',i)
finally:
    txt.close()

with open 不需要手动调用 close()

with open('errorfile.txt','w') as f:
    f.write('abc')

3.5 类

class people:
    '帮助信息'
    # 所有实例都会共享
    number = 1000
    
    # 构造函数,初始化的方法,当创建一个类的时候,首先会调用它
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def display_number(self):
        print ('number: ',people.number)
    def display_name(self):
        print(self.name)
p1 = people('abc',30)
p2 = people('def',40)
print(p1.name)
print(p2.name)
p1.display_number()
p2.display_number()
p2.name = 'aaa'
print(p2.name)
del p2.name
setattr(p1,'name','bbb')
print(getattr(p1,'name'))
delattr(p1,'name')

abc
def
number: 1000
number: 1000
aaa
bbb

print(people.__doc__)
print(people.__name__)
print(people.__module__)
print(people.__bases__)
print(people.__dict__)

帮助信息
people
main
(<class ‘object’>,)
{‘module’: ‘main’, ‘doc’: ‘帮助信息’, ‘number’: 1000, ‘init’: <function people.init at 0x0000027249A6FAE8>, ‘display_number’: <function people.display_number at 0x0000027249A6FB70>, ‘display_name’: <function people.display_name at 0x0000027249A8F048>, ‘dict’: <attribute ‘dict’ of ‘people’ objects>, ‘weakref’: <attribute ‘weakref’ of ‘people’ objects>}

class Parent():
    number = 1000
    num = 1000
    def __init__(self):
        print('父类构造函数')
    def parentM(self):
        print('父类特有方法')
    def pcM(self):
        print('被重写的父类方法')

class Child(Parent):
    number = 100
    def __init__(self):
        print('子类构造函数')
    def childM(self):
        print('子类特有方法')
    def pcM(self):
        print('重写父类的方法')

c = Child()
c.parentM()
c.childM()
print(c.number)
print(c.num)
c.pcM()

子类构造函数
父类特有方法
子类特有方法
100
1000
重写父类的方法

3.6 时间

import time
print(time.time())
print(time.localtime(time.time()))
print(time.asctime(time.localtime(time.time())))
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))

import calendar
print(calendar.month(2020,1))
print(help(calendar.month))

1579363048.7818944
time.struct_time(tm_year=2020, tm_mon=1, tm_mday=18, tm_hour=23, tm_min=57, tm_sec=28, tm_wday=5, tm_yday=18, tm_isdst=0)
Sat Jan 18 23:57:28 2020
2020-01-18 23:57:28
January 2020
Mo Tu We Th Fr Sa Su
        1   2   3   4   5
 6    7   8    9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31


Help on method formatmonth in module calendar:


formatmonth(theyear, themonth, w=0, l=0) method of calendar.TextCalendar instance
Return a month’s calendar string (multi-line).


None

四、练习题

  1. 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
n = 0
for i in range(1,5):
    for j in range(1,5):
        for k in range(1,5):
            if (i!=j) and (i!=k) and (j!=k) :
                print(i,j,k)
                n += 1
print('共有'+str(n)+'个符合条件的三位数')
  1. 企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数?
i = float(input('请输入当月利润:'))
base = [100,60,40,20,10,0]
rate = [0.01,0.015,0.03,0.05,0.075,0.1]
result = 0
for level in range(0,6):
    if i > base[level]:
        result += (i-base[level])*rate[level]
        i = base[level]
print('应发放奖金'+str(result) +'万元')
  1. 输入三个整数x,y,z,请把这三个数由大到小输出
mylist = []
for i in range(3):
    x = int(input('input: '))
    mylist.append(x)
mylist.sort(reverse = True)
print(mylist)
  1. 将一个列表的数据复制到另一个列表中
a = [1,2,3]
b = a[:]
print(b)
  1. 暂停一秒输出,并格式化当前时间。使用 time 模块的 sleep() 函数。
import time
while True:
    print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
    time.sleep(1)
  1. 打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
for x in range(1,10):
    for y in range(0,10):
        for z in range(0,10):
            num1 = x*100 + y*10 + z
            num2 = pow(x,3) + pow(y,3) + pow(z,3)
            if num1 == num2:
                print(num1)
  1. 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
s = input('input: ')
letters = 0
space = 0
digit = 0
others = 0
for c in s:
    if c.isalpha():
        letters += 1
    elif c.isspace():
        space += 1
    elif c.isdigit():
        digit += 1
    else:
        others += 1
print('字符%d个,空格%d个,数字%d个,其它%d个。' % (letters,space,digit,others))
  1. 一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?
h = 100 # 初始高度
time =10 # 下落次数
height = [] #下落高度
for i in range(2,time+1):
    h /= 2
    height.append(h)
print('第十次反弹'+str(h/2)+'米')
print('第十次落地共经过'+str(sum(height)*2+100)+'米')
  1. 利用递归方法求5!
def factorial(num):
    if num < 0:
        print('负数无阶乘')
    elif num == 0:
        return 1
    else:
        return num*factorial(num-1)

num = 5
print(str(num)+'!='+str(factorial(num)))
  1. 利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来
def reverse_str(s,n):
    if n > 0:
        print(s[n-1])
        reverse_str(s,n-1)
    
s = input('输入字符串:')
n = len(s)
reverse_str(s,n)
  1. 按逗号分隔列表
mylist = ['a','b','123','abc']
s = ','.join(str(n) for n in mylist)
print(s)

a,b,123,abc

  1. 将一个数组逆序输出
nums = [1,5,8,6,3,2]
n = len(nums)
print(nums)
for i in range(int(n/2)):
    nums[i],nums[n-i-1] = nums[n-i-1],nums[i]
print(nums)

[1, 5, 8, 6, 3, 2]
[2, 3, 6, 8, 5, 1]

  1. 两个 3 行 3 列的矩阵,实现其对应位置的数据相加,并返回一个新矩阵
X = [[1,2,3],[4,5,6],[7,8,9]]
Y = [[1,2,3],[4,5,6],[7,8,9]]
Z = [[0,0,0],[0,0,0],[0,0,0]]
for i in range(3):
    for j in range(3):
        Z[i][j] = X[i][j] + Y[i][j]
for z in Z:
    print(z)
  1. 匿名函数求和
add_ab = lambda a,b:a+b
print(add_ab(1,2))
  1. 查找字符串的位置
s1 = 'abcdefg'
s2 = 'cde'
print(s1.find(s2))

2

  1. 在字典中找到年龄最大的人,并输出
people = {'zhangsan':30,'lisi':35,'wangwu':20}
m = 'zhangsan'
for p in people.keys():
    if people[p] > people[m]:
        m = p
print('年龄最大的人是%s,年龄为%d' % (m,people[m]))
  1. 列表转换为字典
k = ['a',123]
v = ['b',456]
print(dict([k,v]))

{‘a’: 123, ‘b’: 456}

  1. 从键盘输入一个字符串,将小写字母全部转换成大写字母,然后输出到一个磁盘文件"test"中保存
f = open('test.txt','w')
s = input('输入一个字符串:')
s = s.upper()
f.write(s)
f.close()

f = open('test.txt','r')
print(f.read())
f.close()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!