2. Python语言基本语法
(1)定义变量
1 a = 10 2 b = 2 3 c = a + b
(2)判断语句
1 score = 90 2 3 if score >= 80 : 4 print("优秀") 5 elif score >= 70 : 6 print("中等") 7 elif score >= 60 : 8 print("及格") 9 else: 10 print("不及格")
(3)循环
1 for i in range(0,5,2): 2 print(i) 3 print("================") 4 for i in range(0,5): 5 print(i) 6 print("================")
print("Item {0} {1}".format(10,"eee"))
for i in range(0,5):
print(i)
else:
print("循环结束")
(4)函数
1 def sayHello(): 2 print("Hello world") 3 4 sayHello() 5 6 def myMax(x,y): 7 if x > y : 8 print x,"is Max" 9 else: 10 print y,"is Max" 11 myMax(10,9) 12 13 def myMaxVal(x,y): 14 if x > y : 15 return x 16 return y 17 18 print(myMaxVal(10,8))
(5)对象
1 class Hello: 2 def __init__(self, name): 3 self.name = name 4 print("Hello 构造函数") 5 def __del__(self): 6 print("Hello 析构函数") 7 8 def sayHello(self): 9 print("Hello {0}".format(self.name)) 10 11 class Hi(Hello): 12 def __int__(self,name): 13 Hello.__init__(self,name) 14 self.name = name 15 print("Hi 构造函数") 16 17 def sayHi(self): 18 print("Hi {0}".format(self.name)) 19 20 #Hello对象 21 h = Hello("zhangsan") 22 h.sayHello() 23 24 #Hi对象 25 hi = Hi("lisi") 26 hi.sayHi() 27 hi.sayHello()
(6) 引入Python文件
mylib.py
1 # coding=utf-8 2 class Hello: 3 def __init__(self, name): 4 self.name = name 5 print("Hello 构造函数") 6 def __del__(self): 7 print("Hello 析构函数") 8 9 def sayHello(self): 10 print("Hello {0}".format(self.name))
引用的两种方法
1 #第一种 2 import mylib 3 4 h = mylib.Hello("John") 5 h.sayHello() 6 7 #第二种 8 from mylib import Hello 9 10 h = Hello("John") 11 h.sayHello()