第二课主要内容如下:

  • 代码格式
  • 基本语法
  • 关键字
  • 循环判断
  • 函数
  • 容器
  • 面向对象
  • 文件读写
  • 多线程
  • 错误处理

代码格式

syntax基本语法

 a = 1234
print(a)
a = 'abcd'
print(a) try:
print(b)
except Exception as e:
print(e) a = [1, 2, 3 , 4] def func(a):
a[0] = 2 func(a)
print(a) try:
# Python 2.x 支持
print(100, 200, 300)
except Exception as e:
print(e)
 1234
abcd
name 'b' is not defined
[2, 2, 3, 4]
100 200 300

condition_and_loop 循环判断

 score = 80
if score > 90:
print('A')
elif score > 70:
print('B')
elif score >= 60:
print('C')
else:
print('D') total = 0
i = 1
while i <= 100:
total += i
i += 1 # 没有++i或者--i
print(total) '''
for循环只作用于容器!!!
没有这种写法:
for (i = 0; i < 100; ++i):
# TODO
上面这种循环只能用while实现
''' i = 0
while i < 3:
j = 0
while j <= 3:
if j == 2:
j += 1
continue # 又去了while j <= 3
print(i, j)
j += 1
i += 1
 B
5050
0 0
0 1
0 3
1 0
1 1
1 3
2 0
2 1
2 3

func函数

def hello(who = 'world'):
print('hello %s!' % (who)) hello()
hello('sea') # f(x) = x * 5 + 100
# g(x) = x * 5; f(x) = x + 100
# => f(g(x)) = x * 5 + 100
def g(x):
return x * 5
def f(gf, x):
return gf(x) + 100
print(f(g, 100))
print(f(lambda x: x * 5, 100)) def f(gf, x, y):
return gf(x, y) + 100
print(f(lambda x, y: x * y, 100, 200)) #输出结果
hello world!
hello sea!
600
600
20100

ct_list数组

# list就是数组
li = [1, 2, 3, 4, 5]
# 遍历
for i in li:
# print(i)
pass
# 用range模拟for (i = 0; i < x; ++i)
# range(x) => [0, x - 1]
# range(x, y) => [x, y - 1]
# range(x, y, z) => [x, x + z,..., < y]
for i in range(len(li)):
# print(li[i])
pass for i in range(1, 10, 2):
print(i) #输出结果
1
3
5
7
9
 # 负数索引
print(li[-1])
print(li[-2]) # 负数step的range => [x, x - z, ..., > z]
for i in range(3, -1, -1):
print(i)
 #输出结果
5
4
3
2
1
0
 # 添加元素
li = []
li.append(1)
li.append(2)
li.append('abc')
li.append(['d', 'e', 'f'])
print(li) # 按元素添加数组
li = [1, 2]
li_2 = [3, 4, 5]
# 我们想要[1, 2, 3, 4, 5]
# li.append(li_2) => [1, 2, [3, 4, 5]]
li.extend(li_2)
print(li) # 删除元素
li.pop() # => [1, 2, 3, 4]
print(li)
li.pop(2) # => [1, 2, 4]
print(li) #输出结果
[1, 2, 'abc', ['d', 'e', 'f']]
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
[1, 2, 4]
 li = [5, 8, 7, 4, 2, 3]
li.sort()
print(li)
# lambda帮助排序
li = [[5, 2], [3, 8], [2, 11], [7, 6]]
# li.sort(key = lambda x: x[0]) # 参数名字
# 与lamda等价写法
def item_key(x):
return x[0]
li.sort(key = item_key)
print(li) #输出结果
[2, 3, 4, 5, 7, 8]
[[2, 11], [3, 8], [5, 2], [7, 6]]

ct_tuple只读数组

 # 只读数组
tp = (1, 2, 3)
try:
tp[0] = 100
except Exception as e:
print(e)

ct_set没有重复元素的数组

 s = set([1, 2, 2, 3, 3, 4, 5])
print(s)
s = set((2, 3, 4, 5, 6, 2, 1, 9))
print(s) #输出
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6, 9}

ct_dict 字典(哈希表)

 # key<->value对应的hash表
di = {'k1': 'v1', 'k2': 'v2'}
di['k3'] = 'v3'
di['k4'] = 'v4' for k in di:
print(di[k]) for k, v in di.items():
print(k, v) #输出
v3
v4
v2
v1
k3 v3
k4 v4
k2 v2
k1 v1

slice数组切片

 # [1, 2, 3, 4, 5]
# => [1, 2, 3]
# => [3, 4]
li = [1, 2, 3, 4, 5]
li_0_2 =li[0:3] # 0 <= ? < 3
# 等价li[:3]
print(li_0_2)
# [start, end, step] => [start, start + step, ..., < end]
# start默认是0,end默认-1,step默认1
li_last_3 = li[-1:-4:-1]
print(li_last_3) # 直接用切片反转数组
print(li[::-1])
print(li[-2::-1]) # 切片是复制
li_0_2[-1] = 100
print(li) #输出
[1, 2, 3]
[5, 4, 3]
[5, 4, 3, 2, 1]
[4, 3, 2, 1]
[1, 2, 3, 4, 5

list_string字符串与数组的关系

 s = 'abcdefg'
try:
str[0] = 'x'
except Exception as e:
print(e) # 修改字符串
li = list(s)
# print(li)
li[0] = 'x'
s = ''.join(li)
print(s)
s = '-'.join(li)
print(s) # 切割
s = 'abc,def,ghi'
p1, p2, p3 = s.split(',')
print(p1, p2, p3) # 下标访问和切片
s = 'abcdefg'
print(s[0], s[-1])
print(s[2:5]) #输出
'type' object does not support item assignment
xbcdefg
x-b-c-d-e-f-g
abc def ghi
a g
cde

obj面向对象

 # 用type查看对象类型
print(type([1, 2, 3, 4]))
print(type('abcd'))
print(type({1:2, 2:3})) # 用dir查看属性和方法
print(dir(list))
 <class 'list'>
<class 'str'>
<class 'dict'>
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
 class Clazz(object):
# self参考C++的this指针!
def __init__(self, x, y):
self.x = x
self.y = y # 声明成员函数的时候,第一个参数一定是self,不要忘记!
def display(self):
print(self.x, self.y) print(type(Clazz))
clz = Clazz(100, 200)
clz.display() # => display(clz) class Base:
def run(self):
print('Base::run') class Tom(Base):
def run(self):
print('Tom::run') t = Tom()
print(isinstance(t, Base))
t.run()
<class 'type'>
100 200
True
Tom::run
 def run(runner):
runner.run() class R1:
def run(self):
print('R1::run') class R2:
def run(self):
print('R2::run') run(R1())
run(R2()) #输出
R1::run
R2::run

file_rw文件读写

 # 打开文件操作可能失败,异常处理后不会造成资源泄露等情况
with open('text.txt', 'w') as f:
f.write('''1234
abcd
nefgh''') with open('text.txt', 'rb') as f:
print(f.read()) with open('text.txt') as f:
for line in f.readlines():
print(line.strip()) #输出
b'1234\r\n abcd\r\n nefgh'
1234
abcd
nefgh

threads多线程

 import threading

 def thread_func(x):
# 自己加sleep和其它复杂操作看效果
print('%d\n' % (x * 100)) threads = []
for i in range(5):
threads.append(threading.Thread(target = thread_func, args = (100, ))) for thread in threads:
thread.start() for thread in threads:
thread.join() #输出
10000 10000 10000 10000 10000

error_handling错误和异常处理

 # 错误处理

 try:
r = 10 / 0
except ZeroDivisionError as e:
print(type(e))
print(e)
finally:
# 主要防止资源泄露(服务端。客户端一般不会资源泄露)!
print('Always come here.') #输出
<class 'ZeroDivisionError'>
division by zero
Always come here.
 import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

七月在线爬虫班学习笔记(二)——Python基本语法及面向对象的更多相关文章

  1. 七月在线爬虫班学习笔记(五)——scrapy spider的几种爬取方式

    第五课主要内容有: Scrapy框架结构,组件及工作方式 单页爬取-julyedu.com 拼URL爬取-博客园 循环下页方式爬取-toscrape.com Scrapy项目相关命令-QQ新闻 1.S ...

  2. 七月在线爬虫班学习笔记(六)——scrapy爬虫整体示例

    第六课主要内容: 爬豆瓣文本例程 douban 图片例程 douban_imgs 1.爬豆瓣文本例程 douban 目录结构 douban --douban --spiders --__init__. ...

  3. python学习笔记(二):python数据类型

    上一篇博客写了python的入门和简单流程控制,这次写python的数据类型和各种数据类型的内置方法.一.数据类型是什么鬼?计算机顾名思义就是可以做数学计算的机器,因此,计算机程序理所当然地可以处理各 ...

  4. Java学习笔记二十九:一个Java面向对象的小练习

    一个Java面向对象的小练习 一:项目需求与解决思路: 学习了这么长时间的面向对象,我们只是对面向对象有了一个简单的认识,我们现在来做一个小练习,这个例子可以使大家更好的掌握面向对象的特性: 1.人类 ...

  5. Java基础学习笔记二 Java基础语法

    注释 注释用来解释和说明程序的文字,注释是不会被执行的. 单行注释 //这是一条单行注释 public int i; 多行注释 /* 这是 * 一段注释, * 它跨越了多个行 */ public vo ...

  6. Java基础学习笔记五 Java基础语法之面向对象

    面向对象 理解什么是面向过程.面向对象 面向过程与面向对象都是我们编程中,编写程序的一种思维方式.面向过程的程序设计方式,是遇到一件事时,思考“我该怎么做”,然后一步步实现的过程.例如:公司打扫卫生( ...

  7. Html学习笔记(二) 简单标签

    标签的重点 标签的用途 标签在浏览器中的默认样式 <body>标签: 在网页上显示的内容 <p>标签: 添加段落 <hx>标签: 添加标题 标签一共有6个,h1.h ...

  8. 风变编程笔记(二)-Python爬虫精进

    第0关  认识爬虫 1. 浏览器的工作原理首先,我们在浏览器输入网址(也可以叫URL),然后浏览器向服务器传达了我们想访问某个网页的需求,这个过程就叫做[请求]紧接着,服务器把你想要的网站数据发送给浏 ...

  9. python3.4学习笔记(二十六) Python 输出json到文件,让json.dumps输出中文 实例代码

    python3.4学习笔记(二十六) Python 输出json到文件,让json.dumps输出中文 实例代码 python的json.dumps方法默认会输出成这种格式"\u535a\u ...

随机推荐

  1. 关于spark写入文件至文件系统并制定文件名之自定义outputFormat

    引言: spark项目中通常我们需要将我们处理之后数据保存到文件中,比如将处理之后的RDD保存到hdfs上指定的目录中,亦或是保存在本地 spark保存文件: 1.rdd.saveAsTextFile ...

  2. ASP.NET MVC CSRF (XSRF) security

    CSRF(Cross-site request forgery)跨站请求伪造,也被称为“One Click Attack”或者Session Riding,通常缩写为CSRF或者XSRF,是一种对网站 ...

  3. cookie,session,fileter,liscen

    会话技术: 会话:一次会话中发生多次请求和响应 一次会话:从浏览器的打开到关闭 功能:在会话的过程中 ,可以共享数据 cookie:客户端的会话技术session:服务端的会话技术 Cookie:小饼 ...

  4. 4、static

    static (静态的),用来修饰成员. 一.特点: 1.被修饰的方法或变量随着类的加载而加载 2.优先于对象存在 3.被所有的对象共享 4.除了可以被对象调用还可以被类名直接调用 二.类变量.成员变 ...

  5. Response.End ,Response.Redirect、Server.Transfer 引发 “正在中止线程”异常的问题

    google后得知:Response.End 方法终止页的执行,并将此执行切换到应用程序的事件管线中的 Application_EndRequest 事件,同时抛出ThreadAbortExcepti ...

  6. form 表单提交、后台的统一处理

    配合 form 提交后台 /ajaxSubmit/Submit等通过form提交springMvc下@RequestMapping("/save_oaflow_init")//Re ...

  7. 15、TypeScript-函数

    1.参数和返回值可以指定类型 2.可选参数:在参数上加上?,表示可选的,可传可不传 3.默认参数:如果你不传参数,默认为20,如果你传参,就是你传的参数 4.剩余参数:会把传进来的实参变成一个数组,可 ...

  8. 算法:输出一个整数(不用ToString方法)

    1.递归实现 static void Main(string[] args) { Console.WriteLine("Pls input a number:"); int p = ...

  9. hello2 源码分析

    1.GreetingServlet.java(问候页面): /** * Copyright (c) 2014 Oracle and/or its affiliates. All rights rese ...

  10. FastCGI 进程意外退出造成500错误

    在一台新服务器上,安装新网站,之前只放至了一个网站.是服务器商配置好的,非集成环境. 添加了一个新站,路径都制定好了,但是在访问时出现了500错误.提示貌似是php的问题,但是之前的网站,运行的是di ...