python入门语法结构_Python学习-基本语法入门,基础

1 变量和字符串

1.1 变量

变量就是编程中最基本的存储单位,变量会暂时性的存储你放进去的东西。

a = 1

1.2 字符串

字符串就是:“双引号之间的文字”、‘单引号之间的文字’、’’‘三引号之间的文字’’’。

字符串的加法和乘法

### 字符串的加法 ###

a = 'I '

b = 'love '

c = 'Python.'

print(a + b + c) # 结果:I love Python.

### 字符串的乘法 ###

a = "bang! "

print(a * 3) # 结果:bang! bang! bang!

字符串的分片与索引

从字符串中复制出一小段你要的长度,转存到另一个地方。分片获得的每个字符串可以看做是原字符串的一个副本。

str = "0123456789 abcdefg"

print(len(str)) # 字符串长度,结果为:18

print(str[0]) # 索引为0的字符串,结果为:0

print(str[-4]) # 索引为-4的字符串(字符串从右->左,索引为-1,向左一次减小),结果为:d

print(str[0:5]) # 索引为0-4的字符串,结果为:01234

print(str[12:20]) # 索引为12-18的字符串,结果为:bcdefg

print(str[12:]) # 索引为12-18(str的长度)的字符串,结果为:bcdefg

print(str[:7]) # 索引为0-6的字符串,结果为:0123456

字符串方法

split():通过给定的分隔符将一个字符串分割为一个列表。

注:若没有提供任何分隔符,程序默认将所有空格(空格、制表、换行等)作为分隔符

a = "www.baidu.com"

print(a.split('.')) # 结果:['www', 'baidu', 'com']

replace():查找替换

a = "0123456789 abcdefg"

print(str.replace(str[11:15], "*" * 4)) # 结果:0123456789 ****efg

strip():返回去除两侧空格的字符串,也可以指定需要去除的字符,将他们作为参数即可。

format():格式化字符串

print("{} it was better to just really enjoy {}.".format("Maybe", "life"))

print("{pos1} it was better to just really enjoy {pos2}.".format(pos1 = "Maybe", pos2 = "life"))

print("{0} it was better to just really enjoy {1}.".format("Maybe", "life"))

2. 函数与控制语句

2.1 函数

def function (arg1, arg2, ...):

return 'Something'

关键字:def 和 return;

闭括号后的冒号必不可少;

函数缩进后面的语句被称作语句块,缩进是为了表明语句和逻辑的从属关系,是Python最显著的特征之一。(需特别注意)

2.2 判断语句

逻辑判断:True 和 False

比较运算符:==、!=、、>=

:不同类型的对象不能使用“、<=、>=”进行比较,却可以使用“==”和“!=”;另外,浮点和整型虽是不同类型,但是不影响到比较运算。

成员运算符:in 和 not in

身份运算符:is 和 is not

布尔运算符:not、and、or

函数bool():

除了0、None和所有空的序列与集合(列表、字典、集合)布尔值为False之外,其他都为True。

if condition:

do sth

elif condition:

do sth

else:

do sth

2.3 循环语句

Python的循环语句包括for循环和while循环。

### for循环 ###

for item in iterable: # item表示元素,iterable是集合

do sth

### while循环 ###

while condition:

do sth

3 数据结构

Python四种数据结构:列表List、字典Dictionary、元组Tuple、和集合Set。

3.1 列表

列表特征为:

列表中的每个元素都是可变的;

列表中的元素是有序的,每一个元素都有一个位置;

列表可以容纳 Python 中的任何对象。

letters = ['a', 'b', 'c', 'd', 'e']

### 增 ###

letters.insert(0, 'f') # 在索引0处插入字符'f',结果为:['f', 'a', 'b', 'c', 'd', 'e']

letters[1:1] = "g" # 在索引1到1处插入字符串"g",结果为:['f', 'g', 'a', 'b', 'c', 'd', 'e']

### 删 ###

letters.remove("f") # 删除字符串"f",结果为:['g', 'a', 'b', 'c', 'd', 'e']

del letters[0:2] # 删除索引0-1的值,结果为:['b', 'c', 'd', 'e']

### 查 ###

print(letters[2:]) # 与字符串索引类似,结果为:['d', 'e']

3.2 字典

字典特征为:

字典中数据以键值对的形式出现;

键不可重复,值可重复;

键不可变,值可变

dict = {

'A':'a',

'B':'b',

'C':'c',

'C':'cc' # 字典中的键值不会有重复

}

print(dict) # 结果为:{'A': 'a', 'B': 'b', 'C': 'cc'}

### 增加 ###

dict['D'] = 'd'

print(dict) # 结果为:{'A': 'a', 'B': 'b', 'C': 'cc', 'D': 'd'}

#### update()增加 ###

dict.update({'E':'e', 'F':'f'})

print(dict) # 结果为:{'A': 'a', 'B': 'b', 'C': 'cc', 'D': 'd', 'E': 'e', 'F': 'f'}

3.3 元组

元组可理解为一个稳固版的列表,不可进行修改。

letters = ('a', 'b', 'c', 'd', 'e', 'f', 'g')

3.4 集合

集合中的每一个元素都是无序的、不重复的任意对象。

fruits = ['grape', 'apple', 'grape']

print(set(fruits)) # 结果:{'grape', 'apple'}

3.5 数据结构的一些技巧

3.5.1 多重循环

# 同时循环两个列表,a为num中的元素、b为str中的元素

for a,b in zip(num, str):

do sth

3.5.2 推导式

### for循环 ###

a = []

for i in range(1, 11):

a.append(i)

print(a) # 结果:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

### 写为推导式 ###

b = [i for i in range(1, 11)] # [item for item in iterable]

print(b)

列表解析式不仅非常方便,且在执行效率上要远胜前者。其他示例如下所示:

### 创建列表 ###

a = [i**2 for i in range(1, 11)]

b = [j for j in range(1, 11) if j % 2 == 0] # 取出1-10之间的偶数

### 创建字典 ###

c = {i:i+1 for i in range(4)}

d = {i:j for i,j in zip(range(6), 'abcdef')}

# 结果:{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f'}

4 文件操作

打开文件:文件名name为唯一强制参数,然后返回一个文件对象。模式mode和缓冲buffering为可选参数。在Python文件操作中,mode参数的输入是有必要的,而buffering使用较少。

open(name[,mode[,buffering]])

open()函数中模式参数的常用值有:

描述

‘r’

读模式

‘w’

写模式

‘a’

追加模式

‘b’

二进制模式(可添加到其他模式中使用)

‘+’

读/写模式(可添加到其他模式中使用)

读写文件:read()和write()

关闭文件:close()

f = open('C:/test.txt', 'w+')

f.write("Hello World")

f.close()

f1 = open('C:/test.txt', 'r')

content = f1.read()

f1.close()

print(content)

5 面向对象

Python作为一个面向对象的语言,很容易创建一个类和对象。

5.1 定义类

类是用来描述具有相同属性和方法的对象集合。

class Bike:

# 类属性

compose = ['frame', 'wheel', 'pedal']

# 类方法

def use(self):

print('you are riding')

# 魔术方法 _init_(),创造实例时自动执行

def __init__(self):

self.other = 'basket'

bike = Bike()

bike2 = Bike()

print(bike.compose) # 打印实例属性

print(bike2.compose)

bike2.use() # 调用实例方法

print(bike2.other) # 魔术方法中初始化变量other

bike2.compose = 'basket' # 改变实例属性

print(bike2.compose)

5.2 继承类

继承5.1中的Bike类。

class ShareBike(Bike):

def cost(self, hour):

print('You spent {}.'.format(hour * 2))

bike = ShareBike()

print(bike.other)

bike.cost(2)

参考:

《从零开始学Python网络爬虫》 罗攀 蒋仟

《编程小白的第1本Python入门书》 侯爵

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值