python 学习笔记一,,简介Python是一


简介

Python是一门动态的, 面向对象的, 解释型的语言.由Guidi van Rossum于1989年底发明(话说他只是为了打发圣诞节的无聊时间), 第一个公开发行版发行于1991年.

特点

  1.在源代码中, 我们不需要申明变量, 参数或者方法的类型, 这使得代码简短且灵活

  2. 与c++, java不同的是, Python语句的结尾不需要分号, 你加上也可以, 但这不是好的规范

  3. 单行注释以#开始, 多行注释写在""" """之间

  4. 很重要的一点, Python中使用缩进来标明程序块, 不用传统的{}

HelloThere

Python源文件的拓展名是".py". 程序在hello.py中有下面的一段代码, 那么运行它最简单的方法就是在shell命令行下输入"python hello.py Alice" ----装载并运行hello.py里的代码, 并给它传递了一个命令行参数"Alice".

bubuko.com,布布扣
#!/usr/bin/python# import modules used here -- sys is a very standard oneimport sys# Gather our code in a main() functiondef main():    print ‘Hello there‘, sys.argv[1]    # Command line args are in sys.argv[1], sys.argv[2] ...    # sys.argv[0] is the script name itself and can be ignored# Standard boilerplate to call the main() function to begin# the program.if __name__ == ‘__main__‘:    main()
bubuko.com,布布扣

为hello.py加上可执行属性:

bubuko.com,布布扣
chmod +x hello.py
bubuko.com,布布扣

这样就可以在命令行下使用"./hello.py Alice"执行程序.

函数

Python的函数是这样的:

bubuko.com,布布扣
# Defines a "repeat" function that takes 2 arguments.def repeat(s, exclaim):    """
Returns the string s repeated 3 times. If exclaim is true, add exclamation marks. """ result = s + s + s # can also use "s * 3" which is faster (Why?) if exclaim: result = result + ‘!!!‘ return result
bubuko.com,布布扣

调用上面的函数, 打印结果:

bubuko.com,布布扣
def main():    print repeat(‘Yay‘, False)      ## YayYayYay    print repeat(‘Woo Hoo‘, True)   ## Woo HooWoo HooWoo Hoo!!!
bubuko.com,布布扣

代码检测

Python对所有的类型, 名字的等的检测都是在运行时进行的, 举个例子, 上面的main()这样调用repeat():

bubuko.com,布布扣
def main():    if name == ‘Guido‘:        print repeeeet(name) + ‘!!!‘    else:        print repeat(name)
bubuko.com,布布扣

if语句有个明显的错误, repeat()函数被写成了repeeeet(). 当name不是Guido时, 运行这个程序并不会报错, 只有当名字变为Guido, 运行到含有repeeeet()函数的这句才会出错.

python 学习笔记一,布布扣,bubuko.com

python 学习笔记一

评论关闭