收藏|Python常用的语法和代码

189 阅读2分钟

Python的“Hello World”

输入

source_code/appendix_c_python/example00_helloworld.pyprint "Hello World!"

输出

$ python example00_helloworld.pyHello World

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

输入

# source_code/appendix_c_python/example01_comments.pyprint "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.

数据类型

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

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

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

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

整型

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

输入

# source_code/appendix_c_python/example02_int.pyrectangle_side_a = 10rectangle_side_b = 5rectangle_area = rectangle_side_a * rectangle_side_brectangle_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.

浮点型

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

输入

# source_code/appendix_c_python/example03_float.pypi = 3.14159circle_radius = 10.2circle_perimeter = 2 * pi * circle_radiuscircle_area = pi * circle_radius * circle_radiusprint "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.

字符串

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

输入

# source_code/appendix_c_python/example04_string.pyfirst_name = "Satoshi"last_name = "Nakamoto"full_name = first_name + " " + last_nameprint "The inventor of Bitcoin is", full_name, "."

输出

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

元组

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

输入

# source_code/appendix_c_python/example05_tuple.pyimport mathpoint_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.

列表

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

输入

# source_code/appendix_c_python/example06_list.pysome_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]

集合

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

输入

# source_code/appendix_c_python/example07_set.pyfrom sets import Setboys = Set(['Adam', 'Samuel', 'Benjamin'])girls = Set(['Eva', 'Mary'])teenagers = Set(['Samuel', 'Benjamin', 'Mary'])print 'Adam' in boysprint 'Jane' in girlsgirls.add('Jane')print 'Jane' in girlsteenage_girls = teenagers & girls #intersectionmixed = boys | girls #unionnon_teenage_girls = girls - teenage_girls #differenceprint teenage_girlsprint mixedprint non_teenage_girls

输出

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

字典

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

输入

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

输出

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

控制流

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

输入

# source_code/appendix_c_python/example09_if_else_elif.pyx = 10if 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.

for循环

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

range的for循环

输入

source_code/appendix_c_python/example10_for_loop_range.pyprint "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

列表的for循环

输入

source_code/appendix_c_python/example11_for_loop_list.pyprimes = [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

break和continue

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

输入

source_code/appendix_c_python/example12_break_continue.pyfor 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

函数

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

输入

source_code/appendix_c_python/example13_function.pydef 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.

程序参数

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

输入

source_code/appendix_c_python/example14_arguments.py#引入系统库以使用命令行参数列表import sysprint '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'].

文件读写

下面程序将向文件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 filefile = open("test.txt","r")print file.read()

输出

$ python example15_file.pyfirst linesecond line

以上就是本次分享的全部内容,现在想要学习编程的小伙伴指路微信公众号-Python编程学习圈,更多python干货分享!