行与缩进
在其他语言,例如C,Java中,我们表示代码块的时候都是使用{},但是在python中,我们使用缩进来表示代码块。
缩进的空格数是可以改变的,但是同一个代码块的语句,缩进的空格数必须是相同的。
例如:
if a<b:
print('a<b')
else:
print('a>=b')
如果有语句的缩进的空格数与其他语句缩进的空格数不一致,会导致运行错误。
例如:
if 1:
print ("hello")
print ("1")
else:
print ("hello")
print ("0") #缩进不一致,导致了运行错误
执行结果为:
File "<tokenize>", line 6
print ("0")
^
IndentationError: unindent does not match any outer indentation level #缩进不一致,导致了运行错误
等待用户输入
执行下面的程序,按下回车键后就会等待用户输入
input("\n\n按下 enter 键后退出。")
在上面的代码中,\n\n在结果输出前会输出两个新的空行。
只要用户按下 enter 键时,程序将退出。
在一行中显示多条语句
Python可以在一行中使用多条语句,每条语句之间用 ; 分割。
例如:
import keyword; keyword.kwlist
多个语句构成代码组
缩进相同的一组语句构成一个代码块,也称为一个代码组。
像if、while、def和class这样的复合语句,首行以关键字开始,以冒号( : )结束,该行之后的一行或多行代码构成代码组。我们将首行及后面的代码组称为一个子句(clause)。
例如:
a=4
b=2
c=3
if a<b:
print('a<b')
elif a==b:
print('a=b')
elif a>b:
if b>c:
print('a>b&b>c')
elif b==c:
print('a>b&b=c')
elif b>c:
print('a>b>c')
else:
print('a>b')
else:
print('未知')
print输出
print输出,默认情况下是换行的,如果想要实现不换行,需要在变量末尾加上 end=" " 。
例如:
n = 10
sum = 0
i = 1
while i<=n:
sum = sum+i
i += 1
print("1 到 %d 之和为: %d" %(n,sum))
print(n)
print(i)
print('----------------')
print(n,end=" ")
print(i,end=" ")
执行结果为:
1 到 10 之和为: 55
10
11
----------------
10 11
import 与 from...import
在 python 用 import 或者 from...import 来导入相应的模块。
将整个模块(somemodule)导入,格式为: import somemodule
从某个模块中导入某个函数,格式为: from somemodule import somefunction
从某个模块中导入多个函数,格式为: from somemodule import firstfunc, secondfunc, thirdfunc
将某个模块中的全部函数导入,格式为: from somemodule import *
导入sys模块
import sys
for i in sys.argv:
print (i)
print ('\n python 路径为:',sys.path)
导入 sys 模块的 argv,path 成员
from sys import argv,path # 导入特定的成员
print('path:',path)
# 因为刚开始已经导入path成员,所以此处引用时不需要加sys.path