python实战

一、python基础

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys

__author__ = 'mac'


# 整数
intA = 10
intX = 0xff00
intB = 0b0010

# 浮点数
floatA = 1.8
floatX = 1.0e10

# 字符串
strA = '''
    you say
    it!
'''
print(strA)

# 布尔
boolA = True
boolB = False
boolA and boolB #or not

# 空值
None

# 编码
print(ord('A'))
print(ord('中'))
print(chr(49))
 
# 字节
bytes = b'abc'
print(bytes)
"abc".encode("ascii")
"炎黄子孙".encode("utf-8")
b'abc'.decode("ascii")

# 格式化
# %d    整数
# %f    浮点数
# %s    字符串
# %x    十六进制整数
print("hi, %s" % "you!")

# list
listA = ["A", "B", 1, 2]
print(listA)
# tuple
tupleA = ("A", "b", 1)

# 条件判断 if elif else
if 1 > 3:
    print("wrong!")

# 循环 for var in ...:   while condition:
for i in [1,2,3]:
    print(i)

list(range(10))

# 字典
dict({})
dictA = {"key": "value"}

# set
s = set([1, 2, 3])


def test():
    print("it's a test")

if __name__ == "__main__":
    print(len(sys.argv))
test()

二、python函数

# -*- coding: utf-8 -*-

__author__ = 'sosop'

# 定义一个函数要使用def语句,依次写出函数名、括号、括号中的参数和冒号:
# 在缩进块中编写函数体,函数的返回值用return语句返回。

def my_test(msg):
    print("this is", msg)

# 空函数
def null_func():
    pass

# 类型判断
isinstance(1, (int, float))

# 默认参数
def default_param(x, y = 1):
    return x * y

# 可变参数,可变参数在函数调用时自动组装为一个tuple
def var_params(* num):
    t = 0
    for i in num:
        t = t + i
    return t

# 关键字参数,关键字参数在函数内部自动组装为一个dict
def key_params(** kw):
    print(kw)

# 命名关键字参数,限制关键字参数的名字
def name_key_params(*, job, age):
    print(job, age)

# 尾递归是指,在函数返回的时候,调用自身本身,并且,return语句不能包含表达式
def tail_fact(n, total):
    if n == 1:
       return total
    return tail_fact(n - 1, n * total)

def fact(n):
    tail_fact(n, 1)


# 调用
my_test("123")
null_func()
print(default_param(10, 2))
print(default_param(100))
print(var_params(1,2,3,4))
nums = [5,6,7,8]
print(var_params(*nums))
key_params()
key_params(city="chengdu", location="Internet")
dp = {"name": "sosop", "city": "chengdu"}
key_params(**dp)
print(fact(10))
sosop hou 24 July 2015
blog comments powered by Disqus