iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >【Python】02、Python过程型
  • 913
分享到

【Python】02、Python过程型

过程Python 2023-01-31 01:01:23 913人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

Python过程型程序设计快速入门数据结构     程序=数据结构+算法数据结构:     通过某种方式(例如对元素进行编号)组织在一起的数据元素的集合,这些数据元素可以是数字或者字符,甚至可以是其它的数据结构。      python的最


Python过程型程序设计快速入门

数据结构

     程序=数据结构+算法

数据结构:

     通过某种方式(例如对元素进行编号)组织在一起的数据元素的集合,这些数据元素可以是数字或者字符,甚至可以是其它的数据结构。

      python的最基本数据结构是序列

      序列中的每个元素被分配一个序号(即元素的位置),也称为索引:索引从0开始编号

      Python包含6中内建的数据序列:列表、元祖、字符串、Unicode字符串、buff对象和xrange对象


python的关键要素

基本数据类型

对象引用

组合数据类型

逻辑操作符

控制流语句

算术操作符

输入/输出

函数的创建与调用


一、python中的基本数据类型

任何程序语言都必须能够表示基本数据项

python中字符串一定要加引号,单引号和双引号不加区别使用,数值不加引号

python中的基本数据类型分为:

        可变类型

        不可变类型


python中的基本数据类型有:

1、Integral类型

整型:不可变类型

            -257,20162

布尔型:

             True,False         #不加引号

In [1]: name=xj
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-988278c7330a> in <module>()
----> 1 name=xj

NameError: name 'xj' is not defined                  

In [2]: name="xj"        # python中字符串一定要加引号,'和"不加区别使用,数值不用加引号

In [3]: id(xj)           
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-5ef15bb84886> in <module>()
----> 1 id(xj)

NameError: name 'xj' is not defined

In [4]: id(name)        # id()是python的内建函数,返回对象的内存地址
Out[4]: 43560552

In [5]: id("xj")
Out[5]: 43560552

In [6]: id (name)
Out[6]: 43560552

In [7]: id    (name)
Out[7]: 43560552

In [8]: name=xiejun
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-8-8634eac01eaa> in <module>()
----> 1 name=xiejun

NameError: name 'xiejun' is not defined

In [9]: name="xiejun"      # 改变了指向变量的内存对象引用,原43560552的内存地址对象并没有改变

In [10]: id(name)
Out[10]: 43650480           

In [11]: id("xiejun")
Out[11]: 43650480

In [12]: id('xiejun')
Out[12]: 43650480

In [13]: id('name')
Out[13]: 140268695543408


2、浮点类型    不可变类型

浮点数:

              3.141592

复数:

               3+6j

十进制数字:


3、字符串       不可变类型

            'GNU is Not Unix',“hello”

在python中,字符串是一种序列,可以“分片”

In [22]: name
Out[22]: 'xiejun'

In [23]: name[0]
Out[23]: 'x'

In [24]: name[4]
Out[24]: 'u'


内建函数type:

In [25]: type(name)    #返回对象的数据类型
Out[25]: str

In [26]: num=1

In [27]: type(num)
Out[27]: int

In [28]: test=1.234

In [29]: type(test)
Out[29]: float

In [30]: id(test)
Out[30]: 44558656

In [31]: test=2.3

In [32]: id(test)
Out[32]: 44558560

In [33]: type(test)
Out[33]: float


二、对象引用(变量)

1、对象引用概述

python将所有数据存为内存对象

python中,变量事实上是指内存对象的引用

意思是变量名和内存对象是分开存放的

动态类型:

       在任何时刻,只要需要,某个对象引用都可以重新引用一个不同的对象(可以用不同的数据类型)

“=”用于将变量名与内存中的某对象绑定:如果对象事先存在,就直接进行绑定;否则,则由“=”创建引用的对象


2、变量命名规则

只能包含字母、数字和下划线,且不能以数字开头

区分字母大小写

禁止使用保留字

        Python2与python3的保留字有所不同


命名惯例:

       以单一下划线开头变量名(_x)不会被from module import * 语句导入

       前后有下划线的变量名(__x__)是系统定义的变量名,对python解释器有特殊意义

       以两个下划线开头但结尾没有下划线的变量名(__x)是类的本地变量

       交互式模式下,变量名“_”用于保存最后表达式的结果

注意:变量名没有类型,对象才有

n [1]: a='mageedu'

In [2]: type(a)
Out[2]: str

In [3]: a=3.14

In [4]: type(a)
Out[4]: float

In [5]:


三、组合数据类型

组合基本数据类型就是数据结构

数据结构:通过某种方式(例如对元素进行编号)组织在一起的数据元素的集合

Python常用的组合数据类型:

1、序列类型

列表:使用[]创建,如[‘Call’,’me’, ‘Ishmeal’,’.’]

In [49]: l1=["This",'is', 1 ,"pig"]

In [50]: id(l1)
Out[50]: 45138648

In [51]: l1=["This",'is', 12,"pig"]

In [52]: id(l1)
Out[52]: 45337848

In [54]: print l1[2]
12

In [56]: print l1[1]
is

In [57]: print l1[1][0]
i

In [60]: l1[1]="IS"

In [61]: l1[1]
Out[61]: 'IS'

In [62]: type(l1)
Out[62]: list

In [63]: id(l1)
Out[63]: 45337848

元组: 使用()创建,如(‘one’, ‘two’)


字符串也属于序列类型

In [66]: name='xiejun'

In [67]: print name
xiejun

In [68]: print name[0]
x

In [69]: print name[1]
i

In [70]: print name[0:1]   #切片
x

In [71]: print name[0:2]
xi

In [72]: print name[:2]
xi

In [73]: print name[:6]
xiejun

In [74]: print name[:6:2]   #步调
xeu

In [75]: print name[:]
xiejun

In [76]: print name[::2]
xeu


2、集合类型

集合


3、映射类型

字典          

相当于键值对

In [196]: l1={a:31,'b':78}         #注意,字符串要带引号

In [198]: l1[a]
Out[198]: 31

In [199]: l1[b]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-199-c5320b7f95da> in <module>()
----> 1 l1[b]

KeyError: 4

In [200]: l1['b']
Out[200]: 78

In [201]: l1['a']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-201-79b170f93f5b> in <module>()
----> 1 l1['a']

KeyError: 'a'


列表是可变序列,元组是不可变序列

Python中,组合数据类型也是对象,因此其可以嵌套

如:[‘hello’,’world’, [1,2,3]]

实质上,列表和元组并不真正存储数据,而是存放对象引用


Python对象可以具有其可以被调用的特定“方法(函数) ”

对象由类实例化而来

元组、列表以及字符串等数据类型是“有大小的”,也即,其长度可使用内置函数len()测量;

In [77]: len(name)
Out[77]: 6

In [78]: len(l1)
Out[78]: 4


4、类、对象、方法、属性

        python中一切皆为对象

所谓对象:我自己就是一个对象,我玩的电脑就是对象,坐着的椅子就是对象,家里养的小狗也是一个对象。。。。。。

       我们通过描述属性(特征)和行为来描述一个对象的。比如家里的小狗,它的颜色,大小,年龄,体重等是它的属性或特征。它会汪汪叫,会摇尾巴等是它的行为。

我们在描述一个真实对象(物体)时包括两个方面:

      它是什么样的(属性或特征)

      它可以做什么(行为)

       在python中,一个对象的特征也称为属性(attribute)。它所具有的行为也称为方法(method)

结论:对象=属性+方法

在python中,把具有相同属性和方法的对象归为一个类(class)

比如人类,动物,植物等等,这些都是类的概念。

      类是对象的模板或蓝图,类是对象的抽象化,对象是类的实例化。类不代表具体的事物,而对象表示具体的事物。

类可以看作自定义的数据类型,数据类型也可以看作是内置的类,类和类型没有明显的区别

In [311]: a="nihao"

In [312]: a.
a.capitalize  a.find        a.isspace     a.partition   a.rstrip      a.translate
a.center      a.fORMat      a.istitle     a.replace     a.split       a.upper
a.count       a.index       a.isupper     a.rfind       a.splitlines  a.zfill
a.decode      a.isalnum     a.join        a.rindex      a.startswith  
a.encode      a.isalpha     a.ljust       a.rjust       a.strip       
a.endswith    a.isdigit     a.lower       a.rpartition  a.swapcase    
a.expandtabs  a.islower     a.lstrip      a.rsplit      a.title       

In [312]: str.
str.capitalize  str.format      str.isupper     str.rfind       str.startswith
str.center      str.index       str.join        str.rindex      str.strip
str.count       str.isalnum     str.ljust       str.rjust       str.swapcase
str.decode      str.isalpha     str.lower       str.rpartition  str.title
str.encode      str.isdigit     str.lstrip      str.rsplit      str.translate
str.endswith    str.islower     str.mro         str.rstrip      str.upper
str.expandtabs  str.isspace     str.partition   str.split       str.zfill
str.find        str.istitle     str.replace     str.splitlines  

In [313]: a.islower()
Out[313]: True

In [317]: str.islower(a)
Out[317]: True

In [318]: 

In [320]: a.islower(a)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-320-602f3f86606c> in <module>()
----> 1 a.islower(a)

TypeError: islower() takes no arguments (1 given)


四、逻辑操作符

逻辑运算是任何程序设计语言的基本功能

Python提供了4组逻辑运算

1、身份操作符

is: 判定左端对象引用是否相同于右端对象引用;也可以与None进行;

In [82]: name="xiejun"

In [83]: test="xiejun"

In [84]: test1="xiexie"

In [85]: name is test
Out[85]: True

In [86]: name is  test1
Out[86]: False

In [87]: print "name is test"
name is test

In [88]: print name is test
True

In [89]: type(name)
Out[89]: str

In [90]: type(test1)
Out[90]: str

In [91]: type(name) is type(test1)
Out[91]: True


2、比较操作符

<, >, <=, >=, !=, ==


3、成员操作符

in或not in:测试成员关系


4、逻辑运算符

and, or, not


五、控制流语句

控制流语句是过程式编程语言的基本控制机制

Python的常见控制流语句:

(1)if


(2)while


(3)for…in


(4)try


if boolean_expression1:
   suite1
elif boolean_expression2:
   suite2
…
else:
   else_suite


for variable in iterable:
     suite


while boolean_expression:
   suite


六、算术操作符

Python提供了完整的算术操作集

很多的Python数据类型也可以使用增强的赋值操作符,如+=、-=等;

同样的功能,使用增强型赋值操作符的性能较好;

Python的int类型是不可变的,因此,增强型赋值的实际过程是创建了一个新的对象来存储结果后将变量名执行了重新绑定


七、输入 /输出

1、input

现实中,具有实际功能的程序必须能够读取输入(如从键盘或文件中),以及产生输出,并写到终端或文件中;

Python的输入/输出

输出:

Python3:print()函数

Python2:print语句

输入: #和键盘交互时

input()

raw_input()    #推荐使用这个,

In [93]: raw_input("please input a num: ")
please input a num: 3
Out[93]: '3'

In [94]: a=raw_input("please input a num: ")
please input a num: hello

In [95]: a
Out[95]: 'hello'

注意:

        在python2.x中raw_input( )和input( ),两个函数都存在,其中区别为使用input和raw_input都可以读取控制台的输入,但是input和raw_input在处理数字时是有区别的:

raw_input( ) ---  将所有输入作为字符串看待,返回字符串类型,输入字符串不需使用引号

input( ) --- 在对待纯数字输入时具有自己的特性,它返回所输入的数字的类型( int, float ),输入字符串需要使用引号

        在python3.x中raw_input( )和input( )进行了整合,去除了raw_input( ),仅保留了input( )函数,其接收任意任性输入,将所有输入默认为字符串处理,并返回字符串类型。


2、print

       Python解释器提供了3种标准文件对象,分别为标准输入、标准输出和标准错误,它们在sys模块中分别以sys.stdin、sys.stdout和sys.stderr形式提供

Python的print语句实现打印——一个对程序员友好的标准输出流接口

从技术角度来讲,print是把一个或多个对象转换为其文本表达形式,然后发送给标准输出或另一个类似文件的流

在Python中,打印与文件和流的概念联系紧密

文件写入方法是把字符串写入到任意文件

print默认把对象打印到stdout流,并添加了一些自动的格式化

实质上,print语句只是Python的人性化特性的具体实现,它提供了sys.stdout.write()的简单接口,再加一上些默认的格式设置

print接受一个逗号分隔的对象列表,并为行尾自动添加一个换行符,如果不需要,则在最后个元素后添加逗号

In [75]: print(123)
123

In [76]: print(456)
456

In [77]: print(123);print(456)
123
456

In [78]: print(123),;print(456)
123 456

In [79]: print(123),;print(456),
123 456

In [80]:

Python print 输出不换行

Python 版本 2.7

print "123",print "456"

加逗号
缺点:中间有间隔

print('123123', end='')


print格式化输出:

         print “String %format1 %format2 …” %(variable1, varialbe2, …)


format可以使用的字符:       

      wKioL1fSMHaCeTBdAABHNSGjAwA839.jpg


In [111]: num=7.9

In [112]: num
Out[112]: 7.9

In [113]: print num
7.9

In [114]: print "This is %f"%(num)
This is 7.900000               #f默认是小数点后6位

In [115]: print "This is %f" %(num)
This is 7.900000

In [116]: print "This is %f" %num
This is 7.900000

In [117]: print "This is %f" % num
This is 7.900000

In [118]: print "This is %f" %  num
This is 7.900000

In [119]: print "This is %d" %  num
This is 7


In [129]: num1=7.9

In [130]: num2=23.45

In [133]: print "This nums are %d and %f" %(num1,num2)
This nums are 7 and 23.450000

In [134]: print "This nums are %d and %f" %(num1,567)
This nums are 7 and 567.000000



In [139]: name="xiejun"

In [140]: print "Then anme is %s" %name  #作为字符串输出,包含了数据转换的过程
Then anme is xiejun

In [141]: print "Then anme is %s" %num1
Then anme is 7.9


In [143]: dir(__builtin__)       #查看内建模块builtin内所有的内建函数

In [144]: help(str)        #help()查看函数的帮助信息

In [164]: print "Then anme is %s and %%" %num1
Then anme is 7.9 and %

%后面format前面可以使用的修饰符,(如果有,则只能按如下顺序)

       %[(name)][flags][width][.precision]typecode

typecode就是上面的format和图中的字符

位于括号中的一个属于后面的字典的键名,用于选出一个具体项

下面标志中的一个或多个

       -:表示左对齐,默认为右对齐

       +:表示包含数字符号,正数也会带“+”

       0:表示一个零填充

一个指定最小宽度的数字

一个小数点,用于按照精度分割字段的宽度

一个数字,指定要打印字符串中的最大字符个数,浮点数中小数点之后的位数,或者整数的最小位数;


In [184]: print "Then anme is %20f and %+0d" %(num1,num2)
Then anme is             7.900000 and +23

In [185]: print "Then anme is %10f and %+ d" %(num1,num2)
Then anme is   7.900000 and +23

In [186]: print "Then anme is %10f0 and %+d" %(num1,num2)
Then anme is   7.9000000 and +23

In [187]: print "Then anme is %010f and %+d" %(num1,num2)
Then anme is 007.900000 and +23

In [188]: print "Then anme is %010f and %+0d" %(num1,-23)
Then anme is 007.900000 and -23

In [190]: print "Then anme is %015f and %+0d" %(num1,-23)
Then anme is 00000007.900000 and -23

In [191]: print "Then anme is %+015f and %+0d" %(num1,-23)
Then anme is +0000007.900000 and -23

In [192]: print "Then anme is %-+015f and %+0d" %(num1,-23)
Then anme is +7.900000       and -23

In [194]: print "Then anme is %+015.8f and %+0d" %(num1,-23)   #.后面的位数
Then anme is +00007.90000000 and -23


例子:

d={‘x’:32, ‘y’:27.490325, ‘z’:65}

print “%(x)-10d %(y)0.3g” % d

In [241]: d={'x':32,'y':27.490325,'z':65}

In [242]: print "%(x)10d%(y)0.3g" %d
        3227.5

In [243]: print "%(x)-10d%(y)0.3g" %d
32        27.5


八、函数的创建与调用

函数是实现模块化编程的基本组件

Python使用def语句定义函数

函数可以参数化,通过传递不同的参数来调用

每个Python函数都有一个返回值,默认为None,也可以使用“return value”明确定定义返回值

def语句会创建一个函数对象,并同时创建一个指向函数的对象引用

函数也是对象,可以存储在组合数据类型中,也可以作为参数传递给其它函数

callable()可用于测试函数是否可调用

语法:

def functionName(arguments):
suite

例子:

In [252]: def printName(name):
   .....:     print name
   .....:     

In [255]: printname('xiejun')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-255-3418def8f6f5> in <module>()
----> 1 printname('xiejun')

NameError: name 'printname' is not defined

In [256]: printName('xiejun')
xiejun

In [257]: test="xiejun"

In [258]: printName('test')       #还可以向参数传递参数
test

In [259]: printName(test)
xiejun


In [265]: callable(name)
Out[265]: False

In [266]: callable(printname)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-266-828267093354> in <module>()
----> 1 callable(printname)

NameError: name 'printname' is not defined

In [267]: callable(printName)
Out[267]: True


Python有众多内置函数

Python标准库拥有众多内置模块,这些模块拥有大量函数

Python模块实际上就是包含Python代码的.py文件,其拥有自定义的函数与类及变量等

导入模块使用import语句进行,后跟模块名称(不能指定模块文件名的后缀.py)

导入一个模块后,可以访问其内部包含的任意函数、类及变量

In [289]: import random

In [290]: random.
random.BPF              random.division         random.random
random.LOG4             random.expovariate      random.randrange
random.NV_MAGICCONST    random.gammavariate     random.sample
random.RECIP_BPF        random.gauss            random.seed
random.Random           random.getrandbits      random.setstate
random.SG_MAGICCONST    random.getstate         random.shuffle
random.SystemRandom     random.jumpahead        random.triangular
random.TWOPI            random.lognormvariate   random.uniform
random.WichmannHill     random.normalvariate    random.vonmisesvariate
random.betavariate      random.paretovariate    random.weibullvariate
random.choice           random.randint          


In [291]: random.random()
Out[291]: 0.5583019427071519

In [292]: random.random()
Out[292]: 0.2170560009864373

In [293]: random.random()
Out[293]: 0.8198573354154595


In [271]: dir(__builtin__)   #查看模块的所有内置函数

dir(),id(),type(),str(),help(),len(),callable()

In [275]: help(xrange)



Help on class xrange in module __builtin__:

class xrange(object)
 |  xrange(stop) -> xrange object
 |  xrange(start, stop[, step]) -> xrange object
 |  
 |  Like range(), but instead of returning a list, returns an object that
 |  generates the numbers in the range on demand.  For looping, this is 
 |  slightly faster than range() and more memory efficient.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 
 
 In [284]: range(10)
Out[284]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [285]: range(0,10)
Out[285]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [286]: range(1,10)
Out[286]: [1, 2, 3, 4, 5, 6, 7, 8, 9]

In [287]: range(1,10,2)
Out[287]: [1, 3, 5, 7, 9]

xrange 用法与 range 完全相同,所不同的是生成的不是一个list对象,而是一个生成器。

In [57]: xrange(5)
Out[57]: xrange(5)

In [58]: list(xrange(5))
Out[58]: [0, 1, 2, 3, 4]

由上面的示例可以知道:要生成很大的数字序列的时候,用xrange会比range性能优很多,因为不需要一上来就开辟一块很大的内存空间。

xrange 和 range 这两个基本上都是在循环的时候用。

   for i in range(0, 100):    
        print i    
    
   for i in xrange(0, 100):    
       print i

这两个输出的结果都是一样的,实际上有很多不同,range会直接生成一个list对象:

   a = range(0,100)    
   print type(a)    
   print a    
   print a[0], a[1]

输出结果:

<type 'list'>    
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,93, 94, 95, 96, 97, 98, 99]    
0 1

而xrange则不会直接生成一个list,而是每次调用返回其中的一个值:

a = xrange(0,100)    
print type(a)    
print a    
print a[0], a[1]

输出结果:

<type 'xrange'>    
xrange(100)    
0 1

   所以xrange做循环的性能比range好,尤其是返回很大的时候。尽量用xrange吧,除非你是要返回一个列表。


  • 九、
    Python编程基础及编程风格

1、语句和语法

注释

        #:可以从一行的任何地方开始

续行

       \:

      ''':闭合操作符,单一语句跨多行           #三个单引号或三个双引号

代码组

      缩进相同的一组语句构成的一个代码块

      首行以关键字开始,如if、while等,以冒号结束

      Python使用缩进来分隔代码组,同一代码组的代码行必须严格左对齐,否则会造成语法错误

[root@node3 test]# cat 1.py 
#/usr/local/bin/python27/bin/python2.7
name="xiejun"

def printName(a):
    print a
num=3
print num
printName(name)

[root@Node3 test]# /usr/local/python27/bin/python2.7 1.py 
3
xiejun


同一行放置多个语句

      ;以分号做为分隔符

模块

     每一个Python脚本文件都可以被当成是一个模块

            模块名称就是脚本文件的名称

     模块里的代码可以是一段直接执行的脚本(导入时就会被执行),也可以是一些类似库函数的代码从而可由别的模块执行导入(import)

[root@Node3 test]# vi mod.py 


[root@Node3 test]# cat mod.py 
#/usr/local/python27/bin/python2.7
#

def printName(a):
    print a
    b="black"
    print a+b


2、标识符

标识符是计算机语言中允许作为名字的有效字符串集合

其中有一部分是关键字,它们是语言的标识符,因此是保留字, 不能用于其它用途

Python还有称为“内建”的标识符集合,虽不是保留字,仍不推荐使用这些特别的名字


Python标识符

       第一个字符只能使用字母或下划线

       余下的字符可以使用字母、数字或下划线

       区分字符大小写


Python3的关键字:wKiom1fSlezjLOwfAAev9F88RjQ344.jpg


3、Python基本编程风格

注释

       既不能缺少注释,亦要避免过渡注释

文档

       Python允许通过__doc__动态获得文档字串;代码段都可以有文档

In [307]: help(str)


Help on class str in module __builtin__:

class str(basestring)
 |  str(object='') -> string
 |  
 |  Return a nice string representation of the object.
 |  If the argument is a string, the return value is the same object.
 |  
 |  Method resolution order:
 |      str
 |      basestring
 |      object
 |  
 |  Methods defined here:
 |  
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |  
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x
 |  
:


In [305]: str.__doc__
Out[305]: "str(object='') -> string\n\nReturn a nice string representation of the object.\nIf the argument is a string, the return value is the same object."

In [306]: print str.__doc__
str(object='') -> string

Return a nice string representation of the object.
If the argument is a string, the return value is the same object.

缩进

       统一缩进4个字串

标识符名称

       见名知义


Python风格指南

https://code.Google.com/p/soc/wiki/PythonStyleGuide

译文:Http://www.elias.cn/Python/PythonStyleGuide


Python命名惯例:

        以单一下划线开头的变量名(_x)不会被from module import *语句导入

        前后有下划线的变量名(__x__)是系统变量名,对解释器有特殊意义

        以两个下划线开头、但结尾没有下划线的变量名(__x)是类的本地变量

        交互式模式下,只有单个下划线的变量名(_)用于保存最后表达式的结果


4、Python文件结构

wKioL1fSlw6QavkhAADOJBsDEsQ958.jpg


5、Python文件主程序

主程序

       无论当前模块是被别的模块导入还是作为脚本直接执行,都会执行这部分代码

注意:所有的模块都有能力执行代码

最高级别的Python语句(没有缩进的)在模块被导入时就会执行, 无论是否真的需要执行

妥当的做法:除了那些真正需要执行的代码以外,所有的功能代码都通过函数建立,因此

        仅在主程序模块中编写大量的顶级可执行代码

        用于被导入的模块只应该存在较少的顶级执行代码


__name__指示模块应该如何被加载:

       如果模块是被导入,__name__的值是模块名字

       如果模块是直接执行,__name__的值是‘__main__’

       每个模块都有一个名为__name__的内建变量,此变量值会根据调用此模块的方式发生变化,

如果此文件被作为模块导入,则__name__的值为模块名称,如果此文件被直接执行,则__name__的值为”__main__“

 

       这篇文章是对python的整个体系结构做一个了解,后面将每一项内容都将详细展开学习

--结束END--

本文标题: 【Python】02、Python过程型

本文链接: https://www.lsjlt.com/news/183071.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 【Python】02、Python过程型
    Python过程型程序设计快速入门数据结构     程序=数据结构+算法数据结构:     通过某种方式(例如对元素进行编号)组织在一起的数据元素的集合,这些数据元素可以是数字或者字符,甚至可以是其它的数据结构。      python的最...
    99+
    2023-01-31
    过程 Python
  • Python Learning: 02
      OK, let's continue. Conditional Judgments and Loop if if-else if-elif-else while for break continue multiple loop ...
    99+
    2023-01-30
    Python Learning
  • python day 02
    格式化输出 %s:字符串占位符 %d:数字占位符 例如: "你好%s,我是%s,今年%d岁了。" % ("小明","小红",18) 输出: 你好小明,我是小红,今年18岁了。 ...
    99+
    2023-01-31
    python day
  • Python全栈day 02
    一、循环语句 while 用法 num = 1 while num <= 10: print(num) num += 1 # 循环打印输出1-10 while else 用法 num = 1 while n...
    99+
    2023-01-31
    Python day
  • 【Python3】02、python编码
    一、ASCII、Unicode和UTF-8的区别       因为字符编码的问题而苦恼不已,于是阅读了大量的博客,再进行了一定的测试,基本搞清楚了编码问题的前因后果。1、字符集和字符编码      计算机中储存的信息都是用二进制数表示的;而...
    99+
    2023-01-31
    python
  • python入门基础教程02 Pytho
    02 Python简介Python简介Python是一种解释型、面向对象、动态数据类型的高级程序设计语言,属于应用层软件。自从20 世纪90 年代初Python语言诞生至今,它逐渐被广泛应用于处理系统管理任务、自动化运维、图像处理游戏和We...
    99+
    2023-01-31
    基础教程 入门 python
  • 2019-02-18 扩展Python控
    "中文编程"知乎专栏原文地址 续前文扩展Python控制台实现中文反馈信息, 实现了如下效果: >>> 学 Traceback (most recent call last): File "<console&...
    99+
    2023-01-30
    Python
  • python日常笔记-02
    #!/usr/bin/python#-- coding: UTF-8 --(1).'''在python中,for循环后的in跟随一个序列的话,循环每次使用的是序列元素,而不是序列的下标'''s = 'saflasngsagleaoiga'f...
    99+
    2023-01-31
    日常 笔记 python
  • 2019-02-13 Python爬虫问
    soup=BeautifulSoup(html.text,'lxml') #data=soup.select('body > div.main > div.ctr > div > div.newsmcont &g...
    99+
    2023-01-30
    爬虫 Python
  • 2019-02-10 扩展Python控
    "中文编程"知乎专栏原文地址 参考了周蟒的实现, 运行效果如下: $ python3 解释器.py Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 05:52:31) [GCC 4.2.1 C...
    99+
    2023-01-30
    Python
  • Python图形编程探索系列-02-框架
    跳转到我的博客 在主窗口root中放置三个容器用于容纳组件,容器采用框架设计。 import tkinter as tk root = tk.Tk() root.geometry('800x600+200+200') ro...
    99+
    2023-01-30
    框架 图形 系列
  • upload-labs靶场Pass-02思路过程
    上传2.php上传失败提示:文件类型不正确,请重新上传!  2. 查看提示内容  3. 打开Burp Suite抓包修改Content-Type为如图内容后放包  4. 访问http://10.10.10.127/upload/可以...
    99+
    2023-09-09
    php 安全
  • Python爬虫-02:HTTPS请求与
    目录 1. HTTP和HTTPS 1.1. HTTP的请求和响应流程:打开一个网页的过程 1.2. URL 2. ...
    99+
    2023-01-30
    爬虫 Python HTTPS
  • Python打印数据类型的全过程
    目录打印数据类型基本数据类型与打印语句打印数据类型 右侧编辑器中的代码功能是输出当前 num3 的数据类型,输出结果为: <class 'float'> ...
    99+
    2024-04-02
  • Python面试宝典之基础篇-02
    我觉得你如果正在找工作,我的Python面试宝典几期教程,你一定得花时间看完了!...
    99+
    2023-06-01
  • 02 python网络爬虫《Http和H
    一.HTTP协议   1.概念:     Http协议就是服务器(Server)和客户端(Client)之间进行数据交互(相互传输数据)的一种形式。 之间形成的特殊行话(黑话:(土匪)天王盖地虎,(我)宝塔镇河妖)称为协议。   2.Ht...
    99+
    2023-01-31
    爬虫 网络 python
  • python学习 三 02 再爬一个网站
     讨厌编程 2018-01-12 10:51 Python安装 python学习 一 python语法,及变量类型 python学习 二 爬一个图片网站上 python学习 二 02 爬一个图片网站,获得主链接...
    99+
    2023-01-31
    网站 python
  • Python深入02 上下文管理器
    上下文管理器(context manager)是Python2.5开始支持的一种语法,用于规定某个对象的使用范围。一旦进入或者离开该使用范围,会有特殊操作被调用 (比如为对象分配或者释放内存)。它的语法形式是with...as...关闭文件...
    99+
    2023-06-02
  • python安装过程
    python下载地址: http://python.org/download/选择适合自己系统的版本下载,我是用2.7的安装很简单,傻瓜式下一步就行,安装完后需要配置一下系统环境变量:右键“我的电脑”——属性——系统高级设置——高级——环境...
    99+
    2023-01-31
    安装过程 python
  • Python 开发环境搭建(02):Python 3.7 + Redhat 7 源码安装
    准备编译环境(环境如果不对的话,可能遇到各种问题,比如wget无法下载https链接的文件)yum groupinstall 'Development Tools'yum install zlib-devel bzip2-d...
    99+
    2023-06-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作