zoukankan      html  css  js  c++  java
  • Python的入门

    一 编程语言分类

       机器语言:直接使用二进制指令去编写程序,直接操作硬件,必须考虑硬件细节
       汇编语言:用英文标签取代二进制指令去编写程序,直接操作硬件,必须考虑硬件细节  
       高级语言:用人类能理解的表达方式去编写程序,通过操作系统间接地操作硬件,无需考虑硬件细节
    ​      编译型:类似于谷歌翻译
    ​      解释型:类似与同声传译

        执行效率:机器语言>汇编语言>编译型>解释型
       开发效率:解释型>编译型>汇编语言>机器语言

       跨平台性:解释型>all

    二 安装python解释器,实现多版本共存

                      设置环境变量PATH

    三 执行python程序的两种方式:

               1.交互式环境:用来调试环境,无法永久保存代码      

       优点:输入一行代码立刻返回结果
    ​   缺点:无法永久保存代码
    ​            2.把程序以文件的方式将代码永久保存了下。执行方式如下:python3 D:\test.txt   
    ​        
       注意:运行python2程序是不考虑文件后缀名的,但约定俗成,应该将python程序的后缀名命名为.py
    ​                                                    

    四、运行python程序的三个步骤(**)重要

    1、先启动python解释器
    ​              
    2、将python程序当中普通的文本文件读入内存(此时没有语法的概念)
    ​              
    3、python解释器解释执行刚刚读入内存的代码,开始识别python的语法

    五.变量

    print('hello')  # 这一个打印功能

    1.什么是变量
    量:记录某种现实世界中事物的某种状态
    变:事物的某种状态是可以发生变化的

    2.为何要用变量
    为了让计算机能够像人一样记录下来事物的某种状态

    3.如何用变量
    原则:先定义,后引用

    先定义
    age=18

    定义变量的三大组成部分:

    1.1 变量名:是访问到值的唯一方式
    1.2 =:将变量值的内存地址绑定给变量名
    1.3 变量的值:用来表示事物的某种状态,是我们要存储的数据

    2.后引用
    print(age)

    3.变量名的命名
    3.1 大前提:变量名应该对值有描述性的效果
    3.2 命名规范
    I. 变量名只能是字母、数字或下划线的任意组合
    II. 变量名的第一个字符不能是数字
    III. 关键字不能声明为变量名['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']
    3.3 命名风格:
    I:驼峰体
    OldboyOfAge=73
    II:纯小写字母+下划线
    oldboy_of_age=73(最好用这种风格)

    六.与用户交互

       1.接收用户输入

       name=input("请输入您的账号:") #name="egon"
      print(name)

       2.格式化输出 

       name = input("请输入您的账号:")  # name="egon"
      age = input("请输入您的年龄:")  # age="18"
      print(name,age)
      print('my name is %s my age is %s' % (name,age))

    七,内存管理

    1.Cpython解释器的垃圾回收机制

    什么是垃圾:当一个值身上没有人绑定任何变量名(该值的引用计数=0)时,该值就是一个垃圾

    01.引用计数增加

    age=18 # 18的引用计数等于1
    x=age # 18的引用计数等于2
    print(age)
    print(x)

    02.引用计数减少

    age=19 #18的引用计数等于1
    print(age)

    del x #18的引用计数等于0

    2.变量值的三个特征:

    id: 反映的是内存地址
    type:数据类型
    value: 值
    age=18

    print(id(age))       ->   140718207260224
    print(type(age))   ->       <class 'int'>
    print(age)             ->              18

    总结:

    2.1. id相同,值一定相同
    2.2. 值相同,id可以不同

    x='name:egon age:18'
    y='name:egon age:18
    '
    id(x)
    2847698422856
    id(y)
    er2847698422928

    x=11111111111111111111111111231231231231222222222222
    y=11111111111111111111111111231231231231222222222222

    print(id(x))
    print(id(y))

    3.is 与 ==

    ==:值是否相等
    is:id是否相等

    4.可变类型与不可变类型

    可变类型: 值改变,id不变,证明就是在改变原值
    不可变类型:值改变,id也变,证明根本不是在改变原值,是创建了新值,原值就是不可变类型

    x=10
    print(id(x))  
    x=11
    print(id(x))    

    l=['a','b','c']
    print(id(l))
    l[0]='A'
    print(id(l))
    print(l)

    八.python2中与用户交互

    1.在python3中只有一个input:

    特点:会用户输入的任意内容都存成str类型

    x=input('>>>: ') #x='123123123'
    print(type(x))

    salary=input('>>: ') #salary='3000'
    salary=int(salary)
    print(salary * 12)

    2.在python3中只有一个raw_input,与python3的input一模一样

    x=raw_input('>>>: ')

    要求用户必须输入一个明确的类型,输入什么类型就存成什么类型
    x=input('>>>: ')

    九.数据类型的基本使用

    1: 数字类型

    01.整型int

    作用:用来记录年龄、等级、各种号码状态
    定义:
    age=10 #age=int(10)
    print(type(age))
    使用:
    print(age + 1)
    print(age > 3)

    02.浮点型float

    作用:用来记录身高、体重、工资状态
    定义:
    salary=3.1 #salary=float(3.1)
    print(type(salary))
    使用:
    print(3.1 + 2.3)
    print(3.1 > 2.3)
    print(3.1 > 2)
    print(3.1 + 2)

    2:字符串类型str

    作用:用来记录描述性质状态,比如名字、性别
    定义:在单引号('')、双引号("")、三引号内(''' ''',""" """),包含一系列的字符
    x='abc' # x=str('abc')
    print(type(x))

    y="abc"6

    z="""
    abc
    xxxx
    """

    print(type(x))
    print(type(y))
    print(type(z))

    msg='my name is "egon"'
    使用:
    print('abc'+'def') # 仅限于str类型直接相加
    print('abc'*10) # *的只能是数字

     

    x='abcdef'
    y='z'
    print(x > y)
    print('a' > 'Z' )

    3:列表类型list

    作用:用来记录多个值,用索引对应值,索引反映是位置# 定义:在[]内用逗号分隔开多个任意类型的值
    l=[1,3.1,'xxx',['a','b','c']] #l=list(...)
    print(type(l))
    使用
    print(l[0])
    print(l[2])
    print(l3)

    students_info=[
    ​     ['egon',18,['play',]],
    ​     ['alex',18,['play','sleep']]
    ]

    print(students_info1[0])

     

    4:字典类型dict

    作用:用来记录多个值,用key对应value,其中key对value有描述性的功能
    定义:在{}内,用逗号分割开多元素,每一个元素都是key:value的形式,其中value可以是任意类型,而key通常应该是str类型
    d={'x':1,'y':3.1,'z':['a','b'],'m':{'aaa':1111}} #d=dict(...)
    print(type(d))
    使用:
    print(d['x'])
    print(d'm')
    print(d'z')

    列表的方式

                                name   age  gender   compay_info

    emp_info=['egon',18,'male',['Oldboy','SH',200]]
    print(emp_info[1])
    print(emp_info[3][2])
    字典的方式
    emp_info={'name':'egon','age':18,"gender":'male','company_info':['Oldboy','SH',200]}

    print(emp_info['age'])
    print(emp_info['company_info'][0])

    names=['egon','alex','kevin']
    dic={'name1':'egon','name2':'alex','name3':'kevin'}

    5:布尔类型:True,Flase

    print(type(True))
    print(type(False))

    tag1 = True
    tag2 = True
    print(id(tag1))
    print(id(tag2))

    age = 18
    print(age > 18)

    所有数据类型自带布尔值
    布尔值为假的数据类型:0,None,空
    print(bool([]))
    print(bool(''))
    print(bool(None))

    6: None

    print(type(None))

    十.基本运算符

    01. 比较运算符

          

    print(10 != 11)

    了解

    x=None
    print(x == None)
    print(x is None)

    l1=['abc',1,['a','b','c']]
    l2=['z','aa',]
    print(l2 > l1)

    02. 逻辑运算符

    and:连接左右两个条件,只有两个条件同时成立时and运算的结果为True

    print(10 > 9 and 3 > 2 and 'egon' == 'egon' and True)

    or:连接左右两个条件,两个条件成立任意一个or运算的结果就为True
    print(False or False or True or False or 3 > 10)

    res=(True or (False and True)) or ((False or True) and False)
    res=(True or False) or (True and False)
    res=True or False
    print(res)
    not:取反
    print(not 10 > 3)

    x=None
    print(not x is None)
    print(x is not None)

    age1=18
    age2=19
    print(age2 is not age1)

     

     

    name_bk='egon'
    pwd_bak='123'
    name=input('please input your name: ')
    pwd=input('please input your password: ')
    if name == name_bk and pwd == pwd_bak:
      print('login successfull')
    else:
      print('user name or password error')

    03.算术运算

     

    04.赋值运算

    增量赋值

    age=18
    age+=1#age=age + 1
    print(age)

    age=18
    age/=3 #age=age/3
    print(type(age))

    age**=2 #age=age**2

    交叉赋值

    x=10
    y=20
    temp=x
    x=y
    y=temp


    x,y=y,x
    print(x,y)

    链式赋值

    x=10
    y=x
    z=y
    x=y=z=10

    print(id(x))
    print(id(y))
    print(id(z))

    解压赋值

    l=[1.2,2.2,3.3,4.4,5.5]
    a=l[0]
    b=l[1]
    c=l[2]
    d=l[3]
    e=l[4]

    a,b,c,d,e=l
    l=[1.2,2.2,3.3,4.4,5.5]
    a,b,*_=l
    print(a,b)

    a,*_,b=l
    print(a,b)

    *_,a,b=l
    print(a,b)

    十一.常量

    python程序中变量名使用大写字母来表示的常量,比如AGE_OF_OLDBOY=73

    十二.流程控制之if判断

    语法1:

    '''
    if 条件:
      代码1
      代码2
      代码3
      ...

    '''
    示例:
    age_of_bk=30
    print('start.....')

    inp_age=input('>>>: ') #inp_age='18'
    inp_age=int(inp_age)
    if inp_age == age_of_bk:
      print('猜对了')

    print('end.....')

    语法2:

    '''
    if 条件:
      代码1
      代码2
      代码3
      ...
    else:
      代码1
      代码2
      代码3
      ...
    '''
    示例:
    age=38
    gender='male'
    is_beautiful=True

    if age >= 18 and age <= 25 and gender == 'female' and is_beautiful:
      print('开始表白。。。。')

    else:
      print('阿姨好')

    语法3:

    '''
    if 条件1:
      代码1
      代码2
      代码3
      ...
    elif 条件2:
      代码1
      代码2
      代码3
      ...
    elif 条件3:
      代码1
      代码2
      代码3
      ...
    elif 条件4:
      代码1
      代码2
      代码3
      ...
    else:
      代码1
      代码2
      代码3
      ...
    '''
    示例:
    '''
    如果:
          成绩>=90,那么:优秀

          如果成绩>=80且<90,那么:良好

          如果成绩>=70且<80,那么:普通

          其他情况:很差
    '''
    score=input('your score>>: ')
    score=int(score)
    if score >=90:
      print('优秀')
    elif score >=80:
      print('良好')
    elif score >=70:
      print('普通')
    else:
      print('很差')

    语法4:

    '''
    if 条件1:
      if 条件2:
          代码1
          代码2
          代码3
          ...
      代码2
      代码3

    '''
    示例:
    age=18
    gender='female'
    is_beautiful=True
    is_successful=True

    if age >= 18 and age <= 25 and gender == 'female' and is_beautiful:
      print('开始表白。。。。')
      if is_successful:
          print('在一起')
      else:
          print('我逗你玩呢。。。')
    else:
      print('阿姨好')

    十三.流程控制之while循环

    1.while循环:条件循环

    基本语法

    while 条件:
      代码1
      代码2
      代码3
      ...
    示范
    name_of_bk='egon'
    pwd_of_bk='123'

    tag=True
    while tag:
      inp_name=input('your name>>: ')
      inp_pwd=input('your password>>: ')
      if inp_name == name_of_bk and inp_pwd == pwd_of_bk:
          print('login successful')
          tag=False
      else:
          print('username or password error')

    2.while+break:break代表结束本层循环

    name_of_bk='egon'
    pwd_of_bk='123'

    while True:
      inp_name=input('your name>>: ')
      inp_pwd=input('your password>>: ')
      if inp_name == name_of_bk and inp_pwd == pwd_of_bk:
          print('login successful')
          break
      else:
          print('username or password error')

    3.while + continue: continue代表结束本次循环,直接进入下一次

    示范:
    count=1
    while count < 6:
      if count == 3:
          count+=1
          continue
      print(count)
      count+=1

    4.while + else

    count=0
    while count <= 10:
      print(count)
      count+=1

    else:
      print("else的子代块只有在while循环没有被break打断的情况下才会执行")

    5.死循环

    count=0
    while True:#True 本身就是真呀

    print("你是风儿我是沙,缠缠绵绵走天涯...",count)
    count +=1

    6.输错三次退出

    name_of_bk='egon'
    pwd_of_bk='123'

    count=0
    tag=True
    while tag:
      if count == 3:
          print('输错的次数过多。。。')
          break
      inp_name=input('your name>>: ')
      inp_pwd=input('your password>>: ')
      if inp_name == name_of_bk and inp_pwd == pwd_of_bk:z
          print('login successful')
          while tag:
              print("""
              0 退出
              1 购物
              2 支付
              3 查看购物
              """)
              cmd=input('>>>: ')
              if cmd == '0':
                  tag=False
                  continue
              if cmd == '1':
                  print('购物。。。。。。。')
              elif cmd == '2':
                  print('支付。。。。。')
              elif cmd == '3':
                  print('查看购物车')
              else:
                  print('输入错误的指令')
      else:
          print('username or password error')
          count+=1 #count=3 输错3次

    十四.for循环

    用while循环:
    l=['a','b','c']
    print(len(l))
    i=0
    while i<len(l):
      print(l[i])
      i+=1
    用for循环:
    l=['a','b','c']
    for item in l: #item='a'
      print(item)

    dic={'x':111,'y':222,'z':333}
    for k in dic: #k='x'
      print(k,dic[k])

    1.while循环 vs for循环

    01.
    while循环:称之为条件循环,循环的次数取决于条件何时为False.
    for循环:称之为迭代式循环,循环的次数取决于数据的包含的元素的个数.
    02.
    for循环专门用来取值,在循环取值方面比while循环要强大,以后但凡.
    遇到循环取值的场景,就应该用for循环

        0   1    2
    l=['a','b','c']
    for i in range(3):
      print(i,l[i])

    2.for+continue

    names=['egon','kevin','alex','hulaoshi']
    for name in names:
      if name == 'alex':continue
      print(name)

    3.for+break

    names=['egon','kevin','alex','hulaoshi']
    for name in names:
      if name == 'alex':break
      print(name)

    4.for+else

    names=['egon','kevin','alex','hulaoshi']
    for name in names:
      if name == 'alex':break
      print(name)
    else:
      print('=====>')

    5.for循环嵌套

    for i in range(3): 
      for j in range(2):
          print(i,j)
    '''
    外层循环第一次:i=0
      内层循环
          0,0
          0,1
           
    外层循环第二次:i=1
      内层循环
          1,0
          1,1
    外层循环第三次: i=2
      内层循环
          2,0
          2,1
           

    '''

     
     
  • 相关阅读:
    VScode快捷键:单行注释和多行注释
    常见状态码的含义
    2019年10月22日 文件操作复习
    2019年10月7日 函数复习
    2019年10月4日 元类
    2019年10月2日 property补充
    2019年10月1日 实现延迟计算功能
    2019年9月30日 property流程分析
    2019年9月29日 自定制property
    2019年9月23日 类的装饰器的应用
  • 原文地址:https://www.cnblogs.com/liubinliuliu/p/10009262.html
Copyright © 2011-2022 走看看