Home  >  Article  >  Backend Development  >  python basic knowledge teaching

python basic knowledge teaching

巴扎黑
巴扎黑Original
2017-06-23 15:33:292262browse

Section 1 Python File Type

Source Code

  • Python source code files have the extension "py" and are interpreted by the Python program and do not require compilation

Byte code

  • The file with the extension "pyc" generated after the Python source file is compiled

  • Compilation method

    import py_compile
    py_compile.compile("hello.py")

Optimization code

  • Optimized source file with the extension ".pyo"

  • python -O -m py_compile hello.py

All three of the above can be run directly


Section 2 Python Variables

Definition of Variables

  • A variable is an area in computer memory. Variables can store data within a specified range. value, and the value can change.

Variable naming

  • Variable names are composed of letters, numbers, and underscores.

  • Numbers cannot begin

  • Keywords cannot be used

  • a a1 a_ a_1

Assignment of variables

  • is the process of variable declaration and definition

    a = 1
    ld(a)


Section 3 Operators and Expressions

Case: Write your own four-arithmetic operator

#!/usr/bin/python

import sys
running = True

while running:
    try:
        t = int(raw_input())
        p = int(raw_input())
    except EOFError:
        break

    print 'operator + result\n', t + p
    print 'operator - result\n', t - p
    print 'operator * result\n', t * p
    print 'operator / result\n', t / p

Python operators include

  • Assignment operator

    x = 3, y = 'abcde'      #等于
    x += 2                  #加等于
    x -= 2                  #减等于
    x *= 2                  #乘等于
    x /= 2                  #除等于
    x %= 2                  #求余等于
  • Arithmetic operator

    x + y                   #加法
    x - y                   #减法
    x * y                   #乘法
    x / y                   #实数除法
    x // y                  #整数除法
    x % y                   #求余
    x**y                    #求幂
  • Relational operator

    x < y                   #大于
    x > y                   #小于
    x <= y                  #小于等于
    x >= y                  #大于等于
    x != y                  #不等于
    x == y                  #完全等于
  • Logical operator

    and                     #与
    or                      #或
    not                     #非

Expression

  • Expression is to use operators to combine different data (including variables and functions) An expression connected by certain rules

Priority of operators

  • In regular expressions, there are multiple operators , for example: 1+2*3-1/2*3/2, then there is a problem of calculating priority

  • Generally, operators exist High and low levels, in the same expression, operators with high precedence: For example: 1*2+3*3 = 11 instead of 15

  • for Operators of the same level are processed from left to right. For example: 8*4/2*3 = 48

  • The operator precedence from low to high is:

    Lambda
    逻辑或:or
    逻辑与:and
    逻辑非:not
    成员测试:in      not in
    同一性测试:is      is not
    比较:<   <=  >   >=  !=  ==
    按位或:|
    按位异或:^
    按位与:&
    移位:<<  >>
    加法与减法:+   -
    乘法、除法与取余:*   /   %
    正负号:+x  -x
    按位翻转:~x
    指数:**


Section 4 Data Type

Case

  • ##123and"123"Is it the same

  • () [] {}

  • ##Data type

    Computers are used to assist people, and the classification of the real world is also mapped in programming to facilitate abstract analysis.
  • Number
  • String
  • List
  • Tuple
  • Dictionary
  • Number type

    Integer type
  • Long integer
  • ##Floating point type
  • Complex number type
  • Numeric type - integer int

The range represented by integer int is -2147483648 to 2147483647. For example: 0, 100, -100
  • Range example of int:
num=2147483647
type(num)       #输出结果: <type &#39;int&#39;>
  • Number type - long integer long
  • The range of long is very large. It can be said that almost any large integer can be stored.
    • In order to distinguish between ordinary integers and long integers, you need to add L or lowercase l after the integer. For example:
    • 51856678L, -0x22345L
    • num = 11
      type(num)       #输出结果: <type &#39;int&#39;>
      num = 9999999999999999999999
      type(num)       #输出结果: <type &#39;long&#39;>
      Number type - floating point float

    For example:
      0.0 , 12.0, -18.8, 3e+7
    • Example:
    num = 0.0
    type(num)       #输出结果: <type &#39;float&#39;>
    num = 12
    type(num)       #输出结果: <type &#39;int&#39;>
    num = 12.0
    type(num)       #输出结果: <type &#39;float&#39;>
  • Number type-plural complex
  • Python provides built-in support for complex numbers, which is something that most other software does not have
    • Complex number examples:
    • 3.14j, 8.32e-36j
    • Example:
    >>> num=3.14j
    >>> type(num)
    <type &#39;complex&#39;>
    >>> num
    3.14j
    >>> print num
    3.14j
  • String String
  • A group defined using quotation marks Can contain a collection of numbers, letters, and symbols (non-special system symbols).
      Strval='This is a test'
      Strval="This is a test"
      Strval="""This is a test"""
    • Triple quotation marks (docstring) are usually used to create strings, detailed explanation in object-oriented
    • Section 5 Sequence

      Basic concepts

      Lists, tuples and strings are all two parts of a sequence
      • The main features are the index operator and the slicing operator.
      • The index operator allows us to grab a specific item from a sequence.
        • The slice operator allows us to obtain a slice of a sequence, that is, a part of the sequence.
        • #The index can also be a negative number, and the position is calculated from the end of the sequence.
      • Therefore, shoplist[-1] represents the last element of the sequence, while shoplist[-2] grabs the penultimate item of the sequence
        • The slicing operator is the sequence name followed by a square bracket, an optional pair of numbers in the square bracket, and separated by a colon.
        • shoplist[1:3]返回从位置1开始,包括位置2,但是停止在位置3的一个序列切片,因此返回一个含有两个项目的切片。shoplist[:]返回整个序列的拷贝。你可以用负数做切片。负数用在从序列尾开始计算的位置。例如,shoplist[:-1]会返回除了最后一个项目外包含所有项目的序列切片

        • 注意这与你使用的索引操作符十分相似。记住数是可选的,而冒号是必须的。

        • 切片操作符中的第一个数(冒号之前)表示切片开始的位置,第二个数(冒号之后)表示切片到哪里结束。如果不指定第一个数,Python就从序列首开始。如果没有指定第二个数,则Python会停止在序列尾。

        • 注意:返回的序列从开始位置开始,刚好在结束位置之前结束。即开始位置是包含在序列切片中的,而结束位置被排斥在切片外。

      序列的基本操作

      • len():求序列的长度

      • +:连接两个序列

      • *:重复序列元素

      • in:判断元素是否在序列中

      • max():返回最大值

      • min():返回最小值

      • cmp(tuple1, tuple2):比较两个序列值是否相同

      元组()

      • 元组和列表十分类似,只不过元组和字符串一样是不可变的,即你不能修改元组。

        • 元组通过圆括号中用逗号分割的项目定义。

        • 元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。

      • 创建元组

        • 一个空的元组由一对空的圆括号组成,如:myempty=()

        • 含有单个元素的元组,singleton=(2)

        • 一般的元组

          zoo=('wolf', 'elephant', 'penguin')
          new_zoo=('monkey', 'dolphin', zoo)
      • 元组操作

        • 元组和字符串一样属于序列类型,可通过索引和切片操作。

        • 元组值亦不可变


      第六节 序列-列表

      列表[]

      • list是处理一组有序项目的数据结构,即你可以在一个列表中存储一个序列的项目。

      • 列表是可变类型的数据。

      • 列表的组成:用[]表示列表,包含了多个以逗号分隔开的数字,或者子串。

        list1=['Simon', 'David', 'Clotho']
        list2=[1,2,3,4,5]
        list3=["str1", "str2", "str3", "str4"]

      列表操作

      • 取值

        • 切片和索引

        • list[]

      • 添加

        • list.append()

      • 删除

        • del(list[])

        • list.remove(list[])

      • 修改

        • list[]=x

      • 查找

        • var in list

      • 示例:

        >>> list1=['jack', 20, 'male']
        >>> list1
        ['jack', 20, 'male']
        >>> list1.append('USA')
        >>> list1
        ['jack', 20, 'male', 'USA']
        >>> list1.remove('USA')
        >>> list1
        ['jack', 20, 'male']
        >>> help(list1.remove)
        >>> list1[1]=22
        >>> list1
        ['jack', 22, 'male']
        >>> 22 in list1
        True

      对象与类快速入门

      • 对象和类,更好的理解列表。

      • 对象=属性+方法

      • 列表是使用对象和类的一个例子

        • 当你使用变量i并给它赋值时候,比如整数5,你可以认为你创建了一个类(类型)int的对象(实例)i。

        • help(int)

      • 类也有方法,即仅仅为类而定义的函数。

        • Python为list类提供了append方法,这个方法让你在列表尾添加一个项目。

        • mylist.append('an item')列表mylist中增加字符串。注意,使用点号来使用对象的方法。

        • 仅在该类的对象可以使用这些功能。

        • 例如:

      • 类也有变量,仅为类而定义的变量

        • 仅在该类的对象可以使用这些变量/名称

        • 通过点号使用,例如mylist.field。


      第七节 字典

      基本概念

      • 字典是Python中唯一的映射类型(哈希表)。

      • 字典对象是可变的,但是字典的键必须使用不可变的对象,并且一个字典中可以使用不同类型的键值。

      • keys()或者values()返回键列表或值列表。

      • items()返回包含键值对的元值。

      • 示例:

        >>> dict={'name': 'jack', 'age' : 30, 'gender':'male' }
        >>> dict['name']
        'jack'
        >>> dict['age']
        30
        >>> dict['gender']
        'male'
        >>> dict.keys()
        ['gender', 'age', 'name']
        >>> dict.values()
        ['male', 30, 'jack']
        >>> dict.items()
        [('gender', 'male'), ('age', 30), ('name', 'jack')]

      创建字典

      • dict = {}

      • 使用工厂方法dict()

        fdict=dict(['x',1], ['y',2])
      • 内建方法:fromkeys(),字典中的元素具有相同的值,默认为None

        ddict={}.fromkeys(('x','y'), -1)
        #输出结果:{'x': -1, 'y': -1}

      访问字典中的值

      • 直接使用key访问:key不存在会报错,可以使用has_key()或者in和not in判断,但是has_key方法即将废弃。

      • 循环遍历:for key in dict1.keys():

      • 使用迭代器:for key in dict1:

      更新和删除

      • 直接用键值访问更新;内建的update()方法可以将整个字典的内容拷贝到另一个字典中。

      • del dict1['a']:删除字典中键值为a的元素

      • dict1.pop('a'):删除并且返回键为'a'的元素

      • dict1.clear():删除字典所有元素

      • del dict1:删除整个字典

      字典相关的内建函数

      • type(), str(), cmp()(cmp很少用于字典的比较,比较依次是字典的大小、键、值)

      工厂函数dict()

      * 例如:

      dict(zip(('x','y'),(1,2)))
      dict(x=1,y=2)
      #输出结果:{'x': 1, 'y': 2}
      • 使用字典生成字典比用copy慢,因此这种情况下推荐使用copy()

      常用函数

      • len():返回序列的大小

      • hash() : 用于判断某个对象是否可以做一个字典的键,非哈希类型报TypeError错误

      • dict.clear(): 删除字典中的所有元素

      • dict.fromkeys(seq, val=None): 以seq中的元素为键创建并返回一个字典,val为制定默认值

      • dict.get(key, default=None): 返回key的value,如果该键不存在返回default指定的值

      • dict.has_key(key):判断字典中是否存在key,建议使用in或not in代替

      • dict.items():返回健值对元组的列表

      • dict.keys():返回字典中键的列表

      • dict.iter*(): iteritems(), iterkeys(), itervalues()返回迭代子而不是列表

      • dict.pop(key[,default]):同get(),区别是若key存在,删除并返回dict[key],若不存在则返回default,未指定值,抛出KeyError异常

      • dict.setdefault(key, default=None):同set(),若key存在则返回其value,若key不存在,则dict[key]=default

      • dict.update(dict2):将dict2中的键值对添加到字典dict中,如果有重复则覆盖,原字典不存在的条目则添加进来。

      • dict.values():返回字典中所有值的列表


      第八节 流程控制

      if else

      • if语句

        • 一个字符串是否为空的

        • 一个运算结果是否为零

        • 一个表达式是否可用

        • True:表示非空的量(比如:string, tuple, set, dictonary等),所有非零数

        • False:表示0,None,空的量等。

        • Python的if语句类似其他语言。if语句包含一个逻辑表达式,使用表达式比较,在比较的结果的基础上作用出决定。

          if expression:
              statement
        • 注:Python使用缩进作为其语句分组的方法,建议使用4个空格代替缩进。

        • 逻辑值(bool)用来表示诸如:对与错,真与假,空与非空的概念

        • 逻辑值包含了两个值:

        • 作用:主要用于判读语句中,用来判断

        • else语句

          • 语法

            if expression:
                statement
            else:
                statement
          • 如果条件表达式if语句解析为0或false值。else语句是一个可选的语句,并最多只能有一个else语句。

        • elif语句

          • 语法

            if expression:
                statement
            elif expression2:
                statement
            elif expression3:
                statement
            else:
                statement
          • elif语句可以让你检查多个表达式为真值,并执行一个代码块,elif语句是可选的。可以有任意数量的elif。

        • 嵌套的if...elif...else构造

          if expression1:
              statement
              if expression2:
                  statement
              else:
                  statement
          else:
              statement
        • 使用逻辑运算符and、or、not

          if expression1 and expression2:
              statement
          else:
              statement

        for循环

        • 循环是一个结构,导致一个程序重复一定次数。

        • 条件循环也是如此。当条件变为假,循环结束。

        • for循环:

          • 在Python for循环遍历序列,如一个列表或一个字符。

        • for循环语法:

          for iterating_var in sequence:
              statements
        • 注:如果一个序列包含一个表达式列表,它是第一个执行。
          然后,该序列中的第一项赋值给迭代变量iterating_var。接下来,执行语句块。列表中的每个项目分配到iterating_var,代码块被执行,直到整个序列被耗尽。

        • 注:格式遵循代码块缩进原则

        • 例子:

          for letter in 'python':
              print 'Current Letter: ', letter
          
          fruits=['banana', 'apple', 'mango']
          for fruit in fruits:
              print 'Current fruit: ', fruit
        • 迭代序列指数(索引):

          • 遍历每个项目的另一种方法是由序列本身的偏移指数(索引)

          • 例子

            fruits=['banana', 'apple', 'mango']
            for index in range(len(fruits)):
                print 'Current fruit: ', fruits[index]
          • 注:‘迭代’,指重复执行一个指令。

        range

        • 循环结构是用于迭代多个项的for语句,迭代形式可以循环序列的所有成员。

        • range(i,j[,步进值])

          • 如果所创建的对象为整数,可以用range

          • i为初始数值

          • j为终止数值,但不包括在范围内,步进值为可选参数,不选的话默认是1

          • i不选择的话默认为0

        • 例子:

          sum = 0
          for num in range(1, 101, 1):
              sum += num
          print sum

        遍历字典

            dic={'name': 'jack', 'age': 20, 'gender':'male'}
            for key in dic:
                val = dic[key]
                print key,val
        
            for key,val in dic.items():
                print key, val

        for循环控制

            for x in range(10):
                if x == 1:
                    pass
                if x == 2:
                    continue
                if x == 5:
                    break;
            else
                print 'end'

        while循环

        • while循环,直到表达式变为假。表达的是一个逻辑表达式,必须返回一个true或false值

        • 语法:

          while expression:
              statement
        • 注:遵循代码块缩进原则

          while x != 'q':
              x = raw_input('please input something, q for quit: ')
              if not x:
                  break
          else:
              print 'end'

        The above is the detailed content of python basic knowledge teaching. For more information, please follow other related articles on the PHP Chinese website!

        Statement:
        The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn