python基础教程一

  • 安装
  • 定义功能
    • 函数参数
    • 函数默认参数
    • 可变参数
    • 关键字参数
  • 变量形式
  • 模块安装
  • 文件读取
    • 文件读取1
    • 文件读取2
    • 文件读取3
  • Class类
  • input输入
  • 元组、列表、字典
    • 元组列表
    • list 列表
      • List 添加
      • List 删除
      • List 索引
      • List 排序
    • 多维列表
    • dictionary 字典
      • 创建字典
      • 字典存储类型
  • import 模块
    • import 的各种方法
    • 自己的模块
  • 其他
  • 导出与导入
    • 导出
    • 导入

安装

安装python,建议不要直接安装python,可以直接安装anaconda+pycharm。

定义功能

Python 使用 def开始函数定义,紧接着是函数名,括号内部为函数的参数,内部为函数的 具体功能实现代码,如果想要函数有返回值, 在 expressions 中的逻辑代码中用 return 返回。

def function():print('This is a function')a = 1+2print(a)

函数参数

我们在使用的调用函数的时候,想要指定一些变量的值在函数中使用,那么这些变量就是函数的参数,函数调用的时候, 传入即可。

def func(a, b):c = a+bprint('the c is ', c)

函数默认参数

我们在定义函数时有时候有些参数在大部分情况下是相同的,只不过为了提高函数的适用性,提供了一些备选的参数, 为了方便函数调用,我们可以将这些参数设置为默认参数,那么该参数在函数调用过程中可以不需要明确给出。

def sale_car(price, color='red', brand = 'carmy', is_second_hand = True):print('price', price,'color', color,'brand', brand,'is_second_hand', is_second_hand,)

在这里定义了一个 sale_car 函数,参数为车的属性,但除了 price 之外,像 color, brand 和 is_second_hand 都是有默认值的,如果我们调用函数 sale_car(1000), 那么与 sale_car(1000, ‘red’, ‘carmy’, True) 是一样的效果。当然也可以在函数调用过程中传入特定的参数用来修改默认参数。通过默认参数可以减轻我们函数调用的复杂度。

可变参数

顾名思义,函数的可变参数是传入的参数可以变化的,1个,2个到任意个。当然可以将这些 参数封装成一个 list 或者 tuple 传入,但不够 pythonic。使用可变参数可以很好解决该问题,注意可变参数在函数定义不能出现在特定参数和默认参数前面,因为可变参数会吞噬掉这些参数。

def report(name, *grades):total_grade = 0for grade in grades:total_grade += gradeprint(name, 'total grade is ', total_grade)```

定义了一个函数,传入一个参数为 name, 后面的参数 *grades 使用了 * 修饰,表明该参数是一个可变参数,这是一个可迭代的对象。该函数输入姓名和各科的成绩,输出姓名和总共成绩。所以可以这样调用函数 report(‘Mike’, 8, 9),输出的结果为 Mike total grade is 17, 也可以这样调用 report(‘Mike’, 8, 9, 10),输出的结果为 Mike total grade is 27.

关键字参数

def portrait(name, **kw):print('name is', name)for k,v in kw.items():print(k, v)

定义了一个函数,传入一个参数 name, 和关键字参数 kw,使用了 ** 修饰。表明该参数是关键字参数,通常来讲关键字参数是放在函数参数列表的最后。如果调用参数 portrait(‘Mike’, age=24, country=‘China’, education=‘bachelor’) 输出:

name is Mike
age 24
country China
education bachelor

变量形式

全局&局部变量
局部变量:在 def 中, 我们可以定义一个局部变量, 这个变量 a 只能在这个功能 fun 中有效, 出了这个功能, a 这个变量就不是那个局部的 a。
全局变量:那如何在外部也能调用一个在局部里修改了的全局变量呢。首先我们在外部定义一个全局变量 a=None, 然后再 fun() 中声明 这个 a 是来自外部的 a。声明方式就是 global a。然后对这个外部的 a 修改后, 修改的效果会被施加到外部的 a 上。所以我们将能看到运行完 fun(), a 的值从 None 变成了 20。

APPLY = 100 # 全局变量
a = None
def fun():global a    # 使用之前在全局里定义的 aa = 20      # 现在的 a 是全局变量了return a+100print(APPLE)    # 100
print('a past:', a)  # None
fun()
print('a now:', a)   # 20

模块安装

有了anaconda之后就自动安装很多包了。

文件读取

文件读取1

\n 换行命令
\t tab 对齐

text='\tThis is my first test.\n\tThis is the second line.\n\tThis is the third line'
print(text)  #延伸 使用 \t 对齐"""This is my first test.This is the second line.This is the third line
"""

open 读文件方式
使用 open 能够打开一个文件, open 的第一个参数为文件名和路径== ‘my file.txt’, 第二个参数为将要以什么方式打开它, 比如 w ==为可写方式. 如果计算机没有找到 ‘my file.txt’ 这个文件, w 方式能够创建一个新的文件, 并命名为 my file.txt

my_file=open('my file.txt','w')   #用法: open('文件名','形式'), 其中形式有'w':write;'r':read.
my_file.write(text)               #该语句会写入先前定义好的 text
my_file.close()                   #关闭文件

文件读取2

我们先保存一个已经有3行文字的 “my file.txt” 文件,然后使用添加文字的方式给这个文件添加一行 “This is appended file.”, 并将这行文字储存在 append_file 里,注意\n的适用性:

append_text='\nThis is appended file.'  # 为这行文字提前空行 "\n"
my_file=open('my file.txt','a')   # 'a'=append 以增加内容的形式打开
my_file.write(append_text)
my_file.close()""""
This is my first test.
This is the second line.
This the third line.
This is appended file.
""""
#运行后再去打开文件,会发现会增加一行代码中定义的字符串

掌握 append 的用法 :open(‘my file.txt’,‘a’) 打开类型为 a ,a 即表示 append。

文件读取3

1、读取文件内容 file.read()

file= open('my file.txt','r')
content=file.read()
print(content)
""""
This is my first test.
This is the second line.
This the third line.
This is appended file.
""""

2、按行读取 file.readline()
如果想在文本中一行行的读取文本, 可以使用 file.readline(), file.readline() 读取的内容和你使用的次数有关, 使用第二次的时候, 读取到的是文本的第二行, 并可以以此类推:

file= open('my file.txt','r')
content = file.readline()  # 读取第一行
print(content)""""
This is my first test.
""""second_read_time=file.readline()  # 读取第二行
print(second_read_time)"""
This is the second line.
"""

3、读取所有行 file.readlines()
如果想要读取所有行, 并可以使用像 for 一样的迭代器迭代这些行结果, 我们可以使用 file.readlines(), 将每一行的结果存储在 list 中, 方便以后迭代.

file= open('my file.txt','r')
content = file.readlines() # python_list 形式
print(content)""""
['This is my first test.\n', 'This is the second line.\n', 'This the third line.\n', 'This is appended file.']
""""# 之后如果使用 for 来迭代输出:
for item in content:print(item)"""
This is my first test.This is the second line.This the third line.This is appended file.
"""

Class类

1、class 定义一个类
class 定义一个类, 后面的类别首字母推荐以大写的形式定义,比如Calculator. class可以先定义自己的属性,比如该属性的名称可以写为 name = ‘Good Calculator’. class后面还可以跟def, 定义一个函数. 比如def add(self,x,y): 加法, 输出print(x+y). 其他的函数定义方法一样,注意这里的self 是默认值.

class Calculator:       #首字母要大写,冒号不能缺name='Good Calculator'  #该行为class的属性price=18def add(self,x,y):print(self.name)result = x + yprint(result)def minus(self,x,y):result=x-yprint(result)def times(self,x,y):print(x*y)def divide(self,x,y):print(x/y)""""
>>> cal=Calculator()  #注意这里运行class的时候要加"()",否则调用下面函数的时候会出现错误,导致无法调用.
>>> cal.name
'Good Calculator'
>>> cal.price
18
>>> cal.add(10,20)
Good Calculator
30
>>> cal.minus(10,20)
-10
>>> cal.times(10,20)
200
>>> cal.divide(10,20)
0.5
>>>
""""

2、init
init 可以理解成初始化class的变量,可以在运行时,给初始值附值,

运行c = Calculator(‘bad calculator’,18,17,16,15),然后调出每个初始值的值。看如下代码。

class Calculator:name='good calculator'price=18def __init__(self,name,price,height,width,weight):   # 注意,这里的下划线是双下划线self.name=nameself.price=priceself.h=heightself.wi=widthself.we=weight
""""
>>> c=Calculator('bad calculator',18,17,16,15)
>>> c.name
'bad calculator'
>>> c.price
18
>>> c.h
17
>>> c.wi
16
>>> c.we
15
>>>
""""

如何设置属性的默认值, 直接在def里输入即可,如下:

def init(self,name,price,height=10,width=14,weight=16):查看运行结果, 三个有默认值的属性,可以直接输出默认值,这些默认值可以在code中更改, 比如c.wi=17再输出c.wi就会把wi属性值更改为17.同理可推其他属性的更改方法。

class Calculator:name='good calculator'price=18def __init__(self,name,price,hight=10,width=14,weight=16): #后面三个属性设置默认值,查看运行self.name=nameself.price=priceself.h=hightself.wi=widthself.we=weight""""
>>> c=Calculator('bad calculator',18)
>>> c.h
10
>>> c.wi
14
>>> c.we
16
>>> c.we=17
>>> c.we
17
""""

input输入

variable=input() 表示运行后,可以在屏幕中输入一个数字,该数字会赋值给自变量。看代码:

a_input=input('please input a number:')
print('this number is:',a_input)''''
please input a number:12       #12 是我在硬盘中输入的数字
this number is: 12
''''

input()应用在if语句中。

在下面代码中,需要将input() 定义成整型,因为在if语句中自变量== a_input== 对应的是1 and 2 整数型。输入的内容和判断句中对应的内容格式应该一致。

也可以将if语句中的1and 2 定义成字符串,其中区别请读者自定写入代码查看。

a_input=int(input('please input a number:'))#注意这里要定义一个整数型
if a_input==1:print('This is a good one')
elif a_input == 2:print('See you next time')
else:print('Good luck')""""
please input a number:1   #input 1
This is a good oneplease input a number:2   #input 2
See you next timeplease input a number:3   #input 3 or other number
Good luck
""""

input扩展
用input()来判断成绩

score=int(input('Please input your score: \n'))
if score>=90:print('Congradulation, you get an A')
elif score >=80:print('You get a B')
elif score >=70:print('You get a C')
elif score >=60:print('You get a D')
else:print('Sorry, You are failed ')""""
Please input your score:
100   #手动输入
Congradulation, you get an A
""""

元组、列表、字典

元组列表

Tuple、叫做 tuple,用小括号、或者无括号来表述,是一连串有顺序的数字。

a_tuple = (12, 3, 5, 15 , 6)
another_tuple = 12, 3, 5, 15 , 6

List 、而list是以中括号来命名的:

a_list = [12, 3, 67, 7, 82]

两者对比:
他们的元素可以一个一个地被迭代、输出、运用、定位取值:

for content in a_list:print(content)
"""
12
3
67
7
82
"""for content_tuple in a_tuple:print(content_tuple)
"""
12
3
5
15
6
"""

下一个例子,依次输出a_tuple和a_list中的各个元素:

for index in range(len(a_list)):print("index = ", index, ", number in list = ", a_list[index])
"""
index =  0 , number in list =  12
index =  1 , number in list =  3
index =  2 , number in list =  67
index =  3 , number in list =  7
index =  4 , number in list =  82
"""for index in range(len(a_tuple)):print("index = ", index, ", number in tuple = ", a_tuple[index])
"""
index =  0 , number in tuple =  12
index =  1 , number in tuple =  3
index =  2 , number in tuple =  5
index =  3 , number in tuple =  15
index =  4 , number in tuple =  6
"""

list 列表

List 添加

列表是一系列有序的数列,有一系列自带的功能, 例如:

a = [1,2,3,4,1,1,-1]
a.append(0)  # 在a的最后面追加一个0
print(a)
# [1, 2, 3, 4, 1, 1, -1, 0]

在指定的地方添加项:

a = [1,2,3,4,1,1,-1]
a.insert(1,0) # 在位置1处添加0
print(a)
# [1, 0, 2, 3, 4, 1, 1, -1]

List 删除

remove();

a = [1,2,3,4,1,1,-1]
a.remove(2)        # 删除列表中第一个出现的值为2的项
print(a)
# [1, 3, 4, 1, 1, -1]

List 索引

显示特定位:

a = [1,2,3,4,1,1,-1]
print(a[0])  # 显示列表a的第0位的值
# 1print(a[-1]) # 显示列表a的最末位的值
# -1print(a[0:3]) # 显示列表a的从第0位 到 第2位(第3位之前) 的所有项的值
# [1, 2, 3]print(a[5:])  # 显示列表a的第5位及以后的所有项的值
# [1, -1]print(a[-3:]) # 显示列表a的倒数第3位及以后的所有项的值
# [1, 1, -1]

打印列表中的某个值的索引(index):

a = [1,2,3,4,1,1,-1]
print(a.index(2)) # 显示列表a中第一次出现的值为2的项的索引
# 1

统计列表中某值出现的次数:

a = [4,1,2,3,4,1,1,-1]
print(a.count(-1))
# 1

List 排序

对列表的项排序:

a = [4,1,2,3,4,1,1,-1]
a.sort() # 默认从小到大排序
print(a)
# [-1, 1, 1, 1, 2, 3, 4, 4]a.sort(reverse=True) # 从大到小排序
print(a)
# [4, 4, 3, 2, 1, 1, 1, -1]

多维列表

创建二维列表
一个一维的List是线性的List,多维List是一个平面的List:

a = [1,2,3,4,5] # 一行五列multi_dim_a = [[1,2,3],[2,3,4],[3,4,5]] # 三行三列

索引
在上面定义的List中进行搜索:

print(a[1])
# 2print(multi_dim_a[0][1])
# 2

用行数和列数来定位list中的值。这里用的是二维的列表,但可以有更多的维度。

dictionary 字典

创建字典

如果说List是有顺序地输出输入的话,那么字典的存档形式则是无需顺序的, 我们来看一个例子:

在字典中,有key和 value两种元素,每一个key对应一个value, key是名字, value是内容。数字和字符串都可以当做key或者value, 在同一个字典中, 并不需要所有的key或value有相同的形式。 这样说, List 可以说是一种key为有序数列的字典。

a_list = [1,2,3,4,5,6,7,8]d1 = {'apple':1, 'pear':2, 'orange':3}
d2 = {1:'a', 2:'b', 3:'c'}
d3 = {1:'a', 'b':2, 'c':3}print(d1['apple'])     # 1
print(a_list[0])         # 1del d1['pear']      #删除del
print(d1)   # {'orange': 3, 'apple': 1}d1['b'] = 20      #加入元素
print(d1)   # {'orange': 3, 'b': 20, 'pear': 2, 'apple': 1}

字典存储类型

以上的例子可以对列表中的元素进行增减。在打印出整个列表时,可以发现各个元素并没有按规律打印出来,进一步验证了字典是一个无序的容器。

def func():return 0d4 = {'apple':[1,2,3], 'pear':{1:3, 3:'a'}, 'orange':func}
print(d4['pear'][3])    # a

字典还可以以更多样的形式出现,例如字典的元素可以是一个List,或者再是一个列表,再或者是一个function。索引需要的项目时,只需要正确指定对应的key就可以了。

import 模块

import 的各种方法

方法一:import time 指 import time 模块
方法二:import time as__下划线缩写部分可以自己定义,在代码中把time 定义成 t。
方法三:from time import time,localtime ,只import自己想要的功能.

from time import time, localtime
print(localtime())
print(time())
""""
time.struct_time(tm_year=2016, tm_mon=12, tm_mday=23, tm_hour=14, tm_min=41, tm_sec=38, tm_wday=4, tm_yday=358, tm_isdst=0)1482475298.709855
""""

方法四:from time import * 输入模块的所有功能

自己的模块

自建一个模块
这里写了另外一个模块,是计算五年复利本息的模块,代码如下:模块写好后保存在默认文件夹:balance.py

d = float(input('Please enter what is your initial balance: \n'))
p = float(input('Please input what is the interest rate (as a number): \n'))
d = float(d+d*(p/100))
year = 1
while year<=5:d = float(d+d*p/100)print('Your new balance after year:',year,'is',d)year = year+1
print('your final year is',d)

调用自己的模块
新开一个脚本,import balance

import balance""""
Please enter what is your initial balance:
50000  # 手动输入我的本金
Please input what is the interest rate (as a number):
2.3  #手动输入我的银行利息
Your new balance after year: 1 is 52326.45
Your new balance after year: 2 is 53529.95834999999
Your new balance after year: 3 is 54761.14739204999
Your new balance after year: 4 is 56020.653782067144
Your new balance after year: 5 is 57309.12881905469
your final year is 57309.12881905469
""""

模块存储路径说明:
在Mac系统中,下载的python模块会被存储到外部路径site-packages,同样,我们自己建的模块也可以放到这个路径,最后不会影响到自建模块的调用。

其他

下一篇

导出与导入

导出

如果你想尝试使用此编辑器, 你可以在此篇文章任意编辑。当你完成了一篇文章的写作, 在上方工具栏找到 文章导出 ,生成一个.md文件或者.html文件进行本地保存。

导入

如果你想加载一篇你写过的.md文件或者.html文件,在上方工具栏可以选择导入功能进行对应扩展名的文件导入,
继续你的创作。

莫烦Python[基础教程]相关推荐

  1. 莫烦python系列教程_莫烦python教程学习笔记——总结篇

    一.机器学习算法分类: 监督学习:提供数据和数据分类标签.--分类.回归 非监督学习:只提供数据,不提供标签. 半监督学习 强化学习:尝试各种手段,自己去适应环境和规则.总结经验利用反馈,不断提高算法 ...

  2. 莫烦 Python 基础 Set正则表达

    我的视频学习笔记 Set char_list = ['a', 'b', 'c', 'c', 'd', 'd', 'd'] # 通过set可以去除掉不同的东西 sentence = 'Welcome B ...

  3. CNN识别手写数字-莫烦python

    搭建一个 CNN识别手写数字 前面跟着莫烦python/tensorflow教程完成了神经网络识别手写数字的代码,这一part是cnn识别手写数字的 import tensorflow as tf f ...

  4. 【莫烦Python】Python 基础教程——学习笔记

    文章目录 本笔记基于p1-p29[莫烦Python]Python 基础教程 大家可以根据代码内容和注释进行学习. 安装 我的:python3.8+anaconda+VS code print() pr ...

  5. 【莫烦Python】机器要说话 NLP 自然语言处理教程 W2V Transformer BERT Seq2Seq GPT 笔记

    [莫烦Python]机器要说话 NLP 自然语言处理教程 W2V Transformer BERT Seq2Seq GPT 笔记 教程与代码地址 P1 NLP行业大佬采访 P2 NLP简介 P3 1. ...

  6. 【莫烦Python】Numpy教程

    目录 前言 1.numpy属性 2.numpy的array创建 3.numpy的基础运算 4.numpy的基础运算2 5.numpy的索引 6.numpy的array合并 7.numpy的array分 ...

  7. 莫烦python教程下载_Python 有哪些好的学习资料或者博客?

    Python是一门语法非常简单的语言,学习Python不需要花大量时间去学习它的语法,过一遍就行,主要靠实践.先给大家分享一个免费的Python的编程课,有Python的视频课程+代码实践课+辅导答疑 ...

  8. 【莫烦Python】Pandas教程

    目录 前言 1.Pandas vs Numpy 2.基本介绍 3.选择数据 4.设置值 5.处理丢失的数据 6.pandas导入导出 7.pandas合并concat 8.pandas合并merge ...

  9. 【莫烦Python】Matplotlib Python画图教程

    目录 前言 1.基本使用 1.1 基本用法 1.2 figure图像 1.3 设置坐标轴1 1.4 设置坐标轴2 1.5 Legend图例 1.6 Annotation标注 1.7 tick能见度 2 ...

最新文章

  1. matlab中任意两边之和大于第三边,无法赋值,左侧大小1*1,右侧1*3,代码报错,但是看不出来两边大小不相等啊...
  2. javaweb学习总结(四)——Http协议
  3. arraylist是如何扩容的?_ArrayList的源码分析
  4. php-5.6.26源代码 - opcode处理器,“函数调用opcode”处理器,如何调用扩展模块的函数...
  5. halcon直线标定板对相机标定的效果评估(对比矫正前后、对比标定板矫正效果)
  6. cordova 5.0版本说明
  7. oracle 11.2.4联机文档,ORACLE 11G 联机文档partition_extended_name的一个错误
  8. java学习(111):日期时间格式化
  9. java连接mysql数据库C3P0入门
  10. Chrome Version 19.0.1055.1 dev Flash Missing plug-in的修复
  11. java 解析 csv_在Java中将数据从CSV解析到数组
  12. kotlin 查找id_Kotlin程序查找Sphere的体积
  13. blast2go mysql_Blast2go本地化教程
  14. 目前最强开源人脸检测算法RetinaFace
  15. [leetcode]476. 数字的补数
  16. Dos命令查看端口占用
  17. android 自定义地图标注,Android高德地图自定义Markers【原创】
  18. 企事业单位 固定资产管理系统
  19. linux测试消息队列阻塞,Linux进程间通信:消息队列
  20. win+ubuntu双系统卸载ubuntu

热门文章

  1. 利用Tushare获取金融数据
  2. Linux版原型工具,Justproto:Linux下Axure的替代方案
  3. PID控制器(比例-积分-微分控制器)- I
  4. 电脑高清,查看电脑显示屏是高清还是标清
  5. 公交智能调度系统车载终端应用设计与实现
  6. EPM3128ATC100-10N
  7. 市场调研计算机配置单,PC机市场调研和选配方案.doc
  8. Object-C iOS纯代码布局 一堆代码可以放这里!
  9. android笔记:长按APP图标弹出快捷方式(shortcuts)
  10. 外链代发切勿用群发器