Python学习(二):入门篇:python中流程控制与函数编写,python中流,python中流程控


python中流程控制与函数编写Last Eidt 2014/5/2转载请注明出处http://blog.csdn.net/jxlijunhao

一,流程控制 1)布尔逻辑 Python中利用True来表示逻辑真,False来逻辑假 not :非 and:与 or :或 == :逻辑等
>>> False==TrueFalse>>> False==FalseTrue>>> not FalseTrue>>> False and FalseFalse>>> False and TrueFalse>>> False or TrueTrue
布尔运算的优先级(从高到低) p==p p!=q not p p and q p or q
2)if 语句 Python的一个与众不同的之处是,使用缩进来进行代码块的标识,处于相同的缩进的代码属于同一块。 缩进量很重要,在Python语句中,多一个或者少一个空格都可能导致错误。可以使用Sublime Text等工具来编辑 if 语句1: ... else: ...
pwd=input(‘please input the password:   ‘)if pwd==‘admin‘:    print ‘success!‘else:    print ‘error!‘    

或者 if 语句1: ... elif 语句2: ... elif 语句3: ... else: ...
score=int(input(‘please input the score: ‘))if score>=90:    print ‘A‘elif 80<=score<90:    print ‘B‘elif 60<=score<70:    print ‘C‘else:     print ‘D‘

3)循环 for ,while
pets=[‘dog‘,‘cat‘,‘pig‘]for i in range(len(pets)):    print pets[i]

>>> dogcatpig

>>> while i<10:print ii=i+1    #Python中没有 ++  --23456789

跳出循环可以用break ,也有continue与其他高级语言是一样的作用
total=0while True:    if total<100:        total=total+2    else:        total=total-2        breakprint total    

二,函数的编写 1)在Python中要使用某些函数要导入相应的包 import ** 2)自定义函数
import mathdef area(r):‘‘‘ return the area of a cicle‘‘‘return math.pi*r**2
函数,变量的命名规则与其他高级语言一样的。 ‘‘‘ ....‘‘‘内容是函数的文档
 >>>print(area.__doc__) return the area of a circle
要注意变量的作用域!!! 可以为函数参数设定默认值
def greet(name,greeting=‘hello‘):      ....
3)创建模块 要创建模块可以创建一个.py文件,在其中包含若干函数 要使用是导入即可。这个地方很容易出问题~~~大家自已尝试一下吧 要查看一个模块下有哪些函数,比如
import myfiledir(myfile)

转载请注明出处http://blog.csdn.net/jxlijunhao

Python学习(二):入门篇:python中流程控制与函数编写,布布扣,bubuko.com

Python学习(二):入门篇:python中流程控制与函数编写

评论关闭