整体文章目录

python看这一篇就够了 python pythonw_全局变量

一、 当前章节目录

python看这一篇就够了 python pythonw_缩进_02

二、Python的文件类型

2.1 源代码

  1. Python源代码的扩展名以py结尾,可在控制台下运行。
  2. pyw是Windows下开发图形用户接口(Graphical User Interface,GUI)的源文件

2.2 字节代码

  • Python源文件编译后生成pyc后缀的文件,pyc是编译过的字节文件,这种文件不能使用文本编辑工具打开或修改
  • 下面这段脚本可以吧hello.py编译为hello.cpython-37.pyc
import py_compile
py_compile.compile('hello.py')

2.3 优化代码

  • 扩展名为opt-1.pyc的文件是优化过的源文件,需要用命令行工具生成。
  1. 启动命令行窗口,进入hello.py文件所在的目录。例如:
cd /d D:\pythoncode\ch1code
  1. 在命令行输入,并按回车
    (1)参数“-O”表示生成优化代码。
    (2)参数“-m”表示把导入的py_compile模块作为脚本运行。(编译需要调用py_compile模块的compile()方法)
    (3)参数“hello.py”是待编译的文件名。
python -O -m py_compile hello.py
  1. 查看hello.py文件所在目录中的_pycache_文件夹,此时文件夹中生成了一个名为hello.cpython-37.opt-1.pyc的文件。

三、Python的编码规范

3.1 命名规则

  1. 变量名、包名、模块名
# 变量、模块名的命名规则
# Filename:ruleModule.py

_rule = "rule information"
  1. 类名、对象名
class Student:                      # 类名大写
    __name = ""                     # 私有实例变量前必须有两个下划线
    def __init__(self , name):      # 创建init函数,自动调用并初始化
        self.__name = name          # self相当于Java中的this
    def getName(self):              # 方法名首字母小写,其后每个单词的首字母大写
        return self.__name          # 返回name的值

if __name__ == "__main__":          # 主程序运行
    student = Student("borphi")     # 对象名小写
    print(student.getName())        # 输出调用函数getName获得的值

运行结果:

borphi

  1. 函数名
# 函数中的命名规则
import random                       # 导入random模块

def compareNum(num1 , num2):        # 定义带参数的compareNum函数
    if(num1 > num2):
        return 1
    elif(num1 == num2):
        return 0
    else:
        return -1
num1=random.randrange(1 , 9)        # 产生随机数并赋值给num1
num2=random.randrange(1 , 9)        # 产生随机数并赋值给num2
print("num1 = ", num1)
print("num2 = ", num2)
print(compareNum(num1, num2))      # 调用compareNum函数

运行结果:

num1 = 2
num2 = 7
-1

(1)命名不规范会使得程序难以阅读,例如:

# 不规范的变量命名
sum = 0
i = 2000
j = 1200
sum = i + 12 * j

(2)命名规范会使得程序容易阅读,例如:

# 规范的变量命名
sumPay = 0		# 年薪
bonusOfYear = 2000		# 年终奖金
monthPay = 1200		# 月薪
sumPay = bonusOfYear + 12 * monthPay		# 年薪 = 年终奖金 + 12 * 月

3.2 代码缩进与冒号

  • 对于Python而言,代码缩进是一种语法,使用冒号和代码缩进区分代码之间的层次。
x = 1                               # 定义x并赋值
if x == 1:                          # if判断x是否等于1
    print("x = ",x)                # 代码缩进
else:
    print("x = ", x)               # 代码缩进
x = x + 1                           # 代码缩进
print("x = ", x)                   # 输出x的值

运行结果:

x = 1
x = 2

3.3 模块导入的规范

  1. import语句

(1)语法分析:import A是导入整个A模块的全部内容(包括全部的函数,全局变量,类)。
(2)内存分析:import…方法导入模块会在内存中直接加载该模块的全部属性。当出现多个程序导入该模块时,会共用一个模块,程序之间会互相影响,包括原模块。

# 规范导入方式
import sys

print(sys.path)
print(sys.argv)
  1. from…import…语句

(1)语法分析:from A import a1 是从A模块导入a1工具(可以是某个函数,全局变量,类)
(2)内存分析:from…import…会在内存中创建并加载该模块工具的副本,当有另外一个程序导入时,会在内存中创建另一个副本进行加载,不会共用一个副本。所以程序进行的修改不会影响到被导入的原模块,且不同程序之间不会互相影响

# 不规范导入方式
from sys import path
from sys import argv

print(path)
print(argv)

3.4 使用空行分隔代码

  • 分隔两段不同功能或含义的代码,便于日后代码的维护或重构。
class A:                                # 定义一个A类
    def funX(self):                     # 定义一个funX方法
        print("funX()")                 # 输出内容

    def funY(self):                     # 定义一个funY方法
        print("funY()")                 # 输出内容

if __name__ == "__main__":              # 主程序入口
    a = A()                             # 创建一个a对象
    a.funX()                            # 调用funX方法
    a.funY()                            # 调用funY方法

运行结果:

funX()
funY()

3.5 正确的注释

  1. 单行注释
# 规范的变量命名
sumPay = 0                          # 年薪
bonusOfYear = 2000                  # 年终奖金
monthPay = 1200                     # 月薪
sumPay = bonusOfYear + 12 * monthPay# 年薪 = 年终奖金 + 12 * 月
  1. 多行注释
"""
以下程序的功能是声明和调用函数getv(b,r,n)
根据本金b,年利率r和年数n,计算最终收益,计算最终收益的公式为v=b(1+r)^n
"""
def getv(b,r,n):                        # 定义一个getv函数
    v = b * ((1 + r) ** n)
    return v                            # 返回v的值
sv = getv(15000,0.8,10)                 # 调用函数
print(sv)                               # 输出sv的值

运行结果:

5355700.839936001

  1. 特殊的注释

(1)中文注释

# -*- coding: UTF-8 -*-
# 中文注释

(2)跨平台注释

# !/usr/bin/python
# 跨平台注释

(3)调试程序

def compareNum(num1 , num2):            # 定义compareNum函数
    if(num1 > num2):                    # if判断,比较两个数的大小,返回不同的结果
        return str(num1) + " > " + str(num2)
#    elif(num1 < num2):
#        return str(num1) + " < " + str(num2)
    elif(num1 == num2):
        return str(num1) + " = " + str(num2)
    else:
        return ""

运行结果:

2 > 1
2 = 2

3.6 语句的分隔

(1)分号可以省略,主要通过换行来识别语句的结束。

# 下面两条语句是等价的
print("hello world!")
print("hello world!");

运行结果:

hello world!
hello world!

(2)如果在一行中写多个语句需要用到分隔符号。

# 使用分号分隔语句
x = 1 ; y = 1 ; z = 1

(3)使用“\”作为换行符,提高代码的可读性。

# 字符串的换行
# 写法一
sql = "select id , name \
from dept \
where name = 'A'"
print(sql)
# 写法二
sql = "select id , name "\
    "from dept "\
    "where name = 'A'"
print(sql)

运行结果:

select id , name from dept where name = ‘A’
select id , name from dept where name = ‘A’

四、变量和常量

4.1 变量的命名

  1. 变量由字母数字下划线组成。
  2. 变量的第1个字符必须是字母下划线
# 正确的变量命名
var_1 = 1
print(var_1)
_var1 = 2
print(_var1)

运行结果:

1
2

# 错误的变量命名
1_var = 3
print(1_var)
$var = 4
print($var)

运行结果:

1_var = 3
^
SyntaxError: invalid decimal literal

4.2 变量的赋值

  • 一次新的赋值,将创建一个新的变量。
  • 即使变量的名称相同,变量的标识并不相同
# 一次新的赋值操作,将创建一个新的变量
x = 1
print(id(x))
x = 2
print(id(x))

运行结果:

140707444238112
140707444238144

# 给多个变量赋值
a = (1, 2, 3)
(x, y, z) = a
print("x = ", x)
print("y = ", y)
print("z = ", z)

运行结果:

x = 1
y = 2
z = 3

4.3 局部变量

  • 作用范围:只在其被创建的函数内有效。

python看这一篇就够了 python pythonw_python_03

# 局部变量
def fun():
    local = 1
    print(local)
fun()

运行结果:

1

4.4 全局变量

  • 作用范围:文件内部的任何函数和外部文件

python看这一篇就够了 python pythonw_python_04

# 在文件的开头定义全局变量
_a = 1
_b = 2
def add():
    global _a
    _a = 3
    return "_a + _b = " , _a + _b
def sub():
    global  _b
    _b = 4
    return "_a - _b = " , _a - _b
print(add())
print(sub())

运行结果:

(’_a + _b = ‘, 5)
(’_a - _b = ', -1)

# 全局变量
# gl.py
_a = 1
_b = 2
# 调用全局变量
import gl
def fun():
    print(gl._a)
    print(gl._b)
fun()

运行结果:

1
2

4.5 常量

  • 常量是指一旦初始化后就不能改变的变量
  • 通常使用全大写字母来表示(可以使用下划线增加可读性)
# const.py
class _const:  # 定义常量类_const——35页
    class ConstError(TypeError):
        pass  # 继承自TypeError

    def __setattr__(self, name, value):
        if name in self.__dict__.keys():  # 如果__dict__中不包含对应的key,则抛出错误
            raise self.ConstError("Can't rebind const(%s)" % name)
        self.__dict__[name] = value

import sys
sys.modules[__name__] = _const()  # 将const注册进sys.modules的全局dict中
import const
const.magic = 23
const.magic = 33

运行结果:

const.ConstError: Can’t rebind const(magic)

五、数据类型

5.1 数字

  • 整型、浮点型、布尔型、分数类型、复数类型。
# 下面的两个i并不是同一个对象
i = 1
print(id(1))
i = 2
print(id(i))

运行结果:

140707365005088
140707365005120

# 整型
i = 1
print(type(i))
# 长整型
l = 999999999999999999990               # Python何时将int转为float跟操作系统位数相关
print(type(l))
# 浮点型
f = 1.2
print(type(f))
# 布尔型
b = True
print(type(b))
# 复数类型
c = 7 + 8j
print(type(c))

运行结果:

<class ‘int’>
<class ‘int’>
<class ‘float’>
<class ‘bool’>
<class ‘complex’>

5.2 字符串

  • 三种表示字符串的方式——单引号、双引号、三引号。
# 单引号和双引号的使用是等价的
str = "hello world!"                    # 定义字符串变量str并赋值
print(str)
str = 'hello world!'
print(str)

# 三引号的用法
str = '''he say "hello world!"'''
print(str)

运行结果:

hello world!
hello world!
he say “hello world!”

# 三引号制作doc文档
class Hello:
    '''hello class'''
    def printHello(self):
        '''print hello world'''
        print("hello world!!!!")
print(Hello.__doc__)
print(Hello.printHello.__doc__)
hello = Hello()
hello.printHello()

运行结果:

hello class
print hello world
hello world!!!

# 转义字符
str = 'he say:\'hello world!\''
print(str)
# 直接输出特殊字符
str = "he say:'hello world!'"
print(str)
str = '''he say :'hello world!' '''

运行结果:

he say:‘hello world!’
he say:‘hello world!’

六、运算符与表达式

6.1 算术运算符和算术表达式

python看这一篇就够了 python pythonw_赋值_05

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

6.2 关系运算符和关系表达式

python看这一篇就够了 python pythonw_缩进_06

# 关系表达式
print(2 > 1)
print(1 <= 2)
print(1 == 2)
print(1 != 2)

# 关系表达式的优先级别
print("1 + 2 < 3 - 1 => ", 1 + 2, " < ", 3 - 1, " => ", 1 + 2 < 3 - 1)
print("1 + 2 <= 3 > 5 % 2 => ", 1 + 2, " <= ", 3, " > ", 5 % 2, " => ", 1 + 2 <= 3 > 5 % 2)

运行结果:

True
True
False
True
1 + 2 < 3 - 1 => 3 < 2 => False
1 + 2 <= 3 > 5 % 2 => 3 <= 3 > 1 => True

6.3 逻辑运算符和逻辑表达式

python看这一篇就够了 python pythonw_python_07

# 逻辑运算符
print(not True)
print(False and True)
print(True and False)
print(True or False)

# 逻辑表达式的优先级别
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 > 1 + 2 => ", 1 <= 2, "or", 1 > 2, " => ", (1 <= 2) or (1 < 2))

运行结果:

False
False
False
True
not 1 and 0 => False
not (1 and 0) => True
(1 <= 2) and False or True => True
(1 <= 2) or 1 > 1 + 2 => True or False => True

Process finished with exit code 0

七、习题

习题:

  1. 以下变量命名不正确的是()。
    A. foo = the_value
    B. foo = 1_value
    C. foo = value
    D. foo = value
    &
  2. 计算2的38次方的值。
  3. 以下逻辑运算的结果:
    a) True and False
    b) False and True
    c) True or False
    d) False or True
    e) True or False and True
    f) True and False or False
  4. 编写程序计算1 + 2 +3 + … + 100的结果

答案:

  1. B,D
  2. print("2 ** 38 = " , 2 ** 38)
  3. a) False b) False c) True d) True e) True f) False
  4. 如下代码:
# 第4题
x = 0
for i in range(1,101):
    x += i
    print(i,end='')
    if(i != 100):
        print(" + ", end='')
    else:
        print(" = ", end='')
print(x)

运行结果:

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20 + 21 + 22 + 23 + 24 + 25 + 26 + 27 + 28 + 29 + 30 + 31 + 32 + 33 + 34 + 35 + 36 + 37 + 38 + 39 + 40 + 41 + 42 + 43 + 44 + 45 + 46 + 47 + 48 + 49 + 50 + 51 + 52 + 53 + 54 + 55 + 56 + 57 + 58 + 59 + 60 + 61 + 62 + 63 + 64 + 65 + 66 + 67 + 68 + 69 + 70 + 71 + 72 + 73 + 74 + 75 + 76 + 77 + 78 + 79 + 80 + 81 + 82 + 83 + 84 + 85 + 86 + 87 + 88 + 89 + 90 + 91 + 92 + 93 + 94 + 95 + 96 + 97 + 98 + 99 + 100 = 5050