python

python基础

2018-09-30  本文已影响0人  小小怪吃吃吃

python基础


语言基础

变量

条件语句

在if 语句或for 语句后需要缩进
• 保持缩进指明if/for语句块的范围
• 取消缩进回到与if 语句或for 语句对齐,表明if/for语句块结束 • 空白行不影响缩进
• 注释语句也不考虑缩进

try / except 语句

• 使用try和 except把有危险的代码包围起来
• 如果try模块的代码正常运行,except将被忽略
• 如果try模块的代码运行失败,会跳转到except模块执行

函数

1、Python有两类函数:

2、使用关键字def创建新的函数 ,在括号中输入参数。

循环和迭代

字符串

文件

handle = open(filename, mode)
fhand = open('mbox.txt', 'r')
• 返回句柄,用于操作文件
• 文件名是一个字符串,mode选项可选择,如果只需要读文件可取值为‘r’,如果需 要写文件则取值为‘w’.

xfile = open('mbox.txt')
for cheese in xfile:
print(cheese)

fhand = open('mbox-short.txt')
inp = fhand.read()

数据结构

数据结构,在计算机中组织数据的特定方法。

列表(list)

字典(dict)

计算一行字符串中单词出现的频率通常的模式是先把字符串分割成单词,然后在单词列表中循环,使用字典记录每一个单词出现的次数。

元组(tuple)

正则表达式

常见的正则表达式:

Item meaning
^ Matches the beginning of a line
$ Matches the end of the line.
. Matches any character
\s Matches whitespace
\S Matches any non-whitespace character
* Repeats a character zero or more times.
*? Repeats a character zero or more times (non-greedy)
+ Repeats a character one or more times
+? Repeats a character one or more times (non-greedy)
[aeiou] Matches a single character in the listed set
[^XYZ] Matches a single character not in the listed set.
[a-z0-9] The set of characters can include a range
( Indicates where string extraction is to start.
) Indicates where string extraction is to end
上一篇下一篇

猜你喜欢

热点阅读