1.中文编码
如果直接执行以下代码会报错:
print '中文'
需要增加编码,如下两种方式均可以:
# coding=utf-8
# coding:utf-8
2.执行顺序
以下代码执行的结果:
中文
Hello
print('中文')
def test():
print('Hello')
if __name__ == '__main__':
test()
可以看出Python是解释型语言,自上而下的执行。
3.注释
Python用#
和'''
分别进行单行注释和多行注释,如下:
# print('Hello')
'''
def test():
print('Hello')
print('World')
'''
以上所有代码都不会执行。
3.比较运算符
不等号
两种写法,和SQL中一样:
!=
<>
与或非
and or not
4.空值None
Python中的空值用None,类似于Java中的Null。
5.赋值
赋值=
i=i+1
i+=1
(Python中i++不存在)
x=y=z=1
print x,y,z
x,y,z=1,2,'a string' # 弱类型,可直接变类型
x,y=y,x # 互换数据
因而Python是弱类型语言,因而没有类型的概念。所以z第一个是int型,第二个同样可以赋值String类型。
6.打印输出
Python打印为如下格式。不同类型没有Java中的”+”的字符串自动拼接。
print '%d miles is the same as %f km'%(x,y) # %s 字符串
注:同一类型,Python是可以使用”+”
Java中这么写:
System.out.print(x+" miles is the same as "+y+" km");
7.方法的调用
对于有返回值的方法,可以用
print test()
对于无返回值的方法,可以
test()
如下:
# coding=utf-8
#########
#无返回值
#########
def test():
print('无返回值')
#########
#有返回值
#########
def test2():
print('有返回值')
return 0
test()
print test2()
注意:由于Python是解释型语言,所以方法的调用必须放在方法之后。
如下则会报错
# coding=utf-8
test() #报错
print test2() #报错
#########
#无返回值
#########
def test():
print('无返回值')
#########
#有返回值
#########
def test2():
print('有返回值')
return 0