python

------------恢复内容开始------------

python介绍

 
 
 
 
python的创始人为吉多·范罗苏姆(Guido van Rossum)。1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序,作为ABC语言的一种继承。 
 
 
 
 
 
目前Python主要应用领域:
云计算: 云计算最火的语言, 典型应用OpenStack
WEB开发: 众多优秀的WEB框架,众多大型网站均为Python开发,Youtube, Dropbox, 豆瓣。。。, 典型WEB框架有Django
科学运算、人工智能: 典型库NumPy, SciPy, Matplotlib, Enthought librarys,pandas
系统运维: 运维人员必备语言
金融:量化交易,金融分析,在金融工程领域,Python不但在用,且用的最多,而且重要性逐年提高。原因:作为动态语言的Python,语言结构清晰简单,库丰富,成熟稳定,科学计算和统计分析都很牛逼,生产效率远远高于c,c++,java,尤其擅长策略回测
图形GUI: PyQT, WxPython,TkInter
 
 
 
 
 
Python在一些公司的应用: 
谷歌:Google App Engine 、code.google.com 、Google earth 、谷歌爬虫、Google广告等项目都在大量使用Python开发
CIA: 美国中情局网站就是用Python开发的
NASA: 美国航天局(NASA)大量使用Python进行数据分析和运算
YouTube:世界上最大的视频网站YouTube就是用Python开发的
Dropbox:美国最大的在线云存储网站,全部用Python实现,每天网站处理10亿个文件的上传和下载
Instagram:美国最大的图片分享社交网站,每天超过3千万张照片被分享,全部用python开发
Facebook:大量的基础库均通过Python实现的
Redhat: 世界上最流行的Linux发行版本中的yum包管理工具就是用python开发的
豆瓣: 公司几乎所有的业务均是通过Python开发的
知乎: 国内最大的问答社区,通过Python开发(国外Quora)
春雨医生:国内知名的在线医疗网站是用Python开发的
除上面之外,还有搜狐、金山、腾讯、盛大、网易、百度、阿里、淘宝 、土豆、新浪、果壳等公司都在使用Python完成各种各样的任务。 
 

 

python历史

 
 
 
 
1989年,为了打发圣诞节假期,Guido开始写Python语言的编译器。Python这个名字,来自Guido所挚爱的电视剧Monty Python’s Flying Circus,也有人说,之所以 Guido 会选择 Python 作为该编程语言的名字,是因为他是一个叫 Monty Python 戏剧团体的忠实粉丝。。他希望这个新的叫做Python的语言,能符合他的理想:创造一种C和shell之间,功能全面,易学易用,可拓展的语言。
1991年,第一个Python编译器诞生。它是用C语言实现的,并能够调用C语言的库文件。从一出生,Python已经具有了:类,函数,异常处理,包含表和词典在内的核心数据类型,以及模块为基础的拓展系统。
Granddaddy of Python web frameworks(框架), Zope 1 was released in 1999
python1989年诞生,但是在1999年开始他都不支持网站开发。
Python 1.0 - January 1994 增加了 lambda, map, filter and reduce.
Python 2.0 - October 16, 2000,加入了内存回收机制,构成了现在Python语言框架的基础
Python 2.4 - November 30, 2004, 同年目前最流行的WEB框架Django 诞生
Python 2.5 - September 19, 2006  一个短暂的版本
Python 2.6 - October 1, 2008
Python 2.7 - July 3, 2010
In November 2014, it was announced that Python 2.7 would be supported until 2020, and reaffirmed(再生的) that there would be no 2.8 release(需要) as users were expected to move to Python 3.4+ as soon as possible
Python 3.0 - December 3, 2008
#python3.0和2.6这两个python版本是同年的,python的2.6发布之后,紧接着python3.0也被发布,之所以又开发3.0是因为,在2.6发行之后,进行了一个激进的变更,因为语言是一个社区的人再开发,所以有一些功能被重复开发,而且python语言已经开发了很多年了,也有一些过时的东西,为了清理掉一些重复的东西和一些过时以及一些不符python语言开发理念的东西,所以就进行了一次激进的升级,升级到了3.0版本,而且这版和之前的版本不兼容。比如豆瓣是2.4版本开发的,这些源代码用3.0版本运行是不行的。2.6和2.7两个版本是之前的版本和之后的版本的过渡版本。
Python 3.1 - June 27, 2009
Python 3.2 - February 20, 2011
Python 3.3 - September 29, 2012
Python 3.4 - March 16, 2014
Python 3.5 - September 13, 2015
 

 

python官网

 
 
 
 
https://www.python.org
 

32bit和64bit的区别

 
 
 
 
32bit  CPU一次性处理数据能力,32位系统的处理器最大只支持4G(2**32)内存,如果硬件是8个GB的,但是系统是32bit的,那么他最大识别4个GB。
 
 
 
 
 
64bit   理论上64bit的支持最大的内存是2**64位,但是实际上支持不到这么大,目前主板支持的最大的内存是100多个GB,同样是4GB的内存配上一个64位的系统和32位系统,理论上速度是一样的。按照理论上,64位和32位系统都能吃满这4GB的内存,但是他们都不能吃掉这4G的内存,因为操作系统就需要占用一定的内存。
 

系统运行浅析

 
 
 
 
硬盘:5400转 = 每分钟(每分钟可以在硬盘上找5400次数据)= 骑自行车
     7200转 = 每分钟 = 骑电动车
     10000转 = 每分钟 = 骑快速电动车
     15000转 = 每分钟 = 骑摩托车 机械硬盘最快的 
     SSD = 相当于Tesla,是硬盘中最快的,但还是比内存要慢很多
 

python版本的选择

 
 
 
 
In summary : Python 2.x is legacy遗产, Python 3.x is the present and future of the language
Python 3.0 was released发布 in 2008. The final 2.x version 2.7 release came out in mid-2010, with a statement of
extended support for this end-of-life release. The 2.x branch will see no new major releases after that. 3.x is
under active development and has already seen over five years of stable releases, including version 3.3 in 2012,
3.4 in 2014, and 3.5 in 2015. This means that all recent standard library improvements, for example, are only
available by default in Python 3.x.
 

python 2 vs 3

 
 
 
 
1. python3默认支持中文
2. python3不兼容2
3,核心语法调整,更易学
4. 新特性默认只在3上有
 

 

第一个python程序

通过cmd来执行程序

1.写好hello.txt文档---->2.打开cmd---->3.找到hello.txt---->cd c: (change directory c:)---->dir(查找当前目录的文件)---->4.在c盘目录下找到python解释器;---->5.执行hello.txt

 
 
 
 
cmd下
cd 目录名
cd .. 返回上一层目录
cd ../.. 返回上面两层
cd ../../..  返回三层
...
进入d盘
c:>d:
D:>
在D盘下执行c盘下的hello.txt
D:>python3解释器python.exe c:hello.txt
hello world
 

 

文件后缀及环境变量介绍

 
 
 
 
文件后缀为文件的扩展名,可用于区分文件的类型
.txt  记事本文件
.doc  word文件
.xls  excel文件
.ppt  PPT文件
.exe  可执行文件
.jpg  .png  图片
.gif  动图
.pdf  PDF文件
.mp4 .avi  视频
.py   python文件
.java  java文件
.c  .h  c源码
.php  PHP文件
 
 
 
 
 
环境变量为路径的变量,可认为是路径的快捷键
环境变量的设置:复制路径--鼠标右键我的电脑--属性--高级属性设置--环境变量--系统变量--Path--黏贴
 

python程序文件执行方式

 
 
 
 
1.交互器
缺点程序不能保存,主要用于程序语法的测试
2.集成开发环境
 

 

变量

什么是变量

 
 
 
 
Variables(变量) are used to store(储存) information to be referenced(被日后调用) and manipulated(操作更改) in a computer program. They also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves. It is helpful to think of variables as containers that hold information. Their sole purpose is to label and store data in memory. This data can then be used throughout your program.
注:python是弱类型语言,它的变量可以更改,如 a = "hello world!" , 变量a还可以改成一个整数类型
变量名是我们用来描述数据的,所以我们起一个变量名可以让我们见名知义,如students_num = 30, 我们可以从这个变量名可以看出,它代表学生的数量
我们可以理解变量为一个容器,用来装数据的
 

变量定义的规则

 
 
 
 
变量名只能是 字母、数字或下划线的任意组合,不可以是特殊字符(#,%等),不能用中文
变量名的第一个字符不能是数字
以下关键字不能声明为变量名
变量名不能以数字、符号开头
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
在python中,变量名通常不以大写字母开头,大写字母开头的我们用来区分常量和变量
 

变量的赋值

 
 
 
 
>>> name = "zgzeng"
>>> name
'zgzeng'
>>> name2 = name
>>> name2
'zgzeng'
>>> print(name)
zgzeng
>>> print(name2)
zgzeng
>>> name = "tom"
>>> name
'tom'
>>> name2
'zgzeng'
#  赋值"zgzeng"给变量name,内存中开辟了一个空间存了“zgzeng”,然后name指向了zgzeng
#  再写一个变量名为name2=name,这次赋值使得name2的值指向了zgzeng
#  如果重新给name重新赋值为tom,这样又在内存中重新开辟了一个空间,而这个空间存放的数据就为‘tom’
#  而name2的指向依然是原来的zgzeng
#  将name2 = name,其实两者并联地指向了zgzeng这个内存空间
 

内存的释放

 
 
 
 
内存的大小是固定的,也就是内存条的大小,如果内存一直再用那么内存迟早会用完,但是因为有一个内存的回收机制,使得一些不用的被占用的内存得到释放。在python中,这里的内存是自动回收,不用的内存就会自动回收,也就是变量和变量名之间的指向关系被清空,内存就会被回收
 
怎样清空指向关系
 
 
 
 
# 清空方法1:
>>> name ="tom"
>>> name
'tom'
>>> del name
>>> name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'name' is not defined
#  这里name变量名没有了,那么内存中的“tom”所占用的内存就会被回收,内存中tom就会被清除
# 清空方法2:
>>> name = "tom"
>>> name = "jack"
>>> name
'jack'
# 这里的name开始被赋值为“tom”,那么内存就开辟了一个空间来存放“tom”,而之后name重新被赋值成jack,那么内存中重新开辟了一块空间来存放jack,此时原来存放tom的那块空间就相当于废弃了,就会被内存自动回收机制重新回收。
 

注释

 
 
 
 
单行注释为#
多行注释为"""需注释的内容"""  或 '''注释内容'''
 

 

用户输入

 
 
 
 
death_age = 80
input("please input your name:")     # please input your name:zgzeng
input("please input your age:")      # please input your age:23
name = input("please input your name:")   # please input your name:zgzeng
print("name 的数据类型是", type(name))    # name 的数据类型是 <class 'str'>
age = input("please input your age:")   # please input your age:23
print("age的数据类型是", type(age))      # age的数据类型是 <class 'str'>
print("Your name is:", name)          #  Your name is: zgzeng
print("Your age is:", age)         # Your age is: 23
print(name, "still live for", death_age-int(age), "years")    
# zgzeng still live for 57 years
# 字符串拼接
print(name + "still live for" + str(death_age-int(age)) + "years")    # 字符串只能和字符串拼接,字符串不能和整数拼接,需要将数字转成字符串
print("{} still live for {} years".format(name, death_age-int(age)))   
# zgzeng still live for 57 years
 

if条件语句实现猜年龄

 
 
 
 
princal_age = 56
guess_age = int(input("please input the age of your guessing:"))
if guess_age != princal_age:
    print("the answer of your guessing is wrong")
else:
    print("the answer of your guessing is yes")
 

缩进错误信息

 
 
 
 
IndentationError(缩进): expected(期待) an indented(缩进) block(块)
 
 
 
 
 
princal_age = 56
while True:
    guess_age = int(input("please input the age of your guessing:"))
    if guess_age > princal_age:
        print("Unfortunately! Your anwser is too bigger.")
    elif guess_age < princal_age:
        print("Unfortunately! Your anwser is too smaller")
    else:
        print("Congratulations!Your answer of your guessing is right")
        break
 
 
 
 
 
socre =int(input("请输入您的socre:"))
if socre > 90:
    print("A")
elif socre > 80:
    print("B")
elif socre > 70:
    print("C")
if socre > 60:
    print("D")
else:
    print("E")
# 代码从上到下执行,如果输出的结果是91,但是91即大于90也大于80,那他会打印什么出来呢?
# 代码从上到下执行,如果是条件判断,当符合第一个条件就执行,后面就不执行的。
 

 

运算符,表达式

算术运算符

 
 
 
 
a = 1 + 2
print(a)       # 3
b = 8 - 1
print(b)       # 7
c = 2 * 2
print(c)       # 4
d = 8 / 2
print(d)       # 4.0
e = 9 % 2
print(e)       # 1
f = 7 // 2
print(f)       # 3
g = 2 ** 4
print(g)       # 16
 

 

赋值运算符

 
 
 
 
num = 8
num += 3   # 等同于 num = num + 1
num -= 3   # 等同于 num = num - 1
num *= 3   # 等同于 num = num * 1
num /= 3   # 等同于 num = num / 1
num //= 3  # 等同于 num = num // 3
num %= 3   # 等同于 num = num % 3
 

逻辑运算符

 
 
 
 
and or not
and 
条件1 and 条件2:
当条件1和条件2都为True时,那么返回值为True
当条件1和2中至少有一个是False,那么返回值为False
or
条件1 or 条件2
条件1和条件2中至少一个是True,那么返回值为True
当所有条件都为False,那么返回值为False
not
not 条件
如果条件为False,那么返回值为True
如果条件为True,那么返回值为False
 
 
 
 
 
注意:
and or not 三个条件并没有优先级,判断的顺序是从左往右,但是存在短路原则
短路原则
and 当条件1是False的时候,那么后面的 条件就不会被计算了
or  当条件1是True的时候,那么后面的条件就不会被计算了
例如
>>>>not not True or False and not True
>>>>True
# not not 这里的判断的结果就是True,not not True这里的判断的结果就是True,当遇到or的时候,后面的条件就不会被运算
>>>>True or True False and not True
>>>>True
# True为真,遇到or,后面的条件也就不会运算了
 

while循环

while循环的结构

 
 
 
 
while 条件:      # 当条件为真的时候,那么执行下面的语句
print("执行语句")
 

输出1-100的语句

 
 
 
 
按照我们的输出语句:
print("1")
print("2")
print("3")
...
num = 1
while num <= 100:
print(num)
# 上述程序陷入死循环
num = 1
while num <= 100:
print(num)
num += 1
输出1-100之间的偶数
num2 = 1
while num2 <= 100:
    if num2 % 2 == 0:
        print(num2)
    num2 += 1
 

数据类型

 
 
 
 
整型和长整型
在py3中只有整型,没有整型和长整型之分,在py2中有区分
int(整型)
  在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
  在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
long(长整型)
  跟C语言不同,Python的长整数没有指定位宽,即:Python没有限制长整数数值的大小,但实际上由于机器内存有限,我们使用的长整数数值不可能无限大。
  注意,自从Python2.2起,如果整数发生溢出,Python会自动将整数数据转换为长整数,所以如今在长整数数据后面不加字母L也不会导致严重后果了。
  
  
float(浮点型)
  浮点数用来处理实数,即带有小数的数字。类似于C语言中的double类型,占8个字节(64位),其中52位表示底,11位表示指数,剩下的一位表示符号。
complex(复数)
  复数由实数部分和虚数部分组成,一般形式为x+yj,其中的x是复数的实数部分,y是复数的虚数部分,这里的x和y都是实数。
注:Python中存在小数字池:-5 ~ 257
 
 
 
 
 
布尔值
布尔值分别是True和False
 
 
 
 
 
字符串
字符串的“加法”运算是字符串拼接
 

for循环

 
 
 
 
user = "zgzeng"
password = "12345"
# user_name = input("please input your username:")
# user_password = input("please input your user_password:")
_flag = "y"
while True:
    flag = input("please input your flag:")
    if flag == _flag:
        user_name = input("please input your username:")
        user_password = input("please input your user_password:")
        if user_name == user and user_password == password:
            print("welcome to logining")
        else:
            print("invalid user_name or user_password")
    else:
        break
# 限制登录的次数为3次
for i in range(3):
    user_name = input("please input your username:")
    user_password = input("please input your user_password:")
    if user_name == user and user_password == password:
        print("welcome to logining")
        break
    else:
        print("invalid user_name or user_password")
        
        
# 如果登录了3次还是错的,程序自动跳出并给出提示
passed_authentication = False   # 这个变量在我们的程序中作为一种flag
for i in range(3):
    user_name = input("please input your username:")
    user_password = input("please input your user_password:")
    if user_name == user and user_password == password:
        print("welcome to logining")
        passed_authentication = True   # 真
        break
    else:
        print("invalid user_name or user_password")
if not passed_authentication:
    print("Already pass,break!!!")
    
    
for i in range(3):
    user_name = input("please input your username:")
    user_password = input("please input your user_password:")
    if user_name == user and user_password == password:
        print("welcome to logining")
        break
    else:
        print("invalid user_name or user_password")
else:    # 只要上面的for循环正常执行,中间没有被打断,就会执行这个else语句
print("输入的次数超过了规定")
 
 
 
 
 
# 死循环
counter = 0
while True:
    if counter > 2 **25:
        counter += 1
        # 我们可以看出cpu的计算速度很快,几乎一秒钟就可以计算2**25次,当我们打印的时候就会显得慢,但并不代表cpu计算的慢
 
 
 
 
 
# 为了更加人性化,我们可以设置登录的次数每3次就提示一次是否继续登录
counter = 0
while counter < 3:
    user_name = input("please input your username:")
    user_password = input("please input your user_password:")
    if user_name == user and user_password == password:
        print("welcome to logining")
        break
    else:
        print("Invalid username or password!")
    counter += 1
    
    if counter ==3:
        keep_going_choice = input("还继续吗?[y/n]")
        if keep_going_choice == "y":
            counter = 0
            
            
else:
    print(".....")
 
 
 
 
 
for i in range(10):
    if i > 5:
        continue
    print(i)
    for j in range(10):
        print("layer:", j)
        if j == 6:
            break      # 我们想要实现一个功能,是子层循环break之后,我父级循环层也break
    break              # 但这样的写法,不管子层break与否,父层循环也break
# 那我们怎么来实现父子层循环之间break的关联呢?
# 标志位
exit_flag = False
for i in range(10):
    if i < 5:
        continue
    print(i)
    for j in range(10):
        print("layer:", j)
        if j == 6:
            exit_flag = True
            break
    if exit_flag:
        break
 
 
 
 
 
a, b = [2, 4]
print(a, b)   # 2 4
"""
这里面当有a和b两个变量来接受一个列表的时候,那么分别给a和b赋值
"""
应用:
for i, j in enumerate(goods_info, 1):
    print(i, ">>>", j)
    
    
1 >>> ['Mac', 9000]
2 >>> ['Python Book', 80]
3 >>> ['Bike', 1500]
4 >>> ['Kindle', 1000]
5 >>> ['Tesla', 900000]
 这里的i和j分别赋值给了goods和序号
 i,j = (goods_info, 1)
 

购物车程序

 
 
# 首先有一个商品列表
goods_list = [
    ["Mac", 9000],
    ["Python Book", 80],
    ["Bike", 1500],
    ["Kindle", 1000],
    ["Tesla", 900000]
]
salary = input("Your Salary:")
shopping_car = []
flag = False
if salary.isdigit():
    salary = int(salary)
    while True:
        # 遍历商品列表
        for i, j in enumerate(goods_list, 1):
            print(i, ":",  j)
        # 给出用户选择
        choice = input("请输入商品编号[退出请按q]:")
        if choice.isdigit():
            choice = int(choice)
            if choice in range(len(goods_list)):
                print("您选的商品是{}".format(goods_list[choice-1]))
                # shopping_car = shopping_car.append(goods_list[choice-1])
                # print("您的购物车中有{}".format(shopping_car))
                extra_money = salary - int(goods_list[choice-1][1])
                print("您当前的余额为{}".format(extra_money))
        elif choice == "q":
            break
        else:
            print("Invalid input")
else:
    print("Invalid inp

------------恢复内容结束------------

原文地址:https://www.cnblogs.com/zgzeng/p/12112979.html