python学习(一):基础知识整理

python学习(一):基础知识整理

学习书籍: 《python编程:从入门到实践》

使用IDE: pycharm 2021.3

使用python版本: Anaconda Python 3.9

python官网:

Welcome to Python.org

参考学习信息:

jackfrued/Python-Core-50-Courses: Python语言基础50课 (github.com)

jackfrued/Python-100-Days: Python - 100天从新手到大师 (github.com)

一、一些说明

这篇博客主要是根据书籍的(二——九章节)进行整理,但由于书籍内容较为简单易懂,因此后续博客的python学习内容将根据以上github的两个repo内容进行学习。且内容主要是python与其他语言(Java,C++)不同的地方,或者是相关的语法糖。

本篇博客的内容主要包括python的基础知识展示,包括变量、字符串、数值等简单数据类型,列表、元组、字典等重要数据类型,以及分支语句,循环语句和对函数和类的简单介绍等。后续博客将从对函数进阶的知识开始写起。

二、变量和简单数据类型

2.1 变量

2.1.1 何为变量

1
2
3
4
message="hello"
print(message)
message='wiwi'
print(message)

如上图,执行会打印hello,那么可以理解为meesage存储了后面字符串的信息,且这个信息可以被修改,python始终保存变量的最新值,打印时会将当前存储的信息打印出来。

2.1.2 变量命名的部分规则

  • 变量名只包括字母、数字、下划线,以字母或下划线打头
  • 变量名不含有空格,不能用python关键字和函数名作为变量名
  • 变量名应简洁而具有描述性

2.1.3 变量命名错误

命名错误时,程序会给出相应的错误信息。

1
2
3
4
5
6
7
message="chekc"
print(messag)

Traceback (most recent call last):
File "D:\python_learn\booktest\main.py", line 2, in <module>
print(messag)
NameError: name 'messag' is not defined

2.2 字符串

字符串是一系列字符,也是python的一种数据类型,往往用“,’双引号或单引号括起来

以下是一些基本的字符串操作:

  • str.title(),单词首字母大写
  • str.lower() str.upper(),单词转换为大写(小写)
  • str1+str2,字符串拼接
  • str.strip(),去除两端空白符

2.3 数字

包括整数,浮点数,数字运算一般可以在终端直接进行运行。

2.3.1 使用str()避免类型错误

1
2
3
4
age=23
message="heloo"+age //错误写法
message="heloo"+str(age) //正确写法
print(message)

如上图直接执行会报类型错误,由于程序无法判断是将age理解为数值还是字符串

2.4 注释

使用#作为注释标记,该标记之后内容不会被解释器读取。

2.5 python之禅

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
>>> import this
The Zen of Python, by Tim Peters

"""
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""

三、列表简介

3.1列表是什么

列表是由一系列按特定顺序排列的元素组成。用方括号([])表示列表,用,分隔元素。

1
2
bicycles=['aa','bb','cc','dd']
print(bicycles)

基本用法:

  • 提取列表元素:bicycles[i]即可取出第i个项
  • 索引从0,而不是1开始计数
  • 索引可以为负数,-1代表倒数第一个元素,以此类推。

3.2 修改、添加和删除元素

1.修改:

1
a[0]=3

2.添加,删除:

1
2
3
4
5
6
7
8
a=['1','2','3']

a.append(4) //列表末尾添加元素
a.insert(0,4) //列表指定索引位置插入元素

del a[0] //删除第一个元素
k=a.pop() //弹出最后一个元素,也可以加索引
a.remove('3') //删除为该值的第一个指定元素

3.3 组织列表

排序,长度:

1
2
3
4
5
6
7
a=['abc','bca','cba']
a.sort() //永久升序排序
a.sort(reverse=True) //永久降序排列
sorted(a) //临时排序,不改变原列表

a.reverse() //倒序排列
len(a) //返回长度

四、操作列表

4.1 遍历列表

1
2
3
magicians=['alice','bob','kavin']
for magician in magicians:
print(magician)

4.2 创建数值列表

1
2
3
4
5
6
7
8
9
10
11
for value in range(1,5):
print(value)
digits=list(range(1,5)) #生成1-4的列表
even_numbers=list(range(2,11,2)) #指定步长1-10内偶数
#数值列表处理
min(digits)
max(digits)
sum(digits)

#列表解析
squares=[value**2 for value in range(1,11)]

4.3 使用列表的一部分

4.3.1 切片

1
2
3
4
5
6
7
8
digits=list(range(1,5))    #生成1-4的列表
print(digits[0:3]) #打印前3个元素
print(digits[:3]) #打印前3个元素,自动从最前开始
print(digits[0:]) #打印全部元素,自动到最后结束
print(digits[-3:]) #打印倒数3个元素

#复制列表
dii=digits[:]

4.4 元组

不可变列表被称为元组

1
dimen=(200,50)  #定义元组

五、if语句

条件判断语句:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
cars=['aua','bub','cuc']
for car in cars:
if car == 'aua':
print(car.upper())
elif car=='bub':
print(car.lower())
else:
print(car.title())

if cars[0]=='happy' and cars[1]=='bub': //且
pass

if 'aua' in cars:
pass

六、字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#创建字典
alien_0={'color': 'green','points': 5}
#访问字典
print(alien_0['color'])
print(alien_0['points'])
#增加键值对
alien_0['x_pos']=0
#删除键值对
del alien_0['x_pos']
#遍历字典
for key,value in alien_0.items():
pass

#遍历键
for key in languages.keys():
pass

字典是一系列键——值对,每个键和一个值相对应,使用键访问对应的值。

使用{}表示字典

七、用户输入和while循环

使用input接受用户输入

1
2
3
4
5
6
7
8
9
10
11
message=input("enter your name: ")
print(message)

#处理数字输入,将字符串转化为数字
age=input("how old are you? ")
age=int(age)

#while循环
a=1
while a<=5:
a+=2

使用break可以退出循环,continue直接跳转到该循环的开头判断处。

八、函数

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
32
33
34
35
36
37
38
39
40
41
#函数定义
def greet():
"""hello"""
print("hello")

#传递信息
def greet2(name):
print("hello"+name)

#函数传递参数有多种实参
#1.位置实参:
def a(a,b,c,d):
pass
a(1,2,3,4) #按位置顺序对应上方的参数

#2.关键字实参:
def describe_ani(type,name):
pass
describe_ani(type='dog',name='harry') #以键值对形式传参

#3.默认值,形参列表中一般先列出无默认值,再列出有默认值
def describe_ani(type='dog',name):
pass
describe_ani(name='harry') #使用默认值

#4.返回值
def get_formatted_name(first_name, last_name):
full_name=first_name+' '+last_name
return full_name.title()
musician=get_formatted_name('jimi','page')

#5.可变位置参数,需要放在前几种情况之后
def cook(*cookies):
for cookie in cookies:
print("cookie")
cook('apple','banana')

#6.可变关键字参数,需要放在前几种情况之后
def hello(**hellos):
pass
hello(apple='apple',banana='banana')//任意个数

九、类

面向对象编程具有无与伦比的威力

1
2
3
4
5
6
7
8
9
#类的定义例子
class Dog():
def __init__(self,name,age):
self.name=name
self.age=age
def sit(self):
print(self.name.title()+"is now sitting!")
def roll_over(self):
print(self.name.title()+" rooled over!")

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!