内容正文:
python程序基本构成与风格代码示例:
python文字注释:
python代码注释:
Python 中允许把多条语句写在一行中,中间用分号隔开。例如:
可以写成如下形式:
Python 中还可以将一条长语句分成多行显示,如果语句太长不能在一行中显示,可在该行 的结束处加
上续行符“\”,例如:
可以写成如下形式:
#prog2-1.py
#For loop on a list # 第 1 行
num=[1,2,3,4,5] # 第 2 行
prog =int(input('Please input the value of prog:')) #第3行
for number in num: # 第 4 行
prog = prog *numbe # 第 5 行
print('The prog is:',prog) # 第 6 行
print('Hello,World!') #print a string
'''
for number in num: # 第 4 行
prog = prog *numbe # 第 5 行
print('The prog is:',prog) # 第 6 行
'''
>>>x ='Today'
>>>y='is
>>>z='Thursday'
>>>print(x,y,z)
Today is Thursday
>>>x='Today';y='is';2='Thursday';print(x,y,z)
Today is Thursday
>>>if signal =='red'and car =='moving:
car ='stop
elif signal =='green'and car =='stop':
car ='moving'
小括号、中括号、花括号的内部可以多行书写,不需使用续行符,三引号中的字符串也同样 可以跨行书
写,例如:
python行和缩进:
以下代码将会执行错误:
File "test.py", line 11
print ("False")
^
IndentationError: unindent does not match any outer indentation level
IndentationError: unindent does not match any outer indentation level错误表明,你使用的缩
进方式不一致,有的是 tab 键缩进,有的是空格缩进,改为一致即可。
如果是 IndentationError: unexpected indent 错误, 则 python 编译器是在告诉你"Hi,老兄,你的
文件里格式不对了,可能是 tab 和空格没对齐的问题",所以 python 对格式要求非常严格。
因此,在 Python 的代码块中必须使用相同数目的行首缩进空格数。
>>>if signal =='red'and\
car =='moving':
car ='stop'
elif signal =='green'and\
car =='stop':
car ='moving'
>>>print(""Hi everybody,
welcome to Python's world
Here we can learn something about
Python.Good luck!"")
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")