下载 python解释器
下载 python pycharm
安装好镜像源
python.exe -m pip install --upgrade pip pip insstall requests 更换镜像源 pip config set global.index-url https://mirrors.163.com/pypi/simple pip config set global.index-url https://pypi.douban.com/simple/ pip config set global.index-url https://mirror.baidu.com/pypi/simple/ pip config set global.index-url https://pypi.mirrors.ustc.edu.cn/simple/ pip config set global.index-url https://mirrors.cloud.tencent.com/pypi/simple/ pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple/
目录
python 编码中字符串要转换为 utf-8编码字节 存储 传输
1.python语法
1.1编码
pycharm 默认用的utf-8 (密码文) 进行读取编码
import os for item in os.listdir("/pytharm projects/pythonProject/learning/"): if item.endswith(".py"): print(item)
我们保存代码用 utf-8 保存代码
0 00000000
1.2输出
print 后面加 end= 不会换行
print("你好" end="") print("张三")
1.3数据类型
1.3.1 整型(int)
不加引号的数字 可以计算后输出
print(18 + 9) print(18 - 9) print(18 / 9) print(18 * 9)
1.3.2字符串(str)
表示文本信息 例如:”张三“ ”景德镇“
# 单行文本 "张三" '张”三' # 多行文本 可以写多行hang """张三"""
print("张三") print('张三') print('张”三')
字符串之间可以相加 即拼接
"张三" + "老厉害了" "张三老厉害了"
"张三" * 3
print(12 + 12) # 24 print("12" + "12") # "1212", 字符串(文本拼接)
转换
str(19) # 19 --> "19" int("66") #"66"--> 88
1.3.3布尔类型(bool)
* 真 True
*假 False
0 , "", [], () , {}, set() None False -> False 其他都是 True 1 > 2 ->False 1 == 2 ->False "张三" == "李四" ->False 11 == 11 -True
整型,字符串类型 ->布尔值。
-
整型 0转换为布尔值为 False 其他均为True
print( bool(0) ) #False print( bool(10) ) #True print( bool(-13) ) #True
-
字符串 空字符串转换为布尔值为False 其他的都是True(空格都是True)
print( bool("") ) #False print( bool("s") ) #True print( bool(" ") ) #True
练习题
print( int("8") > 7) # True print( str(111) == 111 ) # False print( bool(-1) ) # True print( bool(0) ) # False print( bool("") ) # False print( bool("你好") ) # True print(True == True) # True print(True == False) # False print( bool("") == bool(0) ) # True
1.4变量
变量 就是给某个值取的名字(variable)
格式: 变量名 = 值
addr= "景德镇" age = 18 name = "张三" is_success = 1 > 19 # False 先计算值 后判断 print(is_success) # False address = "中国江西” + addr + name
result = 1 == 2 # False 先计算值 后判定 print(result) # False
1.4.1 规范
name = "张三"
-
建议(潜规则)
- 见名知意 - 不写拼音 - 多个单词用下划线链接 user_name= "张三"
-
变量名中只能包含:字母 数字 下划线
-
不能以数字开头 不能用除下划线以外的符号
-
不能使用python 内置的关键字
import builtins print(dir(builtins))
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BaseExceptionGroup', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'ExceptionGroup', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
import keyword print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', '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']
情景一
name = "a" name = "b"
在计算机的内存中创建一块区域保存字符串"a" ,name变量名则指向"a"这块区域。然后又再内存中创建一块区域保存"b",name变量名则指向"b"所在区域
-
(无人指向的数据会被标记为垃圾,由解释器自动化回收 )
情景二
name = "abc" new_name = name # 补充 name = "abc" new_name = "abc"
在计算机的内存中创建一块区域保存字符串"a" ,name变量名则指向"a"这块区域。new_name变量名指向name变量,应为是指向变量名,所以自动会指向name变量代表的内存区域
练习
nickname = "一米八" username = nickname username= "弟弟" print(nickname) # "一米八" print(username) # "弟弟"
nickname = "一米八" username = nickname nickname= "弟弟" print(nickname) # "弟弟" print(username) # "一米八"
nickname = "一米八" username = nickname nickname= "弟弟" text = username + nickname print(text) # "一米八弟弟" print(username) # "一米八"
string_number = "20" num = int(string_number) data = string+number *3 print(data) # "202020" value = num * 3 print(value) # 60
1.5注释
注释内容 不会混淆
-
单行注释
# 注释内容 选择要注释的一行或者多行 按下方快捷键 快捷建 -win: control + ? -mac: commond + ?
-
多行注释
""" 多行注释 """
1.6 输入
name = input("用户名:") age = int(input("年龄:")) Email = input("电子邮箱:") text = name + str(age) + Email print(text) # 可以用字典搜集 用户信息
1.7 条件语句
1.7.1 if 条件语句
if 条件: pass else: pass
如果 。。。就。。。
否则。。。就。。。
if 条件/真假: 条件成立后执行这里的代码 else: 不成立 执行这里的代码
1.7.2 if多条件语句
如果。。。就。。。
如果不。。。就。。。
if 条件A/真假: 条件A成立后执行这里的代码 elif B: # 条件A不成立 条件B成立 成立 执行这里的代码 elif C: # 条件A 不成立 条件C成立 成立 执行这里的代码 else: 以上都不成立 执行这里的代码
1.7.3 if 嵌套
-
注意缩进
if A: if B: if C: pass else: pass else: pass elif: D: pass
模拟 : 联通10010客服
print("欢迎致电10010,这里提供以下服务:1.话费服务;2.宽带服;3.企业服务;4.人工服务;") choice = input("请选择序列号:") 字典A = {} if choice == "1": print("话
费服务专区") print("1.查询话费;2.缴话费;3.话费异常") second_choice = input("请选择序列号:") if second_choice == "1": print("话费查询") print("你的花费余额是 字典里的花费余额") elif second_choice == "2": print("成功缴纳花费 缴纳的话费") elif second_choice == "3": print(".。。") else: print("输入错误") elif choice == "2": print("宽带服务") elif choice =="3": print("企业服务") elif choide == "4": print("人工服务专区") else: print("输入错误") # 制作 def dictionary() 包含用户信息 姓名 手机号 花费余额 宽带缴费 。。。 # #也可以分开写 不容易混淆 # 可以用def dictionary_phone() 制作字典 用的时候调用手机缴费数据数据 # 用def dictionary_computer() 制作字典 宽带数据
1.7.4 while 循环
只要条件一直成立,那么其包含的某条语句或某个代码块就会一直被执行
while 条件: 执行这里的代码
1.7.4.1 while 循环的使用
实例1:
print("开始") while True: print("朱是大帅哥") break print("代言人") print("结束") # 结果在下面 开始 朱是大帅哥 结束
print("开始") while True: print("朱是大帅哥") print("代言人") print("结束") # 因为 是 True 故而一直循环 # 打出来的代码是这个 有问题 大帅哥 代言人 某某 是大帅哥 代言人 某某 是大帅哥
上面的代码 有问题
实例2
num = 3 while num > 2: print("123") num = num - 1 print("结束")
实例3
num = True while num > 2: print("123") num = False print("结束")
实例4
循环 5次打印 我爱我的祖国
num = 7 while num > 2: print("我爱我的祖国") num = num - 1 print("结束")
实例5
循环 正0~10打印 反10~0打印
num = 0 while num < 11: print(num) num += 1 num = 10 while num > -1: print(num) num -= 1
实例6
count = 1 a = 66 while count <= 3: num = int(input("猜数字,数字在0~100之间:")) if num == a: print("猜对了") break elif num > a: print("猜大了") count += 1 continue elif num < a: print("猜小了") count += 1 continue print("结束")
1.7.4.2break continue 的使用
在循环体内,一旦遇到 break 语句,Python 二话不说马上就会跳出循环体,即便这时候循环体内还有待执行的语句。跳出循环后, 循环外面, 后面还有代码,会执行后面的代码
continue 不能自己独立使用 放在循环里面
continue 立即结束当前循环, 开始下次循环 进行下一次当前循环体的循环
例子1:
import random a = random.randint(0,100) b = 10 while b > 0: num = int(input("猜数字,数字在0~100之间:")) data_nu = int(num) if num == a: print("猜对了") break elif num > a: print("猜大了") b -= 3 continue elif num < a: print("猜小了") b -= 3 continue
例子2
输出1 ~10 不要7
count = 1 while count < 11: if count == 7: continue print(count) count += 1
count = 1 while count < 11: if count == 7: count += 1 continue print(count) count += 1
例子
print("欢迎使用联通系统") 建立字典a # 最终字典 def users(): user= input("用户名:") pwd = input("密码:") 建立字典b # 临时字典 if user user没有在字典a中找到 并且 其他条件: user加入字典b if pwd 是多少位数字以上的 且没有汉字 都是字母和数字(可以有大小写) 或者 是多少位数字以上的 没有汉字 有 大小写字母 数字: pwd 加入字典b 字典b 加入字典a print("欢迎进入联通系统") else: print(""您输入的密码需要是 条件 请重新输入") def users()
1.7.5 for 循环
1.8 字符串格式化
老师推荐用 format 稳定 旧版本可用
%每个版本都可以用
f 是新版本常用的
"".format() 的使用
python 3.6之前推荐使用
text = "我的名字是{0}今年{1}岁手机好是{2}".format("张三", 18, 13456) # 0 1 2 是标号 后面的值会进入前面的中括号里面 一般不写标号 print(text) # 打印出来就是下面的 # 我的名字是张三今年18岁
text = "我的名字是{0}今年{1}岁手机好是{2}".format("张三", 18, 13456) print(text)
% 的使用
这个是c语言的 这里也可以用
%s 字符串 %d 代替数字
字符串后面 %前面要有空格
text = "我的名字是%s今年%d岁手机好是%d" %("张三", 18, 13456) print(text)
text = "我的名字是%s今年%d岁手机好是%d" vi = text %("张三", 11) v2 = text %("李四", 12) print(vi, v2)
f 的使用 f-string
python3.6+之后有的 字符串格式化方式
name = "张三" age = 18 text = f"我的名字(name),今年(age)岁"’ print(text)
1.9 运算符
算数运算符
+ - * / %
value = 9 % 2 print(value) # 1 取余数
比较运算符
> >= < <= == !=
赋值运算
count = 1 count += 1 # 效果等同于 count = count + 1 count -= 1 # 效果等同于 count = count - 1
-
成员运算, 字符串 中是否含xx (敏感词)
v1 = "日本" in "日本人不是人" # Ture 用if语句判定 v2 = "俄罗斯"in "日本人不是人" # False
逻辑运算
and or
-
一般用法 这里的True 和False 代指条件 也可以是 True False
v1 = True and True # True v2 = False and True # False v3 = True or True # True v3 = False or True # True v5 = False or False # False
-
高级用法
v1 = 值 and/or 值
v = 2 and 4 print(v) # 4 """ 值 and 值 逻辑运算的结果取决于那个值 结果等于值 这里是先进行 布尔计算 都是True 就会返回后面的值 若是第一个值是False 就会返回第一个值 若是第一个值是True 后面是False 就会返回后面的值
v1 = 1 or 2 v2 = 0 or 2 """ 值 or 值 这里也是进行 布尔计算 第一个是 True 就会返回 第一个值 第一个是 False 就会返回 第二个值 """
v1 = 1 and 8 or 9 and 10 or 11 and 0 or "" and "123" 8 # 先算and 后算 or
1.10 基础概念
1.10.1 进制
-
二进制 计算机底层都是用二进制计算的
十进制 -->其他进制度
data = 235 data = int(data) v1 = bin(238) # 转换二进制 0b11101110 v2 = oct(data) # 转换八进制 0o353 v3 = hex(data) # 转换十六进制度 0xeb print(v1, v2, v3) # 打印出来的数字 开头有两个字符不是数值 是描述该数值是什么进制
其他进制度 转换 十进制度
d1 = int("0b11101011", base=2) print(d1) d2 = int("0o353", base=8) print(d2) d3 = int("0xeb", base=16) print(d3)
2 计算机中的单位
内存 : 8G 硬盘: 1T 流量: 300M
计算机底层代码本质是 01010101010, 计算机中为方便搞了一些单位
-
b(bit) , 位
1 1位 1 1位 10 2位 100 3位
-
B (byte) , 字节
8位是一个字节 10001001 1个字节 11000100 10001001 2个字节
-
KB(kilobyte), 千字节
1024个字节 就是 1KB(千字节) 10001001 10001001 1000100 10001001...,1KB 1KB = 1024B = 1024 * 8b
-
M(megabyte), 兆
1024KB 是1M 1M= 1024KB = 1024 * 1024 B = 1024 * 1024 * 8b
-
G(Gigabyte), 千兆
1024M 就是1G 1G = 1024 M= 1024* 1024 KB = 1024 * 1024 * 1024 B = 1024* 1024 * 1024 * 8b
-
T(Terabyte), 万亿字节
1024个G 就是 1T
-
...其他更大的单位是PB/EB/ZB/YB/BB/NB/DB 不再赘述
2.1编码
2.1.1 ascii编码
ascii编码中总共有256个对应关系 可以在网上搜索对照
在ascii 编码中是用一个字节表示二进制 一个字节是8位 故而只能有256个对照关系
2.1.2 gbk 和gb-2312
GB-2312, 国家信息委员会制作(1980年)
GBK, GB-2312的扩展,包含中日韩等文字。(1995) (有些国家的文字没有包含)
1.10.3.3 Unicode(万国码)
-
ucs2, 用固定的2个字节去表示二进制和文字的对应关系。 2**16 =65536
-
ucs4, 用固定的4个字节去表示二进制和文字的对应关系。2**32 =4294967296
文字 二进制 且 00100100 00100101 ucs2 # 用完了 且 00000000 00000000 00100100 00100101 ucs4 # 没有用完 新的文字可以加入对应关系
2.1.3 utf-8编码
对unicode 进行压缩, 用尽可能少的自己来表示数据
-以后开发时,一定要用utf-8 -UTF-8编码中, 1个中文用三个字节
2.1.4 Python
python 编码中字符串要转换为 utf-8编码字节 存储 传输
name = "张三" # 字符串类型, Unicode来存储(uc4) 每个字都是4个字节 data = name.encode("utf-8") # 字节类型 utf-8编码 转换为16进制 print(data) # \xe5\xbc\xa0 \xe4\xb8\x89' 转换为16进制
在Python 开发中, 以后再去做文件存储或网络传输时, 不能直接用字符串, 而是需要将字符串转换为 utf-8编码的字节 然后再来传输和存储
实例 在文件中写入一个字符串
# 在文件中写入一个字符串 name = "张三" # 1.打卡内容 file_object= open("vip.txt",mode="ab") # 2.写入内容 file_object.write(name.encode("utf-8")) # 3.关闭文件 file_object.close()
-
文件编码
-
写文件,写了很多的文本的内容->按照某种编码去存储文件。(010100101010)。
-
读文件,真正的内容读取出来,用同样的编码才能读取到文本内容。
-
-
Python解释器编码,指的是打开和读取某个py文件的内容时,用的是这种编码。utf-8
-
Python解释器将代码读取到内存之后,是需要进行:
语法分析&词法分析
name ="武沛齐" > 字符串处理,去unicode对应关系中找01010101010 age =b"xxooasdf" -> 字节,去utf-8对应关系找01010001
name ="武沛齐" > 字符串处理,去unicode对应关系中找01010101010 age =b"xxooasdf" -> 字节,去utf-8对应关系找01010001 python