1. python基础执行方式

两种执行方式:

$ python解释器 py文件路径
$ python 进入解释器:
实时交互式,输入并获取到执行结果。

  • 1、指定python执行文件时,文件名可以是任意(包括数字、特殊符号),后缀名也可以任意(.txt/.py/.log)。但在工程中,必须使用.py后缀。
  • 2、工程中,导入模块,如果不是.py文件,import会失败。所以后缀必须.py
执行方式:
1、进入交互模式
python
2、python filename.py
3、命令行
./filename.py

py文件

1、解释器路径

#! /usr/bin/env python

2、编码

# -*- coding:utf-8 -*-
# coding=utf-8

Python3 无需关注
Python2 每个文件中只要出现中文,头部必须加

几种常见编码ASCII 8位 最多256

Unicode 16+位 固定长度,至少16位,所以占内存和空间
& 00000000000000001
中 00000000000000001010111101

utf-8 动态 无固定长度,能用多少表示就用多少位表示(最短8的整数倍) : 单中文占3字节
& 00000001
中 10000001010111101

gbk : 单中文占2字节

# -*- coding:utf-8 -*-

a = "张五常"

# python3 : len() 函数统计元素个数
len(a) # utf-8中文 len(a)函数得到长度为3
for item in a:
print(item) # 顺序输出: 张 五 常

Python2 : len() 函数统计字节个数
len(a) # utf-8中文 len(a)函数得到长度为9 = 3 * 3(utf8编码,单中文占3字节)

Python注释

单行注释用 #

多行注释用 """ 注释块 """


输入与输出

#!/user/bin/env python
# -*- coding:utf-8 -*-

# 等待用户输入
n1 = input('请输入用户名:')
# 打印
print(n1)



 变量命名规范

字母、数字、下划线
不能数字开头
不能使用python关键字
不能使用python内置函数名
单词以下划线分隔,如:user_id

Python 关键字

关键字列表

要获取关键字列表,可以使用内置函数 help():

>>> help('keywords')



Here is a list of the Python keywords. Enter any keyword to get more help.

False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not

也可以使用 keyword 模块:

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 
'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

共 33 个关键字,除 True、False 和 None 外,其他关键字均为小写形式。

注意: Python 是一种动态语言,根据时间在不断变化,关键字列表将来有可能会更改。

关键字判断

除此之外,keyword 模块还提供了关键字的判断功能:

>>> keyword.iskeyword('and')
True
>>> keyword.iskeyword('has')
False

关键字含义

下表列举了所有的 Python 关键字,以及它们的的含义:

原文地址:https://www.cnblogs.com/LIAOBO/p/13228005.html