初学python-基础语法

2017-07-25  本文已影响47人  pnjoe
中文编码
#!/usr/bin/python
# -*- coding: UTF-8 -*-
print "你好,世界";
Python 保留字符

| |
|:----:|:----:|:----:|
|and|exec|not|
|assert|finally|or|
|break|for |pass|
|class|from|print|
|continue|global|raise|
|def| if|return|
|del| import|try|
|elif| in|while|
|else|is|with|
|except|lambda|yield|

行和缩进
>>> print 'hello' ; print 'runoob';
hello
runoob
以下是错误案例: (第2行,第4行缩进的空格数不一致.)
if True:
   print "True"
else:
    print "False"
以下正确示范. (要么都空2格,要么都空4格)
if True:
    print "True"
else:
    print "False"
多行语句
total = item_one + \
        item_two + \
        item_three
上面三行代码 与 下面一行 等效
total = item_one + item_two + item_three
days = ['Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday']
Python 引号
word = 'word'
sentence = "这是一个句子。"
paragraph = """这是一个段落。
我可以很多行
我可以很多行
包含了多个语句"""
Python 注释
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:test.py
# 第一个注释
print "Hello, Python!";  # 第二个注释

输出结果:

Hello, Python!
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:test.py
'''
这是多行注释,使用单引号。
这是多行注释,使用单引号。
这是多行注释,使用单引号。
'''
"""
这是多行注释,使用双引号。
这是多行注释,使用双引号。
这是多行注释,使用双引号。
"""
Print 输出
#!/usr/bin/python
# -*- coding: UTF-8 -*-
x="a"
y="b"
# 换行输出
print x
print y
print '.............'
# 不换行输出
print x,
print y,

以上实例执行结果为:

a
b
.............
a b
多个语句构成代码组
if expression : 
    suite 
elif expression :  
    suite  
else :  
    suite 
上一篇下一篇

猜你喜欢

热点阅读