Python编程常用的十大语法和代码汇总
C.1.1 Python的“Hello World”
[输入]
print 'Hello World!'
[输出]
$ python example00_helloworld.pyHello World!
C.1.2 注释
注释不会被Python执行。它以字符#开头,以行尾结束。
[输入]
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 整型
整数数据类型只能存储整数值。
[输入]
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 浮点型
浮点数据类型也可以存储非整数的有理数值。
[输入]
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 字符串
字符串变量可以用于存储文本。
[输入]
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)。
[输入]
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中的列表指的是一组有序的数值集合。
[输入]
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中的集合指的是一组无序的数值集合。
[输入]
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 字典
字典是一种数据结构,可以根据键存储数值。
[输入]
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语句设置代码被执行的下一个条件。
[输入]
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循环
[输入]
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循环
[输入]
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跳过。
[输入]
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定义一个函数。
[输入]
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 程序参数
程序可以通过命令行传递参数。
[输入]
#引入系统库以使用命令行参数列表
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写入两行文字,然后读取它们,最后将其打印到输出中。
[输入]
#写入文件'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