Table of Contents
Section 1 Python File Type
Source Code
Byte code
Optimization code
All three of the above can be run directly
Section 2 Python Variables
Definition of Variables
Variable naming
Assignment of variables
Section 3 Operators and Expressions
Case: Write your own four-arithmetic operator
Python operators include
Expression
Priority of operators
Section 4 Data Type
Case
序列的基本操作
元组()
第六节 序列-列表
列表[]
列表操作
对象与类快速入门
第七节 字典
基本概念
创建字典
访问字典中的值
更新和删除
字典相关的内建函数
工厂函数dict()
常用函数
第八节 流程控制
if else
for循环
range
遍历字典
for循环控制
while循环
Home Backend Development Python Tutorial python basic knowledge teaching

python basic knowledge teaching

Jun 23, 2017 pm 03:33 PM
python Base

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")
    Copy after login

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)
    Copy after login


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
Copy after login

Python operators include

  • Assignment operator

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

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

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

    and                     #与
    or                      #或
    not                     #非
    Copy after login

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
    指数:**
    Copy after login


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;>
Copy after login
  • 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;>
      Copy after login
      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;>
    Copy after login
  • 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
    Copy after login
  • 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"""
      Copy after login
    • 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)
          Copy after login
      • 元组操作

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

        • 元组值亦不可变


      第六节 序列-列表

      列表[]

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

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

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

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

      列表操作

      • 取值

        • 切片和索引

        • 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
        Copy after login

      对象与类快速入门

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

      • 对象=属性+方法

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

        • 当你使用变量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')]
        Copy after login

      创建字典

      • dict = {}

      • 使用工厂方法dict()

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

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

      访问字典中的值

      • 直接使用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 after login
      • 使用字典生成字典比用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
          Copy after login
        • 注:Python使用缩进作为其语句分组的方法,建议使用4个空格代替缩进。

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

        • 逻辑值包含了两个值:

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

        • else语句

          • 语法

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

        • elif语句

          • 语法

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

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

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

          if expression1 and expression2:
              statement
          else:
              statement
          Copy after login

        for循环

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

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

        • for循环:

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

        • for循环语法:

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

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

        • 例子:

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

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

          • 例子

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

        range

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

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

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

          • i为初始数值

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

          • i不选择的话默认为0

        • 例子:

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

        遍历字典

            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
        Copy after login

        for循环控制

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

        while循环

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

        • 语法:

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

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

        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 of this Website
        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

        Hot AI Tools

        Undresser.AI Undress

        Undresser.AI Undress

        AI-powered app for creating realistic nude photos

        AI Clothes Remover

        AI Clothes Remover

        Online AI tool for removing clothes from photos.

        Undress AI Tool

        Undress AI Tool

        Undress images for free

        Clothoff.io

        Clothoff.io

        AI clothes remover

        AI Hentai Generator

        AI Hentai Generator

        Generate AI Hentai for free.

        Hot Article

        R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
        3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
        R.E.P.O. Best Graphic Settings
        3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
        R.E.P.O. How to Fix Audio if You Can't Hear Anyone
        3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
        WWE 2K25: How To Unlock Everything In MyRise
        3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

        Hot Tools

        Notepad++7.3.1

        Notepad++7.3.1

        Easy-to-use and free code editor

        SublimeText3 Chinese version

        SublimeText3 Chinese version

        Chinese version, very easy to use

        Zend Studio 13.0.1

        Zend Studio 13.0.1

        Powerful PHP integrated development environment

        Dreamweaver CS6

        Dreamweaver CS6

        Visual web development tools

        SublimeText3 Mac version

        SublimeText3 Mac version

        God-level code editing software (SublimeText3)

        How does PS feathering control the softness of the transition? How does PS feathering control the softness of the transition? Apr 06, 2025 pm 07:33 PM

        The key to feather control is to understand its gradual nature. PS itself does not provide the option to directly control the gradient curve, but you can flexibly adjust the radius and gradient softness by multiple feathering, matching masks, and fine selections to achieve a natural transition effect.

        Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

        MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

        How to use mysql after installation How to use mysql after installation Apr 08, 2025 am 11:48 AM

        The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

        How to set up PS feathering? How to set up PS feathering? Apr 06, 2025 pm 07:36 PM

        PS feathering is an image edge blur effect, which is achieved by weighted average of pixels in the edge area. Setting the feather radius can control the degree of blur, and the larger the value, the more blurred it is. Flexible adjustment of the radius can optimize the effect according to images and needs. For example, using a smaller radius to maintain details when processing character photos, and using a larger radius to create a hazy feeling when processing art works. However, it should be noted that too large the radius can easily lose edge details, and too small the effect will not be obvious. The feathering effect is affected by the image resolution and needs to be adjusted according to image understanding and effect grasp.

        How to optimize database performance after mysql installation How to optimize database performance after mysql installation Apr 08, 2025 am 11:36 AM

        MySQL performance optimization needs to start from three aspects: installation configuration, indexing and query optimization, monitoring and tuning. 1. After installation, you need to adjust the my.cnf file according to the server configuration, such as the innodb_buffer_pool_size parameter, and close query_cache_size; 2. Create a suitable index to avoid excessive indexes, and optimize query statements, such as using the EXPLAIN command to analyze the execution plan; 3. Use MySQL's own monitoring tool (SHOWPROCESSLIST, SHOWSTATUS) to monitor the database health, and regularly back up and organize the database. Only by continuously optimizing these steps can the performance of MySQL database be improved.

        MySQL download file is damaged and cannot be installed. Repair solution MySQL download file is damaged and cannot be installed. Repair solution Apr 08, 2025 am 11:21 AM

        MySQL download file is corrupt, what should I do? Alas, if you download MySQL, you can encounter file corruption. It’s really not easy these days! This article will talk about how to solve this problem so that everyone can avoid detours. After reading it, you can not only repair the damaged MySQL installation package, but also have a deeper understanding of the download and installation process to avoid getting stuck in the future. Let’s first talk about why downloading files is damaged. There are many reasons for this. Network problems are the culprit. Interruption in the download process and instability in the network may lead to file corruption. There is also the problem with the download source itself. The server file itself is broken, and of course it is also broken when you download it. In addition, excessive "passionate" scanning of some antivirus software may also cause file corruption. Diagnostic problem: Determine if the file is really corrupt

        MySQL can't be installed after downloading MySQL can't be installed after downloading Apr 08, 2025 am 11:24 AM

        The main reasons for MySQL installation failure are: 1. Permission issues, you need to run as an administrator or use the sudo command; 2. Dependencies are missing, and you need to install relevant development packages; 3. Port conflicts, you need to close the program that occupies port 3306 or modify the configuration file; 4. The installation package is corrupt, you need to download and verify the integrity; 5. The environment variable is incorrectly configured, and the environment variables must be correctly configured according to the operating system. Solve these problems and carefully check each step to successfully install MySQL.

        How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

        MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

        See all articles