Python Quick Start

  • Python程序脚本通过空格缩进来表示段落层次
  • 相同段落内的语句必须使用相同数量的空格缩进

数值

sum = 3+4
value = 3/4               # Python3返回0.75;Python2返回整数0
value = 3//4              # 返回整数,舍去小数部分
width = 5
height = 9
area = 5*9                # 乘法
area = 5**2               # 指数运算

字符串

s = "hello python"        # 双引号字符串
s = 'hello python'        # 单引号字符串,与双引号无区别

print(s)                  # 输出

s = r"c:\path\to\name"    # 前缀字符 r = raw string

s = """
Usage:
    command -h -p
"""

s = "hello" + "python"    # 字符串拼接
s = '-' * 72              # 字符串重复
s = 72 * '-'

s = "hello" "python"
s = (
  "hello"
  "python"
)
  • 字符串实质上字符数组,即 List of Char

List

days = [1, 4, 9, 16, 25]
days[0]                         # 下标从0开始
days[-1]                        # 负数的下标表示从尾部算起

days[0:2]                       # 数组截取
days[-3:]                       # 末尾三个元素

days[1] = 6                     # 元素赋值
days[0:2] = ['a', 'b', 'c']     # 范围赋值
days[0:2]                       # 元素删除

days = [ [1, 2, 3], [4, 5, 6]]  # 二维数组

控制结构

i, n = 0, 10                    # 列表形式的赋值

while i < n:                    # while 循环
  print(i)
  i++

for i in range(5):              # for 循环
  print(i)

if i < 10:                      # if 分支
  print("branch 1")
elif i>13:
  print("branch 2")
else:
  print("branch 3")

days = [3, 9, 13, 25]
for d in days:
  if d==9:
    continue                    # 继续循环
  elif d==13
    break                       # 跳出循环

for d in days:
  pass                          # 什么都不干的占位者

函数

def area(width, height=4):      # 定义函数 
  return width*3

area(3, 4)                      # 调用函数
area(width=7, height=8)         # Keyword Arguments

def rpc_call(method, *args, **kargs)
  for arg in args:                    # a tuple for positional arguments
    print(arg)
  print("-" * 40)
  for kw in kargs:                    # Keyword Arguments
    print(kw, ":", keywords[kw])

args = [3, 6]
kargs = { "width":4, "height":9 }
rpc_call("test", *args, **kargs)      # Unpack arguments