039-x

if,elif,else#

  • 控制流:只在需要时才执行代码
  • 靠缩进控制层级
if some_condition:
	# method1
	# method2
elif some_other_condition:
	#method3
	#method4
else:
	#method5
	#method6
#method7
  • 所有处于if下的==缩进==层级 method1,method2 的代码,只有在条件 some_condition 为真时才会执行
  • method7永远都会执行,而其他的则依据条件而论
>>> a=3;b=4;
>>> a
3
>>> b
4
>>> if a<b:
...     print('a<b')
... elif a==5:
...     print('a=5')
... else:
...     print('other')
... print('hello world')
... 
a<b
hello world
>>> a=5;b=2;
>>> if a<b:
...     print('a<b')
... elif a==5:
...     print('a=5')
... else:
...     print('other')
... print('hello world')
... 
a=5
hello world

037-038

比较运算符#

#检查相等性
>>> 2==2
True
>>> 2==1
False
>>> 'hello'=='bye'
False
>>> 'hi'=='hi'
True
>>> 2=='2'
False
>>> 2.0==2 #数值
True
>>> 3!=3
False
>>> 4!=5
True
>>> 2>1
True
>>> 1>2
False
>>> 1<2
True
>>> 2<5
True
>>> 2>=2
True
>>> 4<=1
False

使用逻辑运算符(连接比较运算符)#

  • and
  • or
  • not

and#

>>> 1<2
True
>>> 2<3
True
>>> 1<2<3 #直接串联
True
>>> 1<2>3
False
#使用逻辑运算符连接
 
>>> 1<2 and 2<3
True 
>>> 'h' == 'h' and 2==2
True
>>> ('h' == 'h') and (2==2)
True

>>> 1<2 && 2<3
  File "<python-input-23>", line 1
    1<2 && 2<3
         ^
SyntaxError: invalid syntax

#注意,这是按位与运算符,且优先级高于<,>
>>> 3 < 4 & 4 < 5  #相当于  3< (4&4) <5,3 < 4 < 5
True

or#

>>> 1==1 or 2==2
True
>>> 100==1 or 2==2
True

not#

>>> 1==1
True
>>> not(1==1)
False
>>> not 1==1
False
>>> not 400>5000
True
>>> 1!=1
False
>>> not 1==1 #相比1!=1,逻辑更清晰点  
False

033-036

基本的文件输入输出#

编辑并保存一个测试文件#

在jupyter中输入并运行

%%writefile myfile.txt
Hello this is a text file
this is the second line
this is the third line

得到文件

注意,最后一行(第三行)最后还有一个换行符\n

也就是说,在jupyter输入的文本,都会以一个换行符结束输入

另一种情况,在linux下使用ipython命令行输入

In [2]: %%writefile myfile_linux.txt
   ...: a
   ...: b
   ...: 
   ...: 
Overwriting myfile_linux.txt

在系统中查看,发现jupyter是没有空行的,而myfile_linux.txt则多了一个空行

(myenv) ly@dba13:~$ cat myfile_linux.txt
a
b

(myenv) ly@dba13:~$ cat myfile.txt #这个是我保存的jupyter编辑的文件
Hello this is a text file
this is the second line
this is the third line
(myenv) ly@dba13:~$ 

026-032

List 列表#

索引和切片#

列表支持索引和切片,还支持嵌套 混合

>>> [1,"2",3.5,['a','b']]
[1, '2', 3.5, ['a', 'b']]
>>> a=[1,"2",3.5,['a','b']]
>>> a[3]
['a', 'b']
>>> a[3][1]
'b'

混合,相加#

>>> my_list=[1,2,3]
>>> my_list=['STRING',100,23.2]
>>> len(my_list)
3
>>> my_list[1:]
[100, 23.2]
>>> my_list[:1]
['STRING']
>>> mylist=['one','two','three']
>>> another_list=['four','five']
>>> mylist+another_list
['one', 'two', 'three', 'four', 'five']
>>> mylist
['one', 'two', 'three']
>>> another_list
['four', 'five']
>>> new_list=mylist+another_list
>>> new_list
['one', 'two', 'three', 'four', 'five']

可修改#

>>> new_list[0]='One All Caps'
>>> new_list
['One All Caps', 'two', 'three', 'four', 'five']
>>> new_list.append('six') #向后添加元素
>>> new_list
['One All Caps', 'two', 'three', 'four', 'five', 'six']
>>> new_list[-1]='heihei' #修改最后一个元素
>>> new_list
['One All Caps', 'two', 'three', 'four', 'five', 'heihei']
>>> len(new_list)
6
>>> new_list[6]='heihei'  #向后添加元素不能用下标方式
Traceback (most recent call last):
  File "<python-input-23>", line 1, in <module>
    new_list[6]='heihei'
    ~~~~~~~~^^^
IndexError: list assignment index out of range
>>> new_list.pop
<built-in method pop of list object at 0x7f7a558dfb80>
#移除元素
>>> new_list.pop() #弹出并返回最后一个元素
'heihei'
>>> new_list
['One All Caps', 'two', 'three', 'four', 'five']
>>> popped_item=new_list.pop()
>>> popped_item
'five'
>>> new_list
['One All Caps', 'two', 'three', 'four']
#弹出指定索引的元素
>>> new_list
['One All Caps', 'two', 'three', 'four']
>>> new_list.pop(0)
'One All Caps'
>>> new_list
['two', 'three', 'four']
#弹出列表最后一个元素
>>> new_list.pop(-1)
'four'
>>> new_list
['two', 'three']

sort 和 reverse:(原地操作)#

sort 不返回任何类型

020-025

字符串简介#

#接下来使用ipython

In [2]: print('hello')
hello

In [3]: print("Hello")
Hello

In [4]: print("I don't know")
I don't know

In [5]: print(' hah "hai"')
 hah "hai"
  • 字符串是有序序列,可以使用 indexing 或 slicing 来获取字符串子集
  • 索引和java、c/cpp一样从0开始
  • 可以使用反向索引
  • 切片 [start:stop:step]
    • start (包括)
    • stop (不包括)
    • step (跳跃幅度)
#返回字符串(不是打印字符串),所以这里还显示了''表示这是一个字符串
In [1]: 'hello'
Out[1]: 'hello'

In [2]: "world"
Out[2]: 'world'

In [3]: 'this is a "Test'
Out[3]: 'this is a "Test'

In [4]: 'this is a "Test"'
Out[4]: 'this is a "Test"'

例子1#

  • 创建/取得一个对象 → 用完 → 丢弃
  • 这个例子其实没有什么实际意义,在.py文件中然后被 python xx.py时,这个代码出现在文件中,是会被合并成"hello1hello2"的,而且没人引用它,最终也会被丢弃

例子2#

015-019

数据类型简介#

NameTypeDescription
IntegersintWhole numbers, such as: 3 300 200
Floating pointfloatNumbers with a decimal point: 2.3 4.6 100.0
StringsstrOrdered sequence of characters: "hello" 'Sammy' "2000" "楽しい"
ListslistOrdered sequence of objects: [10,"hello",200.3]
DictionariesdictUnordered Key:Value pairs: {"mykey" : "value" , "name" : "Frankie"}
TuplestupOrdered immutable sequence of objects: (10,"hello",200.3)
SetssetUnordered collection of unique objects: {"a","b"}
BooleansboolLogical value indicating True or False

占用大小(ai)#

数据类型类型标识 (Type)基础/典型占用字节 (Bytes)内存占用与扩容机制说明
布尔型bool28 字节TrueFalse 是全局单例对象(继承自 int),固定占用 28 字节。 True or False
整型int28 字节基础 28 字节(存储 32 位以内的整数)。任意精度:数值超过 32 位( 23012^{30}-1 )后,每增加 30 位数据递增 4 字节。 3 300 200
浮点型float24 字节固定 24 字节(包含 8 字节 IEEE 754 双精度浮点数及对象头)。超出范围返回 inf 或下溢为 0.02.3 4.6 100.0
字符串str48 字节(空串)根据最复杂字符自动选择编码:• ASCII / 纯英文:48 + 字符数×1 字节• Unicode / 中文日文:74 + 字符数×2 字节 "hello" 'Sammy' "2000" "楽しい"
元组tup (tuple)40 字节(空元组)(3 元素示例:64 字节)计算公式约为 40+8×n40 + 8 \times n 字节( nn 为指针数)。只存储元素指针,元素本身内存另计。不可变。 (10,"hello",200.3)
列表list56 字节(空列表)(3 元素示例:88 字节)计算公式约为 56+8×n56 + 8 \times n 字节。为保证追加效率会预分配容量(Over-allocation),仅存储元素指针。 [10,"hello",200.3]
集合set216 字节(空集合)基于哈希表实现,初始即预分配包含 8 个槽位的哈希表,基础开销较大。 {"a","b"}
字典dict64 字节(空字典)(2 键值对示例:184 字节)基于紧凑哈希表实现,包含索引数组与键值对数组。仅计字典结构及指针占用,Key 和 Value 对象本身内存另计。 {"mykey" : "value" , "name" : "Frankie"}

比较#

基础数据类型#

数据类型== 比较标准顺序敏感?独立定义时 a is b
整型 (int)比较数值大小是否完全相同不适用常为 True(小整数区间 -5257 会全局缓存地址;大整数在同一作用域下也有编译优化缓存)
浮点型 (float)比较数值大小(注意 IEEE 754 精度误差)不适用可能为 True(相同常量在同一代码块中会被编译优化指向同地址;不同代码块中为 False
字符串 (str)按字符序列及其顺序依次比较敏感常为 True(满足驻留机制 Interning 的短字符串或编译期常量会共享内存地址)

Python 语言规范本身并没有强制要求必须指向同一地址,这是解释器为了节省内存和提高效率所做的优化。

001-014

课程大纲#

  • 介绍
    • 概述
    • Python2与Python3
    • 如何学习本课程
  • Python设置
    • 安装
    • 环境选择
    • 笔记系统
    • git/github
  • 对象和数据结构基础
    • Numbers
    • Strings
    • Lists
    • Dictionaries
    • Tuples(元组)
    • Files
    • Sets(集合)
    • Booleans
  • 比较运算符
    • 基本运算符
    • 链式比较运算符
  • 语句
    • if,elif,else
    • for
    • while
    • range
    • List Comprehensions(列表推导式)
  • 方法和函数
    • Methods
    • Functions
    • LambdaExpressions(lambda表达式)
    • NestedStatements(嵌套语句)
    • Scope(作用域)
  • 第一个里程碑项目
    • Pyhon创建一个游戏
  • 面向对象编程
    • 对象,类,方法,继承,特殊方法
  • ErrosAndExceptionHandling(错误和异常处理)
    • Erros
    • Exceptions
    • try
    • except
    • finally
  • 第二个里程碑项目
    • 创建更复杂的游戏
  • Modules and Package(模块和包)
    • 创建模块
    • 安装模块
    • 总体上探索Pythone生态
  • 内置函数
    • map
    • reduce
    • filter
    • zip
    • enumerate
    • all and any
    • complex(处理复数)
  • Decorators in Python(装饰器,这个系列三部分)
  • Python Generators(生成器)
    • Iteration vs Generation (迭代器、生成器)
    • Creating Generators (生成器)
  • 所有知识整合到一个项目
  • 高级额外内容(定期添加)—-110集
    • 高级Python Modules
    • 高级Python Object ,高级数据结构

Python 介绍#

  • 可读性、易用性
  • 大量现有库、框架
  • 解决开发时间(不是运行时间)
  • 大量直接可用的基础Python基础模块、外部库
    • 自动化简单任务(搜索文件、读写文件、自动发送电子文件)
    • 数据科学,机器学习
    • 创建网站(Django,Flask)

使用命令行#

本节学习: