python 学习笔记2

来源:互联网 发布:小丸压制软件 编辑:程序博客网 时间:2024/06/06 19:26

  • 指定python编译器与使用注释
  • 条件语句
    • if语句
      • raw_input与input的区别
    • while语句
    • for循环
    • Break语句
  • 函数
    • 函数的定义
    • 使用global为函数外的变量赋值
    • 使用默认参数和指定参数
    • return和pass
    • DocStrings

7.指定python编译器与使用注释

一个简单的程序:

#!/usr/bin/python# Filename: expression.pylength = 5breadth = 2area = length * breadthprint 'Area is', areaprint 'Perimeter is', 2 * (length + breadth) 

这里第一句用#!指定了python编译器的路径,这个很重要。因为python3的语法与python2差异非常大,很多模块也不一样,所以需要指定编译器。这里是Python2的编译器,若是python3的,需要改为:#!…/python3
第二句的#表示单行注释,若多行注释,需要使用三引号(”’)括起来。
在命令行输入 python expression.py ,即可运行程序,得到输出:

Area is 10Perimeter is 14 

8.条件语句

if语句

例子:

#!/usr/bin/python# Filename: if.pynumber = 23guess = int(raw_input('Enter an integer : '))if guess == number:    print 'Congratulations, you guessed it.' # New block starts here    print "(but you do not win any prizes!)" # New block ends hereelif guess < number:    print 'No, it is a little higher than that' # Another block    # You can do whatever you want in a block ...else:    print 'No, it is a little lower than that'    # you must have guess > number to reach hereprint 'Done'# This last statement is always executed, after the if statement is executed 

上面的例子中,if后面有一个空格,之后是判断语句,之后跟一个冒号。执行语句另起一行,在if条件语句一个缩进之后。表示若满足if语句,则执行。上面的elif表示”else if”的意思,可以有也可以没有。后面的else同理。elif和else都要和if在同一个缩进。
运行的结果:

$ python if.pyEnter an integer : 50No, it is a little lower than thatDone$ python if.pyEnter an integer : 22No, it is a little higher than thatDone$ python if.pyEnter an integer : 23Congratulations, you guessed it.(but you do not win any prizes!)Done 

raw_input()与input()的区别

raw_input()函数获取用户输入的字符串,当作原始字符,然后自动添加引号放到字符串中。
若使用input()函数,则相当于没有了引号,直接当作字符串。然而没有引号的字符串是不合法的,这就要求用户输入的时候要加上引号,如Enter an integer :‘10’才是合法的。

注意:类型转换
如上面的

guess = int(raw_input('Enter an integer : '))

这里int()就是强制类型转换,把一个字符串类型转化为int类型。

在Python中没有switch语句。可以使用if..elif..else语句来完成同样的工作(在某些场合,使用字典会更加快捷。) 

while语句

python里的while语句可以有一个else从句,当跳出while循环之后可以执行else中的内容!

 #!/usr/bin/python# Filename: while.pynumber = 23running = Truewhile running:    guess = int(raw_input('Enter an integer : '))    if guess == number:        print 'Congratulations, you guessed it.'        running = False # this causes the while loop to stop    elif guess < number:        print 'No, it is a little higher than that'    else:        print 'No, it is a little lower than that'else:    print 'The while loop is over.'    # Do anything else you want to do hereprint 'Done' 

这个程序和上面的功能相同,都是让用户输入一个数,看是否与number相同。但是不同的是,这次用户可以输入次,根据给定的提示,这是一个猜数游戏。只有当用户猜中了程序才会结束。而上面的if的程序是运行一次即结束。

$ python while.pyEnter an integer : 50No, it is a little lower than that.Enter an integer : 22No, it is a little higher than that.Enter an integer : 23Congratulations, you guessed it.The while loop is over.Done 

for循环

每个程序猿都喜欢用for循环。python中for循环的格式更加简单,并且也可以使用else从句。else部分是可选的。如果包含else,它总是在for循环结束后执行一次,除非遇到break语句。

 #!/usr/bin/python# Filename: for.pyfor i in range(1, 5):    print ielse:    print 'The for loop is over' 

输出:

 $ python for.py1234The for loop is over

我们来看看不一样的地方。首先这里用的是range(start,end,gap)函数,这个函数的第一个变量为开始的元素。end元素为结束的元素的后一个元素(即不包含end!!!)。gap表示取数的间隔,若为负数,则从end-1开始取,一直到start,缺省的话为1,这个跟matlab很像。所以range(1,5)其实 i 取的是从1到4。另外这里用的是in,这个非常的好用。举个例子:我可以新建一个列表mylist,对于列表里的每一个元素都输出,这样就可以直接用

for element in mylist:    print element

不需要使用下标那么麻烦了

Break语句

break语句用于中止while或者for循环,若中断,则while或者for中的else从句都不被执行。当然,只中断离当前语句最近的那层while或者for循环。

Continue的用法与C中相同(略)

看完了条件语句,现在开始高级点的功能了。

9.函数

函数的定义

格式:
def 函数名(参数1,参数2…参数n):
—->函数体
—->…
记住,函数体内的语句的缩进必须比第一行要后,否则将会认为是函数外的语句。

#!/usr/bin/python# Filename: func_local.pydef func(x):    print 'x is', x    x = 2    print 'Changed local x to', xx = 50func(x)print 'x is still', x 

以上,从x=50开始即为函数外的部分,当执行这个程序时,从这一行开始执行,然后将x传入函数内。当函数内出现了同名的参数,则默认使用函数内的参数。所以,这个函数的输出为:

$ python func_local.pyx is 50Changed local x to 2x is still 50 

使用global为函数外的变量赋值

使用global可以引入为函数外的变量,对其进行赋值、更新等操作,但是我并不赞同这样做,这样会傻傻分不清哪个变量在哪里被定义。

#!/usr/bin/python# Filename: func_global.pydef func():    global x    print 'x is', x    x = 2    print 'Changed local x to', xx = 50func()print 'Value of x is', x 

输出:

$ python func_global.pyx is 50Changed global x to 2Value of x is 2 

使用默认参数和指定参数

可以在定义函数的时候,在变量的末尾声明默认参数,当调用函数时缺省该参数,则会使用默认值。也可以不按照顺序,但用指定参数的方法写变量值。

 #!/usr/bin/python# Filename: func_key.pydef func(a, b=5, c=10):    print 'a is', a, 'and b is', b, 'and c is', cfunc(3, 7)func(25, c=24)func(c=50, a=100)

输出

$ python func_key.pya is 3 and b is 7 and c is 10a is 25 and b is 5 and c is 24a is 100 and b is 5 and c is 50 

return和pass

在python中,return的作用和用法与在C中相同,只是不需要指定的返回类型,不赘述。pass为python特用的语句,其作用是在编译的时候忽略这一块。当写空函数或者空类的时候,若没有想好怎么写,用pass灰常方便!

 def someFunction():    pass 

DocStrings

ython有一个很奇妙的特性,称为 文档字符串 ,它通常被简称为 docstrings 。DocStrings是一个重要的工具,由于它帮助你的程序文档更加简单易懂,你应该尽量使用它。你甚至可以在程序运行的时候,从函数恢复文档字符串!

#!/usr/bin/python# Filename: func_doc.pydef printMax(x, y):    '''Prints the maximum of two numbers.    The two values must be integers.'''    x = int(x) # convert to integers, if possible    y = int(y)    if x > y:        print x, 'is maximum'    else:        print y, 'is maximum'printMax(3, 5)print printMax.__doc__ 

输出:

$ python func_doc.py5 is maximumPrints the maximum of two numbers.        The two values must be integers. 

DocStrings也适用于模块和类。当我们在交互式解释器中使用help(printMax)时,会自动抓取这个函数的doc并显示出来。所以这个DocStrings就是函数的文档说明。

函数部分到此结束,我们知道了函数的基本功能,可以自己定义和使用函数了

0 0
原创粉丝点击