第一周-第06章节-Python3.5-第一个python程序
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:chenjisong
@file: HelloWorld.py
@time: 2019/04/15
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
print("HelloWorld!!!")
===========================================================
G:\Python3.7.3\python.exe G:/practise/oldboy/day1/HelloWorld.py
HelloWorld!!!
Process finished with exit code 0
第一周-第07章节-Python3.5-变量
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:chenjisong
@file: HelloWorld.py
@time: 2019/04/15
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
name = "chenjisong"
name2 = name
print("My name is",name,name2)
=================================================================
G:\Python3.7.3\python.exe G:/practise/oldboy/day1/HelloWorld.py
My name is chenjisong chenjisong
Process finished with exit code 0
解释:name值为chenjisong,name将值赋给name2,所以name2也等于chenjisong ,故结果为:My name is chenjisong chenjisong
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:chenjisong
@file: HelloWorld.py
@time: 2019/04/15
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
name = "chenjisong"
name2 = name
print("My name is",name,name2)
print(id(name))
print(id(name2))
print("=================================")
name = "Paochege"
print("My name is",name,name2)
print(id(name))
print(id(name2))
======================================================================
G:\Python3.7.3\python.exe G:/practise/oldboy/day1/HelloWorld.py
My name is chenjisong chenjisong
54678256
54678256
=================================
My name is Paochege chenjisong
54678768
54678256
Process finished with exit code 0
解释:name值为chenjisong,name将值赋予给name2,那么name2值也为chenjisong,后面name的值发生改变,变成了Paochege,内存地址发生了改变,但是name2的内存地址没有变化,所以结果是:My name is Paochege chenjisong
第一周-第08章节-Python3.5-字符编码与二进制(略二进制)
摘抄至https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431664106267f12e9bef7ee14cf6a8776a479bdec9b9000
因为计算机只能处理数字,如果要处理文本,就必须先把文本转换为数字才能处理。最早的计算机在设计时采用8个比特(bit)作为一个字节(byte),所以,一个字节能表示的最大的整数就是255(二进制11111111=十进制255),如果要表示更大的整数,就必须用更多的字节。比如两个字节可以表示的最大整数是65535
,4个字节可以表示的最大整数是4294967295
。
由于计算机是美国人发明的,因此,最早只有127个字符被编码到计算机里,也就是大小写英文字母、数字和一些符号,这个编码表被称为ASCII
编码,比如大写字母A
的编码是65
,小写字母z
的编码是122
。
但是要处理中文显然一个字节是不够的,至少需要两个字节,而且还不能和ASCII编码冲突,所以,中国制定了GB2312
编码,用来把中文编进去。
你可以想得到的是,全世界有上百种语言,日本把日文编到Shift_JIS
里,韩国把韩文编到Euc-kr
里,各国有各国的标准,就会不可避免地出现冲突,结果就是,在多语言混合的文本中,显示出来会有乱码。
因此,Unicode应运而生。Unicode把所有语言都统一到一套编码里,这样就不会再有乱码问题了。
Unicode标准也在不断发展,但最常用的是用两个字节表示一个字符(如果要用到非常偏僻的字符,就需要4个字节)。现代操作系统和大多数编程语言都直接支持Unicode。
现在,捋一捋ASCII编码和Unicode编码的区别:ASCII编码是1个字节,而Unicode编码通常是2个字节。
字母A
用ASCII编码是十进制的65
,二进制的01000001
;
字符0
用ASCII编码是十进制的48
,二进制的00110000
,注意字符'0'
和整数0
是不同的;
汉字中
已经超出了ASCII编码的范围,用Unicode编码是十进制的20013
,二进制的01001110 00101101
。
你可以猜测,如果把ASCII编码的A
用Unicode编码,只需要在前面补0就可以,因此,A
的Unicode编码是00000000 01000001
。
新的问题又出现了:如果统一成Unicode编码,乱码问题从此消失了。但是,如果你写的文本基本上全部是英文的话,用Unicode编码比ASCII编码需要多一倍的存储空间,在存储和传输上就十分不划算。
所以,本着节约的精神,又出现了把Unicode编码转化为“可变长编码”的UTF-8
编码。UTF-8编码把一个Unicode字符根据不同的数字大小编码成1-6个字节,常用的英文字母被编码成1个字节,汉字通常是3个字节,只有很生僻的字符才会被编码成4-6个字节。如果你要传输的文本包含大量英文字符,用UTF-8编码就能节省空间:
从上面的表格还可以发现,UTF-8编码有一个额外的好处,就是ASCII编码实际上可以被看成是UTF-8编码的一部分,所以,大量只支持ASCII编码的历史遗留软件可以在UTF-8编码下继续工作。
搞清楚了ASCII、Unicode和UTF-8的关系,我们就可以总结一下现在计算机系统通用的字符编码工作方式:
在计算机内存中,统一使用Unicode编码,当需要保存到硬盘或者需要传输的时候,就转换为UTF-8编码。
用记事本编辑的时候,从文件读取的UTF-8字符被转换为Unicode字符到内存里,编辑完成后,保存的时候再把Unicode转换为UTF-8保存到文件:
所以你看到很多网页的源码上会有类似<meta charset="UTF-8" />
的信息,表示该网页正是用的UTF-8编码。
Python的字符串
搞清楚了令人头疼的字符编码问题后,我们再来研究Python的字符串。
在最新的Python 3版本中,字符串是以Unicode编码的,也就是说,Python的字符串支持多语言,例如:
>>> print('包含中文的str')
包含中文的str
对于单个字符的编码,Python提供了ord()
函数获取字符的整数表示,chr()
函数把编码转换为对应的字符:
>>> ord('A')
65
>>> ord('中') 20013 >>> chr(66) 'B' >>> chr(25991) '文'
如果知道字符的整数编码,还可以用十六进制这么写str
:
>>> '\u4e2d\u6587'
'中文'
两种写法完全是等价的。
由于Python的字符串类型是str
,在内存中以Unicode表示,一个字符对应若干个字节。如果要在网络上传输,或者保存到磁盘上,就需要把str
变为以字节为单位的bytes
。
Python对bytes
类型的数据用带b
前缀的单引号或双引号表示:
x = b'ABC'
要注意区分'ABC'
和b'ABC'
,前者是str
,后者虽然内容显示得和前者一样,但bytes
的每个字符都只占用一个字节。
以Unicode表示的str
通过encode()
方法可以编码为指定的bytes
,例如:
>>> 'ABC'.encode('ascii')
b'ABC'
>>> '中文'.encode('utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
>>> '中文'.encode('ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
纯英文的str
可以用ASCII
编码为bytes
,内容是一样的,含有中文的str
可以用UTF-8
编码为bytes
。含有中文的str
无法用ASCII
编码,因为中文编码的范围超过了ASCII
编码的范围,Python会报错。
在bytes
中,无法显示为ASCII字符的字节,用\x##
显示。
反过来,如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes
。要把bytes
变为str
,就需要用decode()
方法:
>>> b'ABC'.decode('ascii')
'ABC'
>>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8') '中文'
如果bytes
中包含无法解码的字节,decode()
方法会报错:
>>> b'\xe4\xb8\xad\xff'.decode('utf-8')
Traceback (most recent call last):
...
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 3: invalid start byte
如果bytes
中只有一小部分无效的字节,可以传入errors='ignore'
忽略错误的字节:
>>> b'\xe4\xb8\xad\xff'.decode('utf-8', errors='ignore')
'中'
要计算str
包含多少个字符,可以用len()
函数:
>>> len('ABC')
3
>>> len('中文') 2
len()
函数计算的是str
的字符数,如果换成bytes
,len()
函数就计算字节数:
>>> len(b'ABC')
3
>>> len(b'\xe4\xb8\xad\xe6\x96\x87') 6 >>> len('中文'.encode('utf-8')) 6
可见,1个中文字符经过UTF-8编码后通常会占用3个字节,而1个英文字符只占用1个字节。
在操作字符串时,我们经常遇到str
和bytes
的互相转换。为了避免乱码问题,应当始终坚持使用UTF-8编码对str
和bytes
进行转换。
由于Python源代码也是一个文本文件,所以,当你的源代码中包含中文的时候,在保存源代码时,就需要务必指定保存为UTF-8编码。当Python解释器读取源代码时,为了让它按UTF-8编码读取,我们通常在文件开头写上这两行:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
第一行注释是为了告诉Linux/OS X系统,这是一个Python可执行程序,Windows系统会忽略这个注释;
第二行注释是为了告诉Python解释器,按照UTF-8编码读取源代码,否则,你在源代码中写的中文输出可能会有乱码。
申明了UTF-8编码并不意味着你的.py
文件就是UTF-8编码的,必须并且要确保文本编辑器正在使用UTF-8 without BOM编码:
如果.py
文件本身使用UTF-8编码,并且也申明了# -*- coding: utf-8 -*-
,打开命令提示符测试就可以正常显示中文:
第一周-第09章节-Python3.5-字符编码的区别与介绍
#!/usr/bin/env python
"""
@author:chenjisong
@file: HelloWorld.py
@time: 2019/04/15
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
name = "你好,世界"
print(name)
======================================================================
G:\Python2.7.5\python.exe G:/practise/oldboy/day1/HelloWorld.py
File "G:/practise/oldboy/day1/HelloWorld.py", line 24
SyntaxError: Non-ASCII character '\xe4' in file G:/practise/oldboy/day1/HelloWorld.py on line 24, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
Process finished with exit code 1
原因:python2中因为没有指定字符编码集,所以报错
#!/usr/bin/env python
#-*- coding:utf-8 _*-
name = ("你好,世界").decode(encoding="utf-8")
print(name)
========================================================================
G:\Python2.7.5\python.exe G:/practise/oldboy/day1/HelloWorld.py
你好,世界
Process finished with exit code 0
解决方法:导入utf-8字符集(#-*- coding:utf-8 _*-)并解码 decode(encoding="utf-8")
在puthon 3中
#!/usr/bin/env python
"""
@author:chenjisong
@file: HelloWorld.py
@time: 2019/04/15
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
name = "你好,世界"
print(name)
========================================================================
G:\Python3.7.3\python.exe G:/practise/oldboy/day1/HelloWorld.py
你好,世界
Process finished with exit code 0
在python 3中无需指定编码格式也无需解码
第一周-第10章节-Python3.5-用户交互程序
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:chenjisong
@file: interaction.py
@time: 2019/04/15
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
username=input("username:")
password=input("Password:")
print("Username is "+username,"and Password is "+password)
===========================================================================
G:\Python3.7.3\python.exe G:/practise/oldboy/day1/interaction.py
username:chenjisong
Password:chenjisong
Username is chenjisong and Password is chenjisong
Process finished with exit code 0
解释:红色部分为用户输入的部分。返回的结果调用了输入的变量,形成了交互程序
字符串拼接第一种方法(占位符):
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:chenjisong
@file: interaction.py
@time: 2019/04/15
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
Name=input("name:")
Age=input("Age:")
Job=input("Job:")
Salary=input("Salary:")
info='''
----------------info of %s------------------
Name:%s
Age:%s
Job:%s
Salary:%s
''' % (Name,Name,Age,Job,Salary)
print(info)
=========================================================================
G:\Python3.7.3\python.exe G:/practise/oldboy/day1/interaction.py
name:chenjisong
Age:23
Job:IT
Salary:3000
----------------info of chenjisong------------------
Name:chenjisong
Age:23
Job:IT
Salary:3000
Process finished with exit code 0
注意:%s代表字符串
%d代表整数类型
%f代表浮点数
字符串拼接第二种方法(字符串转换):
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:chenjisong
@file: interaction.py
@time: 2019/04/15
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
Name=input("name:")
Age=int(input("Age:"))
Job=input("Job:")
Salary=float(input("Salary:"))
info='''
----------------info of %s------------------
Name:%s
Age:%d
Job:%s
Salary:%f
''' % (Name,Name,Age,Job,Salary)
print(info)
====================================================================
G:\Python3.7.3\python.exe G:/practise/oldboy/day1/interaction.py
name:chennjisong
Age:23
Job:IT
Salary:1888
----------------info of chennjisong------------------
Name:chennjisong
Age:23
Job:IT
Salary:1888.000000
Process finished with exit code 0
解释:红色部分为数据类型的强制转换,绿色部分为输入的变量
字符串拼接第三种方法(format):
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:chenjisong
@file: interaction.py
@time: 2019/04/15
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
Name=input("name:")
Age=int(input("Age:"))
Job=input("Job:")
Salary=float(input("Salary:"))
info='''
----------------info of {_Name}------------------
Name:{_Name}
Age:{_Age}
Job:{_Job}
Salary:{_Salary}
''' .format(_Name=Name,_Age=Age,_Job=Job,_Salary=Salary)
print(info)
=============================================================================================
G:\Python3.7.3\python.exe G:/practise/oldboy/day1/interaction.py
name:chenjisong
Age:23
Job:IT
Salary:289
----------------info of chenjisong------------------
Name:chenjisong
Age:23
Job:IT
Salary:289.0
Process finished with exit code 0
解释:将变量与值形成一一对应的关系
字符串拼接第四种方法(花括号):
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:chenjisong
@file: interaction.py
@time: 2019/04/15
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
Name=input("name:")
Age=int(input("Age:"))
Job=input("Job:")
Salary=float(input("Salary:"))
info='''
----------------info of {0}------------------
Name:{0}
Age:{1}
Job:{2}
Salary:{3}
''' .format(Name,Age,Job,Salary)
print(info)
=============================================================================================
G:\Python3.7.3\python.exe G:/practise/oldboy/day1/interaction.py
name:chenjisong
Age:28
Job:IT
Salary:2900
----------------info of chenjisong------------------
Name:chenjisong
Age:28
Job:IT
Salary:2900.0
Process finished with exit code 0
将变量换成花括号中的位置参数,并在format后面指明变量
第一周-第11章节-Python3.5-if else流程判断
最简单的逻辑判断:
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:chenjisong
@file: getpass.py
@time: 2019/04/15
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
_username = "chenjisong"
_password = "chenjisong123"
username = input("Name:")
password = input("Password:")
if _username==username and _password==password:
print("Welcome user {name} login ...".format(name=username))
else:
print("Invalid username or password.")
=====================================================================================
两种结果:
条件不符合:
"G:\Python 3.6.6\python.exe" G:/practise/oldboy/day1/getpass.py
Name:cjs
Password:123
Invalid username or password.
Process finished with exit code 0
条件符合:
"G:\Python 3.6.6\python.exe" G:/practise/oldboy/day1/getpass.py
Name:chenjisong
Password:chenjisong123
Welcome user chenjisong login ...
Process finished with exit code
逻辑判断:当输入的值等于变量中存储的值的时候,打印欢迎登陆成功,反之,返回错误的用户名和密码。
多重逻辑判断:
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:chenjisong
@file: guess.py
@time: 2019/04/16
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
Name_Of_Oldboy = 56
guess_age = int(input("please input your guess number:"))
if guess_age == Name_Of_Oldboy:
print("Yes,you got it.")
elif guess_age > Name_Of_Oldboy:
print("think smaller.")
else:
print("think bigger.")
=====================================================================================
三种判断结果:
1、小于实际数值
"G:\Python 3.6.6\python.exe" G:/practise/oldboy/day1/guess.py
please input your guess number:55
think bigger.
Process finished with exit code 0
2、等于实际数值
"G:\Python 3.6.6\python.exe" G:/practise/oldboy/day1/guess.py
please input your guess number:56
Yes,you got it.
Process finished with exit code 0
3、大于实际数值
"G:\Python 3.6.6\python.exe" G:/practise/oldboy/day1/guess.py
please input your guess number:57
think smaller.
Process finished with exit code 0
第一周-第12章节-Python3.5-while 循环
while死循环,恒成立:
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:chenjisong
@file: while.py
@time: 2019/04/16
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
count = 0
while True:
print(count)
count = count + 1
死循环:当条件成立的时候,永久的执行下去的循环,无法跳出循环
当条件成立时候退出循环,否则一直循环下去:
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:chenjisong
@file: guess.py
@time: 2019/04/16
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
Name_Of_Oldboy = 56
while True:
guess_age = int(input("please input your guess number:"))
if guess_age == Name_Of_Oldboy:
print("Yes,you got it.")
break
elif guess_age > Name_Of_Oldboy:
print("think smaller.")
else:
print("think bigger.")
三次循环计数,如果三次猜不对就退出,如果猜对了立马退出
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:chenjisong
@file: guess.py
@time: 2019/04/16
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
Name_Of_Oldboy = 56
count = 0
while True:
if count == 3: ####三次计数
break ####错误就退出
guess_age = int(input("please input your guess number:"))
if guess_age == Name_Of_Oldboy:
print("Yes,you got it.")
break
elif guess_age > Name_Of_Oldboy:
print("think smaller.")
else:
print("think bigger.")
count += 1 ####每循环一次,计数器加1
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:chenjisong
@file: guess.py
@time: 2019/04/16
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
Name_Of_Oldboy = 56
count = 0
while count < 3: #当次数大于3次的时候退出
guess_age = int(input("please input your guess number:"))
if guess_age == Name_Of_Oldboy:
print("Yes,you got it.")
break
elif guess_age > Name_Of_Oldboy:
print("think smaller.")
else:
print("think bigger.")
count += 1 #每循环一次,计数器加1
while...else....语法
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:chenjisong
@file: guess.py
@time: 2019/04/16
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
Name_Of_Oldboy = 56
count = 0
while count < 3:
guess_age = int(input("please input your guess number:"))
if guess_age == Name_Of_Oldboy:
print("Yes,you got it.")
break
elif guess_age > Name_Of_Oldboy:
print("think smaller.")
else:
print("think bigger.")
count += 1
else:
print("you have tried too many times!!!")
解释:当尝试的次数小于3的时候,走上面的代码。
当尝试的次数大于3的时候,打印 you have tried too many times
第一周-第13章节-Python3.5-while 循环优化版本
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:chenjisong
@file: for.py
@time: 2019/04/16
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
Name_Of_Oldboy = 56
count = 0
for i in range(3):
guess_age = int(input("please input your guess number:"))
if guess_age == Name_Of_Oldboy:
print("Yes,you got it.")
break
elif guess_age > Name_Of_Oldboy:
print("think smaller.")
else:
print("think bigger.")
else:
print("you have tried too many times!!!")
####任性玩:
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:chenjisong
@file: while.py
@time: 2019/04/16
url:https://www.liaoxuefeng.com
functions:
Software:JetBrains PyCharm 4.5.3
"""
Name_Of_Oldboy = 56
count = 0
#for i in range(3):
while count < 3:
guess_age = int(input("please input your guess number:"))
if guess_age == Name_Of_Oldboy:
print("Yes,you got it.")
break
elif guess_age > Name_Of_Oldboy:
print("think smaller.")
else:
print("think bigger.")
count += 1
if count == 3:
continue_confirm = input("do you want to keep guessing...?")
if continue_confirm != "N":
count = 0
解释:当三次猜数都没有猜对且次数大于3时发出继续的确认信息,如果输入N,就退出,如果输入其他任意键,继续
第一周-第14章节-Python3.5-for 循环及作业要求
continue:跳出本次循环进行下一次循环
break :跳出整个循环
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:chenjisong
@file: chengfakoujue.py
@time: 2019/04/16
url:https://www.liaoxuefeng.com
functions:乘法口诀表
Software:JetBrains PyCharm 4.5.3
"""
for i in range(1,10):
for j in range(1,i+1):
print("%d * %d = %2d" % (j,i,j*i),end=" ")
print (" ")
========================================================================
G:\Python3.7.3\python.exe G:/practise/oldboy/day1/chengfakoujue.py
1 * 1 = 1
1 * 2 = 2 2 * 2 = 4
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25
1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 6 * 6 = 36
1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49
1 * 8 = 8 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32 5 * 8 = 40 6 * 8 = 48 7 * 8 = 56 8 * 8 = 64
1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81
Process finished with exit code 0
作业:一.博客
二.编写登录接口
1.输入用户名密
2.认证成功后显示欢迎信息
3.输错三次后锁定
三、多级菜单
1.三级菜单
2.可依次选择进入各子菜单
3.所需知识点,列表,字典