Python 学习笔记 4. 流程控制

if

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More
Python 学习笔记 3. 变量类型

数字

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
>>> 17 / 3  # classic division returns a float
5.666666666666667
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17
>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
>>> 4 * 3.75 - 1
14.0
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
>>>
Python 学习笔记 2. 基础语法

保留字符

and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
Python 学习笔记 1. 基础知识

#!/usr/bin/python

脚本语言的第一行,只对 Linux/Unix 用户适用,用来指定本脚本用什么解释器来执行。
另一种写法是 #!/usr/bin/env python

#!/usr/bin/python
Python 学习笔记 9. 类

Python 的类提供了面向对象编程的所有标准特性:类继承机制允许多个基类,派生类可以覆盖它基类的任何方法,一个方法可以调用基类中相同名称的的方法。对象可以包含任意数量和类型的数据。和模块一样,类也拥有 Python 天然的动态特性:它们在运行时创建,可以在创建后修改。

9.1. 名称和对象

对象具有个性,多个名称(在多个作用域内)可以绑定到同一个对象。这在其他语言中称为别名。在某些方面(如参数传递),别名表现的像指针。

Python 学习笔记 11. 标准库简介 —— 第二部分

11.1. 格式化输出

reprlib 模块提供了一个定制化版本的 repr() 函数,用于缩略显示大型或深层嵌套的容器对象:

>>> import reprlib
>>> reprlib.repr(set('supercalifragilisticexpialidocious'))
"{'a', 'c', 'd', 'e', 'f', 'g', ...}"
Python 学习笔记 10. 标准库简介

10.1. 操作系统接口

os 模块提供了许多与操作系统交互的函数:

>>> import os
>>> os.getcwd()
'C:\\Users\\liujiajia'
>>> os.chdir('D:\\')
>>> os.system('mkdir today')
0
>>> os.getcwd()
'D:\\'
>>> os.chdir('today')
>>> os.getcwd()
'D:\\today'
Python 学习笔记 8. 错误和异常

两种错误:语法错误异常

8.1 语法错误

语法错误 又称 解析错误

>>> while True print('Hello world')
  File "<stdin>", line 1
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax
Python 学习笔记 7. 输入输出

有几种方法可以显示程序的输出;数据可以以人类可读的形式打印出来,或者写入文件以供将来使用。

7.1. 更漂亮的输出格式

  • 使用 格式字字符串字面值

    >>> year = 2016
    >>> event = 'Referendum'
    >>> f'Results of the {year} {event}'
    'Results of the 2016 Referendum'
    >>> F'Results of the {year} {event}'
    'Results of the 2016 Referendum'
    
  • 使用 str.format() 方法

    >>> yes_votes = 42_572_654
    >>> no_votes = 43_132_495
    >>> percentage = yes_votes / (yes_votes + no_votes)
    >>> '{:-9} YES votes  {:2.2%}'.format(yes_votes, percentage)
    ' 42572654 YES votes  49.67%'
    
Python 学习笔记 6. 模块

模块是一个包含 Python 定义和语句的文件。 文件名就是模块名后跟文件后缀 .py

在一个模块内部,模块名(作为一个字符串)可以通过全局变量 __name__ 的值获得。

fibo.py

# Fibonacci numbers module

def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

def fib2(n):   # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a+b
    return result
Python 学习笔记 5. 数据结构

5.1 列表的更多特性

  • append(x) :在列表的末尾添加一个元素。
  • extend(iterable) :使用可迭代对象中的所有元素来扩展列表。
  • insert(i, x) :在给定的位置插入一个元素。
  • remove(x) :移除列表中第一个值为 x 的元素。
  • pop([i]) :删除列表中给定位置的元素并返回它。
  • clear() :删除列表中所有的元素。如果没有给定位置,将会删除并返回列表中的最后一个元素。
  • index(x[, start[, end]]) :返回列表中第一个值为 x 的元素的从零开始的索引。
  • count(x) :返回元素 x 在列表中出现的次数。
  • sort(key=None, reverse=False) :对列表中的元素进行排序
  • reverse() :反转列表中的元素。
  • copy() :返回列表的一个浅拷贝。