第2章 Python 必须知道的基础语法
本章知识
1、Python 文件的扩展名;
2、Python 的编码规则;
3、数据类型;
4、变量和常量的定义和使用;
5、运算符及表达式;
内容
2.1 Python 的文件类型
2.1.1 源代码
2.1.2 字节代码
2.1.3 优化代码
(1)、启动命令行窗口;
(2)、在命令行中输入 python-O-m py_compile hello.py;
2.2 Python的编码规范
2.2.1 命名规则
(1)、变量名、包名、模块名;
(2)、类名、对象名;
class Student:
__name = ""
def __init__(self, name):
self.__name = name
def getName(self):
return self.__name
if __name__ == "__main__":
student = Student("borphi")
print(student.getName())
# 输出:borphi
(3)、函数名;
import random
def compareNanum(num1, num2):
if (num1 > num2):
return 1
elif(num1 == num2):
return 0
else:
return -1
num1 = random.randrange(1, 9)
num2 = random.randrange(1, 9)
print ("num1 =", num1 )
print ("num2 =", num2)
print (compareNanum(num1, num2))
# 输出:num1 = 5; num2 = 3; 1
# 不规范的命名
sum = 0
i = 2000
j = 1200
sum = i + 12 * j
print (sum)
#输出:16400
#规范的命名
sumPay = 0
bonusOfYeay = 2000
monthPay = 1200
sumPay = bonusOfYeay + 12 * monthPay
print (sumPay)
#输出:16400
2.2.2 代码缩进与冒号
x = 1
if x == 1:
print ("x =", x)
else:
print ("x =", x)
x = x + 1
print ("x =", x)
输出:x=1 x=1
x = 2
if x == 1:
print ("x =", x)
else:
print ("x =", x)
x = x + 1
print ("x =", x)
输出:x=2 x=3
x = 1
if x == 1:
print ("x =", x)
else:
print ("x =", x)
x = x + 1
print ("x =", x)
# 输出: x=1; x=2
2.2.3 模块导入的规范
(1)、import 语句
import sys
print (sys.path)
print (sys.argv)
输出:['D:\\Python\\零基础学 python\\第2章 Python 必须知道的基础语法',
'D:\\Python\\零基础学 python', 'F:\\Anaconda3\\python36.zip',
'F:\\Anaconda3\\DLLs', 'F:\\Anaconda3\\lib', 'F:\\Anaconda3',
'F:\\Anaconda3\\lib\\site-packages',
'F:\\Anaconda3\\lib\\site-packages\\win32',
'F:\\Anaconda3\\lib\\site-packages\\win32\\lib',
'F:\\Anaconda3\\lib\\site-packages\\Pythonwin',
'C:\\PyCharm 2017.3.3\\helpers\\pycharm_matplotlib_backend']
['D:/Python/零基础学 python/第2章 Python 必须知道的基础语法/hello.py']
(2)、from...import... 语句
from sys import path
from sys import argv
print (path)
print (argv)
输出:['D:\\Python\\零基础学 python\\第2章 Python 必须知道的基础语法',
'D:\\Python\\零基础学 python', 'F:\\Anaconda3\\python36.zip',
'F:\\Anaconda3\\DLLs', 'F:\\Anaconda3\\lib', 'F:\\Anaconda3',
'F:\\Anaconda3\\lib\\site-packages',
'F:\\Anaconda3\\lib\\site-packages\\win32',
'F:\\Anaconda3\\lib\\site-packages\\win32\\lib',
'F:\\Anaconda3\\lib\\site-packages\\Pythonwin',
'C:\\PyCharm 2017.3.3\\helpers\\pycharm_matplotlib_backend']
['D:/Python/零基础学 python/第2章 Python 必须知道的基础语法/hello.py']
2.2.4 使用空行分割代码
class A:
def funX(self):
print ("funY")
def funY(self):
print ("funX")
if __name__ == "__main__":
a = A()
a.funX()
a.funY()
# 输出:funX; funY
2.2.5 正确的注释
(1)、中文注解
# -*- coding:utf-8 -*-
(2)、跨平台注解
# !/usr/bin/python
def compareNum(num1, num2):
if (num1 > num2):
return str(num1)+">"+str(num2)
elif(num1 < num2):
return str(num1)+"<"+str(num2)
elif(num1 == num2):
return str(num1)+"="+str(num2)
else:
return ""
num1 = 2
num2 = 1
print (compareNum(num1, num2))
num1 = 2
num2 = 2
print (compareNum(num1, num2))
num1 = 1
num2 = 2
print (compareNum(num1, num2))
# 输出:2>1;2=2;1<2
2.2.6 语句的分割
print ("hello world!")
print ("hello world!");
x = 1;y = 2; z = 3;
print (x, y, z)
# 输出:hello world! hello world! 1 2 3
2.3 变量和常量
2.3.1 变量的命名
var_1 = 1
print (var_1)
_var1 = 2
print (_var1)
# 输出:1; 2
2.3.2 变量的赋值
x = 1
print (id(x))
x = 2
print (id(x))
# 输出:1611623488; 1611623520
a = (1,2,3)
(x, y, z) = a
print ("x =", x)
print ("y =", y)
print ("z =", z)
# 输出:x = 1; y = 2; z = 3
2.3.3 局部变量
def fun():
local = 1
print (local)
fun()
# 输出:1
2.3.4 全局变量
_a = 1_b = 2
def add():
global _a
_a = 3
return "_a + _b =", _a+_b # _a=3;_b=2
def sub():
global _b
_b = 4
return "_a - _b =", _a-_b #_a=3;_b=4
print (add())
print (sub())
# 输出:('_a + _b =', 5); ('_a - _b =', -1)
_a = 1
_b = 2
def add():
_a = 3
return "_a + _b =", _a+_b # _a=3;_b=2
def sub():
_b = 4
return "_a - _b =", _a-_b #_a=1;_b=4
print (add())
print (sub())
# 输出:('_a + _b =', 5); ('_a - _b =', -3)
2.3.5 常量
class _const:
class ConstError(TypeError):
pass
def __setattr__(self, name, value):
if self.__dict__.has_key(name):
raise self.ConstError, "Can't rebind const(%s)" %name
self.__dict__[name] = value
import sys
sys.modules[__name__] = _const()
# 输出:SyntaxError: invalid syntax
import const
const.magic = 23
const.magic = 33
2.4 数据类型
2.4.1 数字
i = 1
print (id(i))
i = 2
print (id(i))
i = 1
print (type(i))
i = 999999999999990
print (type(1))
f = 1.2
print (type(f))
b = True
print (type(b))
# 输出:1611623488; 1611623520; <class 'int'>; <class 'int'>;
<class 'float'>; <class 'bool'>
2.4.2 字符串
str = "hello world!"
print (str)
str = 'hello world!'
print (str)
str = '''he say "hello world!"'''
print (str)
# 输出:hello world!
hello world!
he say "hello world!"
class Hello:
'''hello class'''
def printHello():
'''print hello world'''
print ("hello world")
print (Hello.__doc__)
print (Hello.printHello.__doc__)
# 输出:hello class
# print hello world
str = '''he say: 'hello world!' '''
print (str)
str = 'he say :\'hello world!\''
print (str)
str = "he say: 'hello world!'"
print (str)
# 输出:he say: 'hello world!'
# he say :'hello world!'
# he say: 'hello world!'
2.5 运算符与表达式
2.5.1 算术运算符和算术表达式
print ("1 + 1 =", 1+1)
print ("2 - 1 =", 2-1)
print ("2 * 3 =", 2*3)
print ("4 / 2 =", 4/2)
print ("1 / 2 =", 1/2)
print ("1.0 / 2.0 =", 1.0/2.0)
print ("3 % 2 =", 3%2)
print ("2 ** 3 =", 2**3)
# 输出:1 + 1 = 2
# 2 - 1 = 1
# 2 * 3 = 6
# 4 / 2 = 2.0
# 1 / 2 = 0.5
# 1.0 / 2.0 = 0.5
# 3 % 2 = 1
# 2 ** 3 = 8
a = 1
b = 2
c = 3
d = 4
print ("a + b * c % d =", a+b*c%d)
print ("(a + b) * (c % d)=", (a+b)*(c%d))
# 输出:a + b * c % d = 3
# (a + b) * (c % d)= 9
2.5.2 关系运算符和关系表达式
print (2 > 1)
print (1 <= 2)
print (1 == 2)
print (1 != 2)
# 输出:True
# True
# False
# True
print ("1 + 2 < 3 - 1 =>", 1 + 2, "<", 3 -1, "=>", 1 + 2 < 3 - 1 )
print ("1 + 2 <= 3 > 5 % 2 =>", 1 + 2, ">", 5 % 2, "=>", 1 + 2 <= 3 > 5 % 2)
# 输出:1 + 2 < 3 - 1 => 3 < 2 => False
# 1 + 2 <= 3 > 5 % 2 => 3 > 1 => True
2.5.3 逻辑运算符和逻辑表达式
print (not True)
print (False and True)
print (True and False)
print (True or False)
# 输出:False
# False
# False
# True
print ("not 1 and 0 =>", not 1 and 0)
print ("not (1 and 0) =>",not (1 and 0))
print ("(1 <= 2) and False or True =>", (1 <= 2) and False or True)
print ("(1 <= 2) or 1 > + 2 =>", 1 <= 2, "or", 1 > 2, "=>", (1 <= 2) or (1 < 2))
# 输出:not 1 and 0 => False
# not (1 and 0) => True
# (1 <= 2) and False or True => True
# (1 <= 2) or 1 > + 2 => True or False => True

浙公网安备 33010602011771号