Python编程常用的十大语法和代码汇总,学会他事半功倍

Stella981
• 阅读 653

Python编程常用的十大语法和代码汇总,学会他事半功倍 Python编程常用的十大语法和代码汇总,学会他事半功倍

Python是一种通用的编程和脚本语言。它的简单性和丰富的库使得快速开发一个符合现代技术需求的应用成为可能。Python代码写在后缀为.py文件中,可以用命令python执行。

C.1.1 Python的“Hello World”实例

以下为一个基于Python的简单程序,仅打印一行文本。

[输入]

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

[输出]

$ python example00_helloworld.pyHello World!

C.1.2 注释

注释不会被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.

C.2 数据类型

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

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

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

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

C.2.1 整型

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

[输入]

# 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.

C.2.2 浮点型

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

[输入]

# 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.

C.2.3 字符串

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

[输入]

# 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.

C.2.4 元组

元组数据类型类似于数学中的向量。例如,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.

C.2.5 列表

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]

C.2.6 集合

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'])

C.2.7 字典

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

[输入]

# 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.

C.3 控制流

条件语句,即我们可以使用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.

C.3.1 for循环

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

C3.1.1 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

C3.1.2 列表的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

C3.1.3 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

C.3.2 函数

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.

C.3.3 程序参数

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

[输入]

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'].

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 filefile = open("test.txt","r")print file.read()

[输出]

$ python example15_file.pyfirst linesecond line

Python编程常用的十大语法和代码汇总,学会他事半功倍

欢迎大家点赞,留言,转发,转载,****感谢大家的相伴与支持

万水千山总是情,点个【在看】行不行

*声明:本文于网络整理,版权归原作者所有,如来源信息有误或侵犯权益,请联系我们删除或授权事宜。

本文分享自微信公众号 - python教程(pythonjc)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Java修道之路,问鼎巅峰,我辈代码修仙法力齐天
<center<fontcolor00FF7Fsize5face"黑体"代码尽头谁为峰,一见秃头道成空。</font<center<fontcolor00FF00size5face"黑体"编程修真路破折,一步一劫渡飞升。</font众所周知,编程修真有八大境界:1.Javase练气筑基2.数据库结丹3.web前端元婴4.Jav
Stella981 Stella981
3年前
Python3:sqlalchemy对mysql数据库操作,非sql语句
Python3:sqlalchemy对mysql数据库操作,非sql语句python3authorlizmdatetime2018020110:00:00coding:utf8'''
Stella981 Stella981
3年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Stella981 Stella981
3年前
Python之time模块的时间戳、时间字符串格式化与转换
Python处理时间和时间戳的内置模块就有time,和datetime两个,本文先说time模块。关于时间戳的几个概念时间戳,根据1970年1月1日00:00:00开始按秒计算的偏移量。时间元组(struct_time),包含9个元素。 time.struct_time(tm_y
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
11个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这