码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-05-03 17:17:00      阅读:442      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   ext   int   

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

一,流程控制
       1)布尔逻辑
             Python中利用True来表示逻辑真,False来逻辑假
             not :非
             and:与
             or   :或
             ==  :逻辑等
>>> False==True
False
>>> False==False
True
>>> not False
True
>>> False and False
False
>>> False and True
False
>>> False or True
True
          布尔运算的优先级(从高到低)
          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]

>>> 
dog
cat
pig

   
>>> while i<10:
	print i
	i=i+1    #Python中没有 ++  --
	
2
3
4
5
6
7
8
9

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

二,函数的编写
       1)在Python中要使用某些函数要导入相应的包  import  **
       2)自定义函数           
import math
def 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 myfile
dir(myfile)

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

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

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

标签:style   blog   class   code   ext   int   

原文地址:http://blog.csdn.net/jxlijunhao/article/details/24876025

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!