zoukankan      html  css  js  c++  java
  • Python——基础篇【一】——变量与赋值、用户交互、条件判断、循环控制、数据类型、文本操作

    目录

    Python——基础篇【一】

    1、学习Python目的

    2、Python简史介绍

    3、Python3特性

    4、Hello World程序

    5、变量与赋值

    6、用户交互

    7、条件判断与缩进

    8、循环控制

    9、循环次数限制

    10、简单的嵌套循环

    11、常用数据类型

    12、字符串格式化

    13、列表常用操作

    14、列表后续操作

    15、文件基本操作

    1、学习Python目的:

    1、学完之后,可以做开发运维监控、自动化软件、聊天软件、BBS、博客和网站。

    2、投资自己,结识更多的朋友,变更更优秀的人

    Python——基础篇【一】

    2、Python简史介绍

    python创始人Guido,荷兰人,Python源自他所挚爱的电视剧Monty Python's Flying Circus。Python编译器使用C语言实现,能够调用C语言库文件。1991年初,Python发布了第一个公开发行版。

    Python版本

    Python1.0   1994年

    python2.0   2000年(加入了内存回收机制)

    Python2.4    2004年(Pyhton诞生了目前最流行的WEB框架Django)

    Python2.5    2006年

    Python2.6    2008年(过渡版本,过渡到3.0版本)

    Python2.7    2010年(过渡版本,2014年11月官方声明,Python 2.7 支持到2020年,2.7是最后一个版本,不会出现2.8版本,官方希望大家都尽快切换到3.4版本)

     

    Python3.0    2008年 (不兼容2.0版本语法和功能)

    Python3.2    2011年

    python3.3    2012年

    Python3.4    2014年

    Python3.5    2015年

    注释:

    1、2008年python 2.6和Python3.0同时发布,2.0里面有重复的功能重复的模块,发布3.0目的是去繁从简,加入新的功能,把很多语法合并在一起等等,从而有了3.0版本.(2008年的时候,大家还用的是2.4版本,3.X版本不兼容2.X版本语法和功能)

     

    Python应用:

    Web Programming(web开发方向): Django,pyramid,Bottle,Tornado,Flask,web2py(列出的是主流web框架)

    GUI Development(图形界面开发):wxPython,tklnter,PyGtk,PyGObject,PyQt(做图形界面越来越少,现在流行H5)

    Scientific and Numeric(科学计算):Scipy,pandas(作金融分析),IPython

    software Development(软件开发):Buildbot(程序集成、自动测试、自动部署),trac(处理bug),Roundup(处理Bug)

    System Administration:Ansible,Salt,OpenStack(虚拟化)(运维三剑客)

     

    Twisted 是Python下最优秀的异步网络框架,目前还不支持python3.0,是因还没改完(目前进度:https://twistedmatrix.com/trac/milestone/Python-3.x)

     

    使用Python开发的实例

    Facebook、Youtube、Yelp(product)(国外的大众点评)、Quora(国外的知乎)、Instagram、豆瓣、知乎、雅虎、SOHO、腾讯(蓝鲸)、网易、金山

     

    3、Python3新特性

    print()

    Old: print "The answer is", 2*2
    New: print("The answer is", 2*2)
    Old: print x, # Trailing comma suppresses newline
    New: print(x, end=" ") # Appends a space instead of a newline
    Old: print # Prints a newline
    New: print() # You must call the function!
    Old: print >>sys.stderr, "fatal error"
    New: print("fatal error", file=sys.stderr)
    Old: print (x, y) # prints repr((x, y))
    New: print((x, y)) # Not the same as print(x, y)!
    

     

    ALL IS UNICODE NOW
    从此不用为编码错误而烦恼

    (A, *REST, B) = RANGE(5)

    (a, *rest, b) = range(5)

     

    Python2.x到Python3.0新旧模块name对照表

    还有谁不敢支持Python3?

    目前除了Twisted不支持Python3,其他主流模块都支持,(Twisted 是Python下最优秀的异步网络框架,目前还不支持python3.0,是因还没改完,目前修改进度:https://twistedmatrix.com/trac/milestone/Python-3.x

    总结:哪些Python2的语法在3里变了?

    1、1/2终于等于0.5了

    2、print“hello world”变成了print(“hello world!”)

    3、raw_input没了

    4、class Foo:写法不能用了,只能class Foo(object)

    安装

    Windows:

    1、下载安装包
        https://www.python.org/downloads/
    2、安装
        默认安装路径:C:python27
    3、配置环境变量
        【右键计算机】--》【属性】--》【高级系统设置】--》【高级】--》【环境变量】--》【在第二个内容框中找到 变量名为Path 的一行,双击】 --> 【Python安装目录追加到变值值中,用 ; 分割】
        如:原来的值;C:python27,切记前面有分号

    注:在安装Python过程中,可以勾选添加环境变量会自动添加

    更新Python :

    卸载重装即可
    

     

    Linux:

    无需安装,原装Python环境
       
    ps:如果自带2.6,请更新至2.7
    

     更新Python

     Linux的yum依赖自带Python,为防止错误,此处更新其实就是再安装一个Python!

    查看默认Python版本
    python -V
       
    1、安装gcc,用于编译Python源码
        yum install gcc
    2、下载源码包,https://www.python.org/ftp/python/
    3、解压并进入源码文件
    4、编译安装
        ./configure
        make all
        make install
    5、查看版本
        /usr/local/bin/python2.7 -V
    6、修改默认Python版本
        mv /usr/bin/python /usr/bin/python2.6
        ln -s /usr/local/bin/python2.7 /usr/bin/python
    7、防止yum执行异常,修改yum使用的Python版本
        vi /usr/bin/yum
        将头部 #!/usr/bin/python 修改为 #!/usr/bin/python2.6
    

    4、Hello World程序

    python3 #进入交互器

    print("Hello World!")

      #换行
    后缀名

    hello.py(python)、hello.sh(shell)、hello.java(java)、hello.c(C)、hello.php(PHP)、hello.rb(ruby)

    vim hello.py   #编辑python文件

    #!/usr/bin/python3   #默认位置,python升级之后默认在/user/local/bin下,如果还写#!/usr/bin/python可能调用还是原来版本的python

    #!/usr/bin/env python   #最安全的写法

    print("hello world!")(wq!)

    python hello.py #执行python文件

    chmod +X hello.py #给python加可执行权限

    ll hello.py   #查权限

    ./hello.py  #执行python

     

    5、变量与赋值

    变量、注释、数据类型

    变量传参,变量存在的意义是在程序中存储一些临时的数据,在程序运行中不断的用来调用

    变量起名

    1、显式(通俗易懂)

    2、nums_of_alex_gf = 19

    3、NumsOfAlexGf = 2

    4、names-of-alex-gf = 22(不合法)

    5、5name = 数字不能开头,可以写成na5me=

    6、!name特殊字符不能有,!@#¥%……&

    7、name of teacher = 不能有空格

    8、某些关键字不能为变量名

     
    a=3
    b=a
    id(a),id(b) #查看变量内存地址
     

    6、用户交互

    name=input("Please input your name:")

    jack

    print(jack)

     

    eval()#python3.0查找内存里的变量

     

    7、条件判断与缩进

    sex = input("input your gender:")
    if sex == "girl":
       print("I would like to have a little monkey with jack")
    elif sex =="man":
        print("Going to homesexual!...")
    else:
        print("Pervert!")
    

    8、循环控制

    (猜数字)

    while true: # 死循环

    lucky_num = 19
    input_num = -1
    while lucky_num != input_num:
        input_num = int(input('input the guess num:'))  #int是把字符串格式转为数字格式
        if input_num > lucky_num:
            print("the real num is smaller.")
        elif input_num < lucky_num:
            print("the real num is bigger.")
    print("Bingo!")
    

    break #结束整个循环

    while True:
         input_num = int(input("input the guess num:"))
         if input_num == lucky_num:
             print("bingo!")
             break
          elif input_num >lukcky_num:
              print("the real numer is smaller.")
           else:
              print("the real num is bigger...")
    

     9、循环次数限制

    lucky_num = 19
    input_num = -1
    guess_count = 0
    while guess_count < 3:
        print("guess conut",guess_count)
        input_num = int(input('input the guess num:'))
        if input_num > lucky_num:
            print("the real num is smaller.")
        elif input_num < lucky_num:
            print("the real num is bigger.")
        else:
            print("Bingo!")
            break
        guess_count += 1  #guess_count=guess_count+1
    else:
        print("Too many retrys!")
    

     for循环

     

    for i in rang(3):
         print i
    

     

    lucky_num = 19
    input_num = -1
    for i in range(3):
        input_num = int(input('input the guess num:'))
        if input_num > lucky_num:
            print("the real num is smaller.")
        elif input_num < lucky_num:
            print("the real num is bigger.")
        else:
            print("Bingo!")
            break
    else:print("Too many retrys!")
    

     

    10、简单的嵌套循环

    for j in range(5):
        for i in range(10):
            if i <5:
                continue  #跳出本次循环,继续下一次循环
            if j>3:
                break     #跳出整个循环
            print(i)
    

     

    count = 0
    while True:
         print("count")
         count +=1
         if count >=5:
             break
    

     

    11、常用数据类型

    数据类型:

    a=2**31

    a

    type(a) #显示数据类型

    uname -a #linux版本检查

     

    12、字符串格式化

    name = input("name:").strip()
    age = input("age:").strip()
    job = input("job:").strip()
    
    #print("Information of []:"+ name + "
    Name:[]"+name+"
    Age;[]"+age+"
    Job:[]"+job)
    msg='''
    Information of %s:
        Name:%s
        Age:%s
        Job:%s
    '''%(name,name,age,job)
    print(msg)
    #print("Information of %s:
    Name:%s
    Age:%s
    Job:%s" %(name,name,age,job))
    
    #%s  字符串
    #%d  数字
    #%f  浮点
    #''''''1、注释 2、表示段落

     

    13、列表常用操作

    .strip()  #去掉两边空格,也可以指定去除某个字符

    name_list = ["alex","65b","tenglan"]
    
    name_list[1]
    name_list[2]
    #1,2为索引
    name_list.append(“eric”) #追加
    .count #统计
    .extend #扩展
    .index #索引
    .insert #插入
    .pop #删除一个
    .remove #删除指定的一个
    .reverse #反转
    .sort #排序

    help(name) #查看方法
    dir(name_list) #查看列表功能

     

    14、列表的后续操作

    a[0:2]  #切片

    a[0:5:3]   #隔一个切一个

    a[-2:-1]   #取后两个

    a.extend(b)
    

     

     

    15、文件基本操作

     file_obj = open("路径",“模式”)

    obj.read()  #读取所有内容

    obj.readlines() #读取所有行分隔成字符串

    #每次仅读取一行数据

    for line in obj:
    
          print iine
    

     obj.write("内容") #写内容

    obj.close()  #关闭文件

    f = open("test.log","w")
    
    f.write("This is the first line
    ")
    f.write("This is the second line
    ")
    f.write("This is the 3 line
    ")
    f.write("This is the 4 line
    ")
    

     

    f= open("test.log","r")
    
    # print (f.readlines())
    

     

    for line in f:
        if"3" in line:
            print("this is the third line")
        else:
            print (line)
    

     追加

    f=open("test.log","a")
    f.write("6
    ")
    f.write("7
    ")
    f.close()
    

     写读‘

    f=open("test.log","w+")
    f.write("new line
    ")
    print("data:",f.read())
    f.close()
    

     

  • 相关阅读:
    爬虫-requests-html
    pillow
    bs4-mysql-豌豆荚
    代理池-豆瓣电影
    Codeforces 1373D
    Codeforces 1365D
    AtCoder "NOMURA Programming Competition 2020" C
    Codeforces 1359D
    Codeforces 1359C
    Codeforces 1358D
  • 原文地址:https://www.cnblogs.com/yard/p/5386555.html
Copyright © 2011-2022 走看看