查看模块
[infobg class=“notice” bgcolor=“#d9edf7”] dir(模块名) [/infobg]
查看函数使用规则
[infobg class=“notice” bgcolor=“#d9edf7”] help(模块.函数) [/infobg]
**乘方,从右向左
[infobg class=“notice” bgcolor=“#d9edf7”] 2**2**3=256 (2**2)**3=64 [/infobg] [callout class=“warning” title=""]
更多字符相关内容,请参见《简明 Python 教程》学习笔记-运算符与表达式
[/callout]
键盘输入
[infobg class=“notice” bgcolor=“#d9edf7”] raw_input() [/infobg]
选择分支
[infobg class=“notice” bgcolor=“#d9edf7”] if score >= 90: print ‘A’ elif score >=80: print ‘B’ elif score >=70: print ‘C’ else: print “E” [/infobg]
注释
中文注释
[infobg class=“notice” bgcolor=“#d9edf7”] 在Python脚本文件的第一行或第二行添加一句: #coding:gbk或#coding:utf-8或##-*- coding : gbk -*- [/infobg]
本质就是使用编码声明。
块注释
"""注释内容"""行注释
#注释内容Renyi停车常数
[infobg class=“notice” bgcolor=“#d9edf7”] 常数0.7475972被称为Renyi停车常数 [/infobg]
函数
优点
[infobg class=“notice” bgcolor=“#d9edf7”]
-
代码可重用
- 提高开发效率
- 减少重复编码
-
代码更简洁
- 函数功能相对独立
- 结构清晰,可读性好
-
编程更容易把握
- 复杂程序分解成较小部件
-
封装与信息隐藏
[/infobg]
global
表明非局部变量
代码实例
"""汉诺塔实例,其中的count用作计算总共的移动次数"""count = 0def hannoi(n,A,B,C): global count if n == 1: print 'Move',n,'from',A,'to',C count +=1 else: hannoi(n-1,A,C,B) print 'Move',n,'from',A,'to',C count +=1 hannoi(n - 1, B ,A, C)
hannoi(3,'Left','Mid','Right')print count运行效果:
>>>Move 1 from Left to RightMove 2 from Left to MidMove 1 from Right to MidMove 3 from Left to RightMove 1 from Mid to LeftMove 2 from Mid to RightMove 1 from Left to Right7pass
[infobg class=“notice” bgcolor=“#d9edf7”] 占位符,表示这是一些语句,但未实现 [/infobg] [callout class=“warning” title=“Python中的函数”] 更多有关函数的内容,请参见《简明 Python 教程》学习笔记-函数 [/callout]
递归
解决问题的思想
if 问题足够简单: 直接解决问题 返回解else: 将问题分解为与原问题同构的一个或多个更小的问题 逐个解决这些更小的问题 将结果组合,获得最终的解 返回解优势
[infobg class=“notice” bgcolor=“#d9edf7”]
- 能使一个蕴含递归关系且结构复杂的程序简洁精练,增加可读性
- 特别是在难于找到从边界到解的全过程的情况下,若把问题推进一步,其结果仍维持原问题的关系。
[/infobg]
劣势
[infobg class=“notice” bgcolor=“#d9edf7”]
- 嵌套层次深,函数调用开销大
- 重复计算
[/infobg]

评论