Python编程常用的十大语法和代码汇总

C.1.1 Python的“Hello World”

[输入]

source_code/appendix_c_python/example00_helloworld.py
print 'Hello World!'

[输出]

$ python example00_helloworld.pyHello World!

C.1.2 注释

注释不会被Python执行。它以字符#开头,以行尾结束。

[输入]

# source_code/appendix_c_python/example01_comments.py
print 'This text will be printed because the print statement is executed.'
#这只是一个注释,不会被执行
#print 'Even commented statements are not executed.'
print 'But the comment finished with the end of the line.'
print 'So the 4th and 5th line of the code are executed again.'

[输出]

$ python example01_comments.pyThis text will be printed because the print statement is executedBut the comment finished with the end of the line.So the 4th and 5th line of the code are executed again.

C.2 数据类型

Python的一些有效数据类型如下所示。

  • 数字数据类型:整型、浮点型。

  • 文本数据类型:字符串型。

  • 复合数据类型:元组、列表、集合、字典。

C.2.1 整型

整数数据类型只能存储整数值。

[输入]

# source_code/appendix_c_python/example02_int.py
rectangle_side_a = 10
rectangle_side_b = 5
rectangle_area = rectangle_side_a * rectangle_side_b
rectangle_perimeter = 2*(rectangle_side_a + rectangle_side_b)
print 'Let there be a rectangle with the sides of lengths:'
print rectangle_side_a, 'and', rectangle_side_b, 'cm.'
print 'Then the area of the rectangle is', rectangle_area, 'cm squared.'
print 'The perimeter of the rectangle is', rectangle_perimeter, 'cm.'

[输出]

$ python example02_int.pyLet there be a rectangle with the sides of lengths: 10 and 5 cm.Then the area of the rectangle is 50 cm squared.The perimeter of the rectangle is 30 cm.

C.2.2 浮点型

浮点数据类型也可以存储非整数的有理数值。

[输入]

# source_code/appendix_c_python/example03_float.py
pi = 3.14159
circle_radius = 10.2
circle_perimeter = 2 * pi * circle_radius
circle_area = pi * circle_radius * circle_radius
print 'Let there be a circle with the radius', circle_radius, 'cm.'
print 'Then the perimeter of the circle is', circle_perimeter, 'cm.'
print 'The area of the circle is', circle_area, 'cm squared.'

[输出]

$ python example03_float.pyLet there be a circle with the radius 10.2 cm.Then the perimeter of the circle is 64.088436 cm.The area of the circle is 326.8510236 cm squared.

C.2.3 字符串

字符串变量可以用于存储文本。

[输入]

# source_code/appendix_c_python/example04_string.py
first_name = 'Satoshi'
last_name = 'Nakamoto'
full_name = first_name + ' ' + last_name
print 'The inventor of Bitcoin is', full_name, '.'

[输出]

$ python example04_string.pyThe inventor of Bitcoin is Satoshi Nakamoto.

C.2.4 元组

元组数据类型类似于数学中的向量。例如,tuple = (integer_number, float_number)。

[输入]

# source_code/appendix_c_python/example05_tuple.py
import math
point_a = (1.2,2.5)
point_b = (5.7,4.8)
#math.sqrt计算浮点数的平方根
#math.pow计算浮点数的幂
segment_length = math.sqrt(
math.pow(point_a[0] - point_b[0], 2) +
math.pow(point_a[1] - point_b[1], 2))
print 'Let the point A have the coordinates', point_a, 'cm.'
print 'Let the point B have the coordinates', point_b, 'cm.'
print 'Then the length of the line segment AB is', segment_length, 'cm.'

[输出]

$ python example05_tuple.pyLet the point A have the coordinates (1.2, 2.5) cm.Let the point B have the coordinates (5.7, 4.8) cm.Then the length of the line segment AB is 5.0537115074 cm.

C.2.5 列表

Python中的列表指的是一组有序的数值集合。

[输入]

# source_code/appendix_c_python/example06_list.py
some_primes = [2, 3]
some_primes.append(5)
some_primes.append(7)
print 'The primes less than 10 are:', some_primes

[输出]

$ python example06_list.pyThe primes less than 10 are: [2, 3, 5, 7]

C.2.6 集合

Python中的集合指的是一组无序的数值集合。

[输入]

# source_code/appendix_c_python/example07_set.py
from sets import Set
boys = Set(['Adam', 'Samuel', 'Benjamin'])
girls = Set(['Eva', 'Mary'])
teenagers = Set(['Samuel', 'Benjamin', 'Mary'])
print 'Adam' in boys
print 'Jane' in girls
girls.add('Jane')
print 'Jane' in girls
teenage_girls = teenagers & girls #intersection
mixed = boys | girls #union
non_teenage_girls = girls - teenage_girls #difference
print teenage_girls
print mixed
print non_teenage_girls

[输出]

$ python example07_set.pyTrueFalseTrueSet(['Mary'])Set(['Benjamin', 'Adam', 'Jane', 'Eva', 'Samuel', 'Mary'])Set(['Jane', 'Eva'])

C.2.7 字典

字典是一种数据结构,可以根据键存储数值。

[输入]

# source_code/appendix_c_python/example08_dictionary.py
dictionary_names_heights = {}
dictionary_names_heights['Adam'] = 180.
dictionary_names_heights['Benjamin'] = 187
dictionary_names_heights['Eva'] = 169
print 'The height of Eva is', dictionary_names_heights['Eva'], 'cm.'

[输出]

$ python example08_dictionary.pyThe height of Eva is 169 cm.

C.3 控制流

条件语句,即我们可以使用if语句,让某段代码只在特定条件被满足的情况下被执行。如果特定条件没有被满足,我们可以执行else语句后面的代码。如果第一个条件没有被满足,我们可以使用elif语句设置代码被执行的下一个条件。

[输入]

# source_code/appendix_c_python/example09_if_else_elif.py
x = 10
if x == 10:
print 'The variable x is equal to 10.'
if x > 20:
print 'The variable x is greater than 20.'
else:
print 'The variable x is not greater than 20.'
if x > 10:
print 'The variable x is greater than 10.'
elif x > 5:
print 'The variable x is not greater than 10, but greater ' + 'than 5.'
else:
print 'The variable x is not greater than 5 or 10.'

[输出]

$ python example09_if_else_elif.pyThe variable x is equal to 10.The variable x is not greater than 20.The variable x is not greater than 10, but greater than 5.

C.3.1 for循环

for循环可以实现迭代某些集合元素中的每一个元素的功能,例如,range集合、列表。

C3.1.1 range的for循环

[输入]

source_code/appendix_c_python/example10_for_loop_range.py
print 'The first 5 positive integers are:'
for i in range(1,6):
print i

[输出]

$ python example10_for_loop_range.pyThe first 5 positive integers are:12345

C3.1.2 列表的for循环

[输入]

source_code/appendix_c_python/example11_for_loop_list.py
primes = [2, 3, 5, 7, 11, 13]
print 'The first', len(primes), 'primes are:'
for prime in primes:
print prime

[输出]

$ python example11_for_loop_list.pyThe first 6 primes are:23571113

C3.1.3 break和continue

for循环可以通过语句break提前中断。for循环的剩余部分可以使用语句continue跳过。

[输入]

source_code/appendix_c_python/example12_break_continue.py
for i in range(0,10):
if i % 2 == 1: #remainder from the division by 2
continue
print 'The number', i, 'is divisible by 2.'
for j in range(20,100):
print j
if j > 22:
break;

[输出]

$ python example12_break_continue.pyThe number 0 is divisible by 2.The number 2 is divisible by 2.The number 4 is divisible by 2.The number 6 is divisible by 2.The number 8 is divisible by 2.20212223

C.3.2 函数

Python支持函数。函数是一种定义一段可在程序中多处被执行的代码的好方法。我们可使用关键词def定义一个函数。

[输入]

source_code/appendix_c_python/example13_function.py
def rectangle_perimeter(a, b):
return 2 * (a + b)
print 'Let a rectangle have its sides 2 and 3 units long.'
print 'Then its perimeter is', rectangle_perimeter(2, 3), 'units.'
print 'Let a rectangle have its sides 4 and 5 units long.'
print 'Then its perimeter is', rectangle_perimeter(4, 5), 'units.'

[输出]

$ python example13_function.pyLet a rectangle have its sides 2 and 3 units long.Then its perimeter is 10 units.Let a rectangle have its sides 4 and 5 units long.Then its perimeter is 18 units.

C.3.3 程序参数

程序可以通过命令行传递参数。

[输入]

source_code/appendix_c_python/example14_arguments.py
#引入系统库以使用命令行参数列表
import sys
print 'The number of the arguments given is', len(sys.argv),'arguments.' print 'The argument list is ', sys.argv, '.'

[输出]

$ python example14_arguments.py arg1 110The number of the arguments given is 3 arguments.The argument list is ['example14_arguments.py', 'arg1', '110'].

C.3.4 文件读写

下面程序将向文件test.txt写入两行文字,然后读取它们,最后将其打印到输出中。

[输入]

# source_code/appendix_c_python/example15_file.py
#写入文件'test.txt'
file = open('test.txt','w')
file.write('first line\n')
file.write('second line')
file.close()
#read the file
file = open('test.txt','r')
print file.read()

[输出]

$ python example15_file.pyfirst linesecond line
(0)

相关推荐

  • xrange和range的区别是什么?

    学习Python的时候,我们经常会看到xrange和range,那么Python中xrange和range有什么区别?跟着小编来看看吧. 首先要说明一下,只有在Python2中才有Xrange和ran ...

  • python学习——类中为什么要定义__init__()方法

    python学习--类中为什么要定义__init__()方法 geerniya 2017-08-22 21:12:41 36244 收藏 188 分类专栏: python 文章标签: python 版 ...

  • 使用OpCode绕过Python沙箱的方法详解

    0x01 OpCode opcode又称为操作码,是将python源代码进行编译之后的结果,python虚拟机无法直接执行human-readable的源代码,因此python编译器第一步先将源代码进 ...

  • 精品:教师最常用的十大课件下载网

    ◤1 人民教育出版社 最权威的课件内容提供者,提高小学.初中.高中.职业教育及相关教育的课件及内容. ◤2 中华资源库 课件只是其中一小部分,主要内容是各种知识点解析.视频资料等内容,并可按照地区选择 ...

  • 特级教师常用的十大教育原理

    特级教师常用的十大教育原理 [教育君语] 根雕原理.过河原理.图钉原理--特级教师常用的这十大教育原理,值得老师们收藏,也值得家长们深思. 一.赏识法则--根雕原理 根雕常常以其精美的造型,独特的构思 ...

  • 盘点炉石传说里常用的十大反制手段,真的像设计师说的即少又弱吗

    本周的推特炉石问答中,设计师Iksar提到了炉石里的反制手段,称炉石通常只会偶尔出一些反制手段,而且这些卡牌通常比较弱,这一说法遭到了玩家们的抨击,那我们今天就来盘点一下炉石传说里的那些反制卡牌. 奥 ...

  • 【管遵信】常用耳穴十大基本方

    管遵信老师堪称中国中医耳针学的先驱,其倾注几十年于耳穴研究,影响巨大,成果丰硕,吾十余年前初试尝耳针,惊于其效,后闻管老之名,悉管老之学,感管老治学求真之不易! 今愿与诸学友同习.同求,感念管师之德. ...

  • 临床中常用的十大痛证药对1、白芍、甘草:...

    临床中常用的十大痛证药对 1.白芍.甘草:缓急止痛,常用于挛急或不荣之痛,如头痛.胸痛.胃脘痛.胁痛.腹痛.经痛.四肢痛.小腿转筋等. 2.全蝎.钩藤.紫河车:祛风解痉,通络止痛,益养脑络,常用于偏头 ...

  • 临床中常用的十大痛证药对

    临床中常用的十大痛证药对

  • 八字断命常用的十大技法

    在八字命理中,解析命理的技法有很多种,会根据不同的事情,来提取不同的象,以及吉凶,比如,看事业财运,婚姻.父母.子女.健康等,会用到不同的技法. 再加之不同的流派,所使用的技法也有轻重之别,下面,给大 ...

  • 如何让学生对课堂“欲罢不能”?特级教师常用的十大法则

    教师就像厨师,学生就是食客,好菜要有诱惑力,就要想如何吸引食客的胃口,也就是说老师的课要有魅力,要寻找让学生欲罢不能之道.下面是特级教师经常运用10个教育原理,老师们快来学习一下"大厨&qu ...

  • 常用耳穴十大基本方

    管遵信老师堪称中国中医耳针学的先驱,其倾注几十年于耳穴研究,影响巨大,成果丰硕,吾十余年前初试尝耳针,惊于其效,后闻管老之名,悉管老之学,感管老治学求真之不易! 今愿与诸学友同习.同求,感念管师之德. ...