Python语法快速入门指南
Python语言与Perl,C和Java等语言有许多相似之处。但是,也存在一些差异。 $ python Python 2.7.6 (default,Sep 9 2014,15:04:36) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin Type "help","copyright","credits" or "license" for more information. >>> Window上在安装Python时已经已经安装了默认的交互式编程客户端,提示窗口如下: 在 python 提示符中输入以下文本信息,然后按 Enter 键查看运行效果: >>> print "Hello,Python!";
Hello,Python!
>>> print ("Hello,Python!");
print "Hello,Python!";
$ python test.py
Hello,Python!
#!/usr/bin/python print "Hello,Python!";
$ chmod +x test.py # 脚本文件添加可执行权限 $./test.py
Hello,Python! Python 标识符 行和缩进 学习Python与其他语言最大的区别就是,Python的代码块不使用大括号({})来控制类,函数以及其他逻辑判断。python最具特色的就是用缩进来写模块。 缩进的空白数量是可变的,但是所有代码块语句必须包含相同的缩进空白数量,这个必须严格执行。如下所示: if True: print "True" else: print "False" #!/usr/bin/python # -*- coding: UTF-8 -*- # 文件名:test.py if True: print "Answer" print "True" else: print "Answer" # 没有严格缩进,在执行时保持 print "False" $ python test.py File "test.py",line 5 if True: ^ IndentationError: unexpected indent IndentationError: unexpected indent 错误是python编译器是在告诉你"Hi,老兄,你的文件里格式不对了,可能是tab和空格没对齐的问题",所有python对格式要求非常严格。 total = item_one + item_two + item_three 语句中包含[],{} 或 () 括号就不需要使用多行连接符。如下实例: days = ['Monday','Tuesday','Wednesday','Thursday','Friday']
word = 'word' sentence = "这是一个句子。" paragraph = """这是一个段落。 包含了多个语句""" Python注释 #!/usr/bin/python # -*- coding: UTF-8 -*- # 文件名:test.py # 第一个注释print "Hello,Python!"; # 第二个注释 输出结果: Hello,Python!
name = "Madisetti" # 这是一个注释 python 中多行注释使用三个单引号(''')或三个单引号(""")。 #!/usr/bin/python # -*- coding: UTF-8 -*- # 文件名:test.py ''' 这是多行注释,使用单引号。 这是多行注释,使用单引号。 这是多行注释,使用单引号。 ''' """ 这是多行注释,使用双引号。 这是多行注释,使用双引号。 这是多行注释,使用双引号。 """ Python空行 #!/usr/bin/python raw_input("nnPress the enter key to exit.") 以上代码中 ,"nn"在结果输出前会输出两个新的空行。一旦用户按下键时,程序将退出。 import sys; x = 'foo'; sys.stdout.write(x + 'n')
if expression : suite elif expression : suite else : suite 命令行参数 $ python -h usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): -c cmd : program passed in as string (terminates option list) -d : debug output from parser (also PYTHONDEBUG=x) -E : ignore environment variables (such as PYTHONPATH) -h : print this help message and exit [ etc. ] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |