Python学习总结一:基础篇

Python学习总结一:基础篇

<说明>
操作平台:DeepinLinux OS 15.7
版本选择:Python3.6.5
适用人群:有基本的计算机基础

0.Python3安装使用

Linux默认安装是Python2.x,在控制台输入代码查看是否安装了Python3:

$ python3
Python 3.6.5 (default, May 11 2018, 13:30:17) 
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

若出现这个结果,说明已经安装成功,否则要自行安装:

$ sudo apt-get install python3

使用和退出

# 使用
$ python3
# 退出
Ctrl + D 或者 exit()

1.Python规则

  • 1.用4个空格缩进(或设定好一个tab键为4个空格)
  • 2.不要混用空格和制表符
  • 3.函数之间空一行,类之间空两行
  • 4.运算符周围1个空格
  • 5.字典,元组,列表逗号后1个空格;字典冒号后1个空格
  • 6.注释符#后1个空格
  • 7.不要出现多余的空格,用缩进区分语句块

2.第一个Python3文件

su - root	# 输入密码后进入root模式
vim xx.py	# 创建.py文件
chmod +x xx.py    # 赋予该文件执行权限
./xx.py    # 执行文件

或者用记事本或者其他编辑器创建保存.py文件
进入该文件目录执行
python3 xx.py

文件格式:

#!/usr/bin/env python3   # 调用Python的解释器
python code
...

3.变量和简单的数据类型

3.1变量命名

变量命名规则

  • 变量名只能包含数字、字母和下划线,且不能以数字开头
  • 不能使用Python关键字和函数名作为变量名
  • 慎用大小写的L和O,可能会误认为1和0
  • 变量名应简短具有描述性

查看所有关键字

$ python3
>>> help()
help> keywords

False               def                 if                  raise
None                del                 import              return
True                elif                in                  try
and                 else                is                  while
as                  except              lambda              with
assert              finally             nonlocal            yield
break               for                 not                 
class               from                or                  
continue            global              pass   

3.2字符串

用单引号‘’或双引号”“引起来的内容就是字符串

3.2.1常用方法

title()将首字母大写、upper()全部大写、lower()全部小写,例如:

>>> name = "deemo liNUX"
>>> name.title()
'Deemo Linux'
>>> name.upper()
'DEEMO LINUX'
>>> name.lower()
'deemo linux'

3.2.2字符串的连接

使用加号+连接即可,例如:

>>> one = "deemo"
>>> two = "linux"
>>> one + two
'deemolinux'

3.2.3避免错误

单引号里有单引号,双引号里有双引号,如:

>>> name = 'xyp'gg'
  File "<stdin>", line 1
    name = 'xyp'gg'
                 ^
SyntaxError: invalid syntax
>>> name = "xyp"gg"
  File "<stdin>", line 1
    name = "xyp"gg"
                 ^
SyntaxError: invalid syntax

两者混合使用即可,避免歧义,如:

>>> name = "xyp'gg"
>>> print(name)
xyp'gg

3.3数字

3.3.1整数

可进行加减乘除乘方等常规运算,如:

>>> 3 + 2
5
>>> 3 - 2
1
>>> 3 * 2
6
>>> 3 / 2
1.5
>>> 3 ** 2
9
>>> 3 ** 3
27

3.3.2浮点数

带小数点的数称为浮点数

3.3.3类型转换

使用str()避免类型错误,如:

>>> age = 22
>>> print("Your age is:" + age)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int
# 转换后
>>> print("Your age is:" + str(age))
Your age is:22

3.3.4取模取余

divmod(number1, number2) 返回两个结果,第一个是number1 / number2
第二个是number1 % number2

>>> print("div={}, mod={}".format(*divmod(3, 2)))
div=1, mod=1

4.注释

使用#进行注释,注释要简明扼要,不能不注释,但不要说太多废话

5.列表

5.1列表简介

5.1.1列表是什么

列表由一系列按特定顺序排列的元素组成,如

>>> namelist = ['deemo', 'linus', 'mark']
>>> print(namelist)
['deemo', 'linus', 'mark']
# 列表索引从0开始,访问列表
>>> namelist[0]
'deemo'
>>> namelist[2]
'mark'
>>> print("My name is " + namelist[0].title() + "!")
My name is Deemo!

5.1.2修改添加删除元素

# 修改
>>> namelist[2] = 'jack'
>>> namelist
['deemo', 'linus', 'jack']
# 添加(在末尾添加)append()
>>> namelist.append('xiye')
>>> namelist
['deemo', 'linus', 'jack', 'xiye']
# 插入(在指定位置添加,0是下标)insert()
>>> namelist.insert(0, 'uzi')
>>> namelist
['uzi', 'deemo', 'linus', 'jack', 'xiye']
# 删除指定下标的元素 del
>>> del namelist[0]
>>> namelist
['deemo', 'linus', 'jack', 'xiye']

insert(下标, 元素) 实际上是在原来列表下标位置上插入新数据
而原来那个位置往后的数据都向后移动了一位

问题来了,del删除后这个值就消失了,如果想用这个值怎么办?
使用pop()即可,把pop弹出的值赋给新变量,例如:

>>> namelist.pop()
'xiye'    # 弹出后也就相当于删除了
>>> namelist
['deemo', 'linus', 'jack']
>>> name_1 = namelist.pop()
>>> name_1
'jack'  
>>> print("My name ever used is:" + name_1)
My name ever used is:jack
>>> namelist
['deemo', 'linus']

pop(下标):弹出指定位置的值

根据元素删除值:remove()

>>> namelist.remove('deemo')
>>> namelist
['linus']

5.1.3组织列表

sort():永久性排序(列表元素是排序后的顺序)

>>> numbers = [1, 3, 2, 4]
>>> numbers
[1, 3, 2, 4]
>>> numbers.sort()
>>> numbers
[1, 2, 3, 4]

sorted():临时性排序(列表元素还是原来的顺序)

>>> numbers = [1, 3, 2, 4]
>>> numbers
[1, 3, 2, 4]
>>> sorted(numbers)
[1, 2, 3, 4]
>>> numbers
[1, 3, 2, 4]

反转列表元素,reverse()

>>> numbers
[1, 3, 2, 4]
>>> numbers.reverse()
>>> numbers
[4, 2, 3, 1]

列表长度,len()

>>> len(numbers)
4

5.1.4避免错误

使用列表时要避免索引错误,是从0开始

5.2列表操作

5.2.1遍历列表

常规操作

namelist = ['alan', 'judis', 'carl']
for name in namelist:
	print(name)

遍历列表同时输出索引值 enumerate()

a = [1, 2, 3]
for i, j in enumerate(a):
	print(i, j)

同时遍历两个列表 zip()

a = [1, 2, 3]
b = ['a', 'b', 'c']
for x, y in zip(a, b):
	print("{} ---- {}".format(x, y))

5.2.2创建数值列表

使用函数range()和list()创建

>>> number = list(range(1, 6))
>>> number
[1, 2, 3, 4, 5]

例子:生成列表数值的平方值列表

# 创建空列表,用于存放平方值数据
square = []
for value in range(1, 11):
	square.append(value ** 2)
print(square)

range(start, stop, step)
start:初始值
stop:结束值,但不包括
step:步长

# 数值列表简单操作
>>> min(number)
1
>>> max(number)
5
>>> sum(number)
15

5.2.3列表切片

>>> a = [1, 3, 2, 4, 5]
>>> a
[1, 3, 2, 4, 5]
# 取出a[0]~a[2]
>>> a[: 3]
[1, 3, 2]
# 取出a[0]~a[1]
>>> a[0: 2]
[1, 3]
# 取出a[1]~a[3]
>>> a[1: 4]
[3, 2, 4]
# 取出后三位 也就是a[-3]~a[-1]  列表最后一位是a[-1]
>>> a[-3:]
[2, 4, 5]

5.2.4复制列表

定义新列表,把需要复制的列表直接赋值给新列表即可

new_list = old_list[]

6.元组

元组和列表不同处在于:

  • 元组用() 列表用[]
  • 元组内元素一旦定义将不可修改,必要时可以重新给元组赋值
  • 元组只有一个元素是末尾也要有,
>>> a = (1, 2, 3)
>>> a
(1, 2, 3)
>>> a[0] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

其他操作和列表类似,只是没有列表灵活,适合用于不变的场景

7.if、while、for、input、print语句

7.1if、while、for语法

# 1.if语句
if exp:
	do this
elif exp:      # else if
	do this
else:
	do this
# 2.while语句
while condition:
	stat1
	stat2
	...
# 3.for语句
for x in a:
	stat
	...

7.2input()方法

input():作用是暂停输出,等待用户输入字符串,存储在变量内以便使用,例如:

name = input("Enter your name:")
age = int(input("Enter your age:"))  # age是整数int类型

7.3while中循环操作

while循环中break退出循环,continue继续循环,例如:

#!/usr/bin/env python3
mess = "\nI will repeat your words those you enter,"
mess += "\nor you can enter 'quit' to quit:"

while 1:   
    message = input(mess)
    print(message)
    
    if message != "quit":
        continue
    else:
        break

结果:

$ python3 message_while.py 

I will repeat your words those you enter,
or you can enter 'quit' to quit:Xypgg
Xypgg

I will repeat your words those you enter,
or you can enter 'quit' to quit:quit
quit

7.4print()方法

print(str)   # 常规输出
print(str, end='***')  # 每次输出以end后面的内容结尾
print()   # 再带换行效果,单独使用相当于换一行
print("@" * 40)  # 输出40个@

注: str.format() 格式化函数
字符串格式化:将`{}`中的内容替换为format中的参数
数字格式化:
- {:.2f} 2位精度的浮点数
- {:5d} 5字符宽的整数
- {:7.2f} 7字符宽,2位精度的浮点数

8.字典

8.1字典定义

字典是一系列键-值对组成的数据结构,键与值相关联,可以使用键来访问相关的值。

与键相关的值可以是数字、字符串、列表甚至是字典。

字典用{键: 值, 键: 值, ....}表示,例如:

>>> user = {'contury': 'china', 'language': 'chinese', 'color': 'yellow',}
>>> user['color']
'yellow'

8.2字典操作

8.2.1添加元素

>>> user['eatting'] = 'chopsticks'
>>> user
{'contury': 'china', 'language': 'chinese', 
 'color': 'yellow', 'eatting': 'chopsticks'}

8.2.2修改元素

>>> user['contury'] = 'England'
>>> user
{'contury': 'England', 'language': 'chinese', 
 'color': 'yellow', 'eatting': 'choopstiks'}

8.2.3删除元素

>>> del user['eatting']   # del
>>> user
{'contury': 'England', 'language': 'chinese', 'color': 'yellow'}

8.2.4遍历所有键-值对

使用方法items()

>>> user
{'contury': 'England', 'language': 'chinese', 'color': 'yellow'}
>>> for key, value in user.items():
...     print("Key:" + key)     
...     print("Value:" + value)
... 
Key:contury
Value:England
Key:language
Value:chinese
Key:color
Value:yellow

8.2.5遍历所有键

使用方法keys()

>>> for key in user.keys():
...     print("Key:" + key)
... 
Key:contury
Key:language
Key:color

8.2.6遍历所有值

使用方法values()

>>> for value in user.values():
...     print("Value:" + value)
... 
Value:England
Value:chinese
Value:yellow

8.2.7列表嵌套字典

>>> user_1 = {'color': 'white',}
>>> user_2 = {'color': 'yellow',}
>>> user_3 = {'color': 'black',}
>>> user = [user_1, user_2, user_3]
>>> for man in user:
...     print(man)
... 
{'color': 'white'}
{'color': 'yellow'}
{'color': 'black'}

8.2.8字典嵌套列表

>>> user = {'language': ['Chinese', 'English', ], 'color': ['yellow'], }
>>> user
{'language': ['Chinese', 'English'], 'color': ['yellow']}
>>> for x, y in user.items():
...     print("\nKey:" + x)
...     for z in y:
...			print("\t" + z)
... 
Key:language
	Chinese
	English

Key:color
	yellow

8.2.9字典嵌套字典

#!/usr/bin/env python3
user = {
    'xiaozhang': {
        'color': 'yellow',
        'language': 'Chinese',
        },
    'xiaoxi': {
        'color': 'white',
        'language': 'English',
        }
    }
for name, info in user.items():
    print("\nName:" + name)
    for x, y in info.items():
        print("\t" + x + ":" + y)

结果是:

$ python3 markdown_user.py 

Name:xiaozhang
	color:yellow
	language:Chinese

Name:xiaoxi
	color:white
	language:English

小结

Python基础总结内容有:

  • Python3的安装与使用
  • 变量和数据类型
  • 列表
  • 元组
  • 字典
  • if、for、while、input、print语句
posted @ 2018-10-24 20:49  deemolinux  阅读(461)  评论(0编辑  收藏  举报