Python学习笔记#2:基本语法结构


前言

本文记录Python得几种基本语法


程序基本结构

典型的Python文件结构

# coding: utf-8

import sys	# 导入包

def foo():	# 定义函数
	print "Hello World"

class my_class(object): # 自定义类
	def __init__(self): # 构造函数
		pass
	
	def foo(self):
		k = 100
		return k

# 主函数
if __name__ == '__main__':
	foo()

if 语句

if condition:
    pass
else:
    pass

for 语句

for target_list in expression_list:
    pass

while 语句

while expression:
    pass
else:
    pass

try 语句

try:
    pass
except expression as identifier:
    pass
else:
    pass
finally:
    pass

print 语句

基础函数,但是用法很灵活

常规用法

# 纯文本输出
print("hello, world!")

# 特殊字符 \t , \n
print("hello\t,wo\nrld!")

# 结束字符
print("你以为会换行?", end="")
print("然而并不会")

# 字符串格式化
print("%s , %s, %d" % ("hello", "world", 1234567))

结果

hello, world!
hello   ,wo
rld!
你以为会换行?然而并不会
hello , world, 1234567

format

传统的字符串格式化,不容易记住,2.6版本以后可以用format代替

# format
# 不设置指定位置,按默认顺序
print("{} {}".format("hello", "world"))

# 设置指定位置
print("{1} {0}".format("hello", "world"))

# 设置指定位置
print("{0} {1}".format("hello", "world"))

# 指定变量
aa = "hello"
bb = "world"
cc = 1234123123
print("{a} + {b} = {c}".format(a=aa, b=bb, c=cc))

结果

hello world
world hello
hello world
hello + world = 1234123123

函数

函数格式很简单,重点在于几种不同得参数传递形式。

无参数

def funcname():
    pass
    return

固定参数

def funcname(x,y,z):
    pass
    return

默认参数

def funcname(x, y="hello", z="world~"):
    print(x, y, z)

funcname("yes")
funcname("yes", z="1")
funcname("yes", y="2", z="3")

结果

yes hello world~
yes hello 1
yes 2 3

未知参数传递

对于某些函数,我们不知道传进来多少个参数,只知道对这些参数做怎样得处理,这个时候就需要用到未知参数传递机制。

def funcname(*args):
    sum = 0
    for i in args:
        sum += i
    print("sum = ", sum)

funcname(1, 2, 3, 4, 5, 6, 7)
funcname(1, 2, 3, 4, 5, 6)
funcname(1, 2, 3, 4, 5)

结果

sum =  28
sum =  21
sum =  15

带键参数传递

带键参数传递是指参数通过键值对得方式进行传递。

def funcname(**kwargs):
    print(type(kwargs))
    for i in kwargs:
        print(i, kwargs[i])

funcname(aa=1, bb=2, cc=3)
funcname(x=1, y=2, z="hello world!")
funcname(a=[0, 1, 2, 3], b=(0, 1, 2, 3), c={1: "one", 2: "two", 3: "three"})

结果

<class 'dict'>
aa 1
bb 2
cc 3
<class 'dict'>
x 1
y 2
z hello world!
<class 'dict'>
a [0, 1, 2, 3]
b (0, 1, 2, 3)
c {1: 'one', 2: 'two', 3: 'three'}

lambda函数

lambda函数又叫做匿名函数,当某些函数只需要使用一两次的时候,这个时候定义一个专门的函数名称就显得比较浪费,这种情况下就可以使用lambda函数,也称 “一次性函数”。

maximum = lambda x, y: (x > y) * x + (x < y) * y

minimum = lambda x, y: (x > y) * y + (x < y) * x

print("The largar one is %d" % maximum(10, 20))
print("The lower one is %d" % minimum(5, 6))

结果

The largar one is 20
The lower one is 5

回调函数

函数要作为参数传递到另外的函数中,回调函数得好处有两个:

  1. 可以在函数定义前就使用
  2. 调用其他程序得API

回调函数并不是一种函数种类,而是一种函数调用方法,需要好生体会。

def func(f, args):
    f(args)

def f1(x):
    print("this is f1: ", x)

def f2(x):
    print("this is f2: ", x)

func(f1, 9)
func(f2, 2323)

结果

this is f1:  9
this is f2:  2323

yield 函数

yield 是 python 当中的关键字,它的作用是将一个普通函数变成一个 generator,调用该函数的时候就不再执行整个函数,而是返回一个 iterable 对象。

例子1:斐波拉契数列

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n += 1

for i in fib(5):
    print(i)

结果

1
1
2
3
5

例子2:生成随机数列

def random_int_generator(N):
    i = 0
    ra = 0
    while i < N:
        yield ra
        ra = random.randint(0, 100)
        i += 1

for i in random_int_generator(5):
    print(i)

结果

0
58
7
26
0

主函数

特点:

  1. Python命名规则当中,前后两个_符号,代表该函数是内部函数,外部模块调用的时候看不到。
  2. main函数的作用在于调试代码,我们可以在主函数当中加入调试代码,外部模块调用时,不会执行main函数里面的代码。反过来,当我们需要单独调式这个模块的时候,就可以直接执行main函数。
if __name__ == "__main__":
    pass

数据结构

简单介绍几种基本的数据结构

列表 list

a = [1, 3, 2]
b = [3, 4, 5]

a.sort()  # 对列表 a 进行排序
print(a)

a.extend(b)  # 连接列表 a 与 b
print(a)

c = a + b  # 连接列表 a 与 b
print(c)

print(c[0])

print(c[-1])  # 倒叙

print(c[1:3])  # 子列表

print(c[:-2])

print(c[-3:])

结果

[1, 2, 3]
[1, 2, 3, 3, 4, 5]
[1, 2, 3, 3, 4, 5, 3, 4, 5]
1
5
[2, 3]
[1, 2, 3, 3, 4, 5, 3]
[3, 4, 5]

元组 tuple

t = (1, 2, 3, 4, 5)
print(t)
a, b = 1, 2
print(a, b)
# 交换
a, b = b, a
print(a, b)

结果

(1, 2, 3, 4, 5)
1 2
2 1

集合 set

集合最重要的特点:

  1. 元素唯一
  2. 元素无序

常规操作

s = {11, 23, 44, 33, 22, 66, 88, 44, 99, 55, 55, 55, 99, 88, 44}

print(s)

s1 = set(i for i in range(10))
print(s1)

s1.add(123)  # 添加
print(s1)

s1.remove(2)  # 删除
print(s1)

s1.update(s)  # 更新
print(s1)

结果

{33, 66, 99, 11, 44, 55, 22, 23, 88}
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 123}
{0, 1, 3, 4, 5, 6, 7, 8, 9, 123}
{0, 1, 66, 3, 4, 5, 6, 7, 8, 9, 11, 22, 23, 88, 33, 99, 44, 55, 123}

转换

t = (5, 1, 2, 3, 4, 2, 3, 4, 5)
l = [1, 3, 2, 2, 3, 323, 2, 1, 2, 8, 8, 9, 6, 4]

print(set(t))
print(set(l))

结果

{1, 2, 3, 4, 5}
{1, 2, 323, 3, 4, 6, 8, 9}

字典 dict

  1. 字典就是键值对,每种语言都有键值对,python里面就是 dict
  2. 字典符号 “{ }” 和集合一样,所以可以很好得理解字典的几种特性:
    1. 字典得所有键值 (key) 唯一
    2. 字典所有元素无序
d = {"one": {i for i in range(5)}, 2: (1, 2, 3), "three": "test", 4: [i for i in range(5)]}

for item in d:
    print(item, d[item])

结果

one {0, 1, 2, 3, 4}
2 (1, 2, 3)
three test
4 [0, 1, 2, 3, 4]

列表转化字典: 特俗情况下,如果列表格式如:[(key,value),(key,value)],可以直接转换成字典

a = [("a", "1 2 3 4 5 6 7"), ("b", 5), ("c", (6,4,3)), ("d", [1, 2, 3, 5, 6])]

d = dict(a)

print(d)
{'a': '1 2 3 4 5 6 7', 'b': 5, 'c': (6, 4, 3), 'd': [1, 2, 3, 5, 6]}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值