The first Python knowledge points compiled for beginners

coldplay.xixi
Release: 2020-10-30 16:58:05
forward
4328 people have browsed it

python video tutorialThis article will guide you to learn Python knowledge points today.

The first Python knowledge points compiled for beginners

This article is the first one. There are four articles in total to lay the foundation of Python

1. Basic concepts

1.1 Four types

There are four types of numbers in python: integers, long integers, floating point numbers and complex numbers.

  • Integer, such as 1
  • Long integer is a relatively large integer
  • Floating point number such as 1.23, 3E-2
  • Complex number such as 1 2j , 1.1 2.2j

1.2 String

String (sequence of characters)

  • The use of single quotes and double quotes in Python is exactly the same.
  • Use triple quotes (''' or """) to specify a multi-line string.
  • Escape character'\'
  • Natural string, by adding r or R before the string. For example, r"this is a line with \n", then \n will be displayed, not a line break.
  • Python allows processing unicode strings, prefixed with u or U, such as u"this is an unicode string".
  • Strings are immutable .
  • Concatenate strings literally, such as "this " "is " "string" will be automatically converted to this is string.

1.3 Naming of identifiers

Naming of identifiers

  • The first character must be a letter of the alphabet or the underscore '_'.
  • The other parts of the identifier are letters, numbers and Composed of underscores.
  • Identifiers are case-sensitive.

1.4 Object

Any "thing" used in a python program becomes an "object".

1.5 Logical line and physical line

  • Physical line: It is the line where the code written by the programmer is located.
  • Logical line: It refers to the precompiled source code , the line where the code is located.

Python assumes that each physical line corresponds to a logical line. For example: print( "Hello World" ) is a physical line, and Python hopes that each line has only one statement , because it looks more readable.

If you want to use more than one logical line in a physical line, then you need to use a semicolon (;) to specifically indicate this usage. Semicolon Indicates the end of a logical line/statement.

For example:

count = 5print ( "count" )复制代码
Copy after login

is equivalent to the following statement:

count = 5;print ( "count" );复制代码
Copy after login

Of course it can also be written as the following:

count = 5 ; print ( "count" );复制代码
Copy after login

can even be written like this:

count = 5 ; print ( "count" )复制代码
Copy after login

We use \ for line breaks

print \
("Runsen")复制代码
Copy after login

1.6 Indentation

White spaces are very important in python, lines The leading blank space is the most important, also known as indentation. The blank space at the beginning of the line (spaces and tabs) is used to determine the indentation level of the logical line and thus the statement.

2. Operators and expressions

2.1 Operators and their usage

##<< Shift left, shift the binary system of a number to the left by a certain amount, that is, add as many 0s to the right, For example, 2 << 2 gets 8, and binary 10 becomes 1000>>Shift the bits of a number right Shift a certain number to the right, that is, delete the digits on the right 10>>2 to get 2, binary 1010 becomes 10, directly delete the next 2 digits &Bitwise AND Bitwise AND of 9 & 13 gets 9, binary 1001&1101, becomes 1001, the corresponding positions of both values ​​are 1, then the result is 1, Otherwise, it is 0| bitwise or bitwise or 5 | 3 to get 7. Binary 101&11 becomes 111. If one of the corresponding positions of the two values ​​​​is 1, then the result is 1, that is, if both are 0, the result is 0. 101 and 11 are not both 0, so 111^Bitwise XORBitwise XOR of numbers 5 ^ 3 gets 6, binary 101&11, becomes 110, the two values ​​correspond The positions are the same, then the result is 0, that is, if they are all 0 or both 1, the results are 0, 101 and 11, the first one is 1, so 110## ~<><=##>=greater than or equal to Returns whether 3; = y returns True!=Not equal to Compare whether two objects are equalx = 2; y = 3; x != y returns True. notBoolean "not" If x is True, returns Falsex = True; not y returns False. orBoolean "or" If x is True, it returns True, otherwise it returns the calculated value of y. x = True; y = False; x or y returns True##2.2 Operator precedence.Operator precedence (low to high)
Operator Name Example
Add two objects Addition, such as 3 5 gets 8, characters can also be added 'a' 'b' gets 'ab'
- One number minus another number 5 - 2 gets 3
* Multiplication Multiply two numbers or return a string that is repeated several times 2 * 3 gets 6,'a' * 3 Get 'aaa'
** power Return x raised to the y power 3 ** 4 get 81 (ie 3 * 3 * 3 * 3)
/ divide x by y 4/3 to get 1 (division of integers yields an integer result). 4.0/3 or 4/3.0 gets 1.3333
// Take integer division and return the integer part of the quotient 4 // 3.0 gets 1.
% Modulo Returns the remainder of division 8%3 gets 2. -25.5%2.25 gets 1.5
Bitwise flip The bitwise flip of x is -(x 1) ~5 gets 6
Less than returns whether x is less than y. All comparison operators return 1 for true and 0 for false. 5 < 3 returns 0 (i.e. False) and 3 < 5 returns 1 (i.e. True). It can also be connected arbitrarily: 3 < 5 < 7 returns True.
Greater than Returns whether x is greater than y 5 > 3 returns True. If both operands need to be numbers
less than or equal to, return whether x is less than or equal to yx = 3; y = 6; x <= y returns True
Operator Description

lambda

Lambda expression##orBoolean "or"and Boolean "and" not xBoolean "not" in, not in member Testis,is notIdentity testCompare##`^Bitwise XOR``##,-Addition and Subtraction*,/,%Multiplication, division and remainder x,-xPositive and negative signs~xBitwise flip##**~xx.attributex[index]x[index:index]f(arguments...)(experession,...)[expression,...]##{key:datum,...}Dictionary display'expression,...'String

2.3 输出

python 控制台输出 使用print

print ("abc"  )  #打印abc并换行print ("abc%s" % "d"  )  #打印abcdprint ("abc%sef%s" % ("d", "g")  )  #打印abcdefg复制代码
Copy after login

3、控制流

3.1 if 语句

i = 10n = int(input("enter a number:"))if n == i:
    print( "equal")elif n < i:
    print( "lower")else:    print ("higher")复制代码
Copy after login

3.2 while语句

while True:    passelse:    pass#else语句可选,当while为False时,else语句被执行。 pass是空语句。复制代码
Copy after login

for 循环 for..in

for i in range(0, 5):    print (i)else:    pass# 打印0到4复制代码
Copy after login

注:当for循环结束后执行else语句;range(a, b)返回一个序列,从a开始到b为止,但不包括b,range默认步长为1,可以指定步长,range(0,10,2);

3.3 break语句

终止循环语句,如果从for或while中终止,任何对应循环的else将不执行。

3.4 continue语句

continue语句用来调过当前循环的剩余语句,然后继续下一轮循环。

下面就是 break 和 continue 主要的 区别:

  • break:跳出整个循环
  • continue:跳出本次循环,继续执行下一次循环

希望大家牢记。

4、函数

函数通过def定义。def关键字后跟函数的标识符名称,然后跟一对圆括号,括号之内可以包含一些变量名,该行以冒号结尾;接下来是一块语句,即函数体。

def sumOf(a, b):
    return a + b复制代码
Copy after login

4.1 函数形参

函数中的参数名称为‘形参’,调用函数时传递的值为‘实参’

4.2 局部变量

在函数内定义的变量与函数外具有相同名称的其他变量没有任何关系,即变量名称对于函数来说是局部的。这称为变量的作用域。

global语句, 为定义在函数外的变量赋值时使用global语句。

def func():
    global x
    print( "x is ", x)
    x = 1x = 3func()
print(x)#3#1 复制代码
Copy after login

4.3 默认参数

通过使用默认参数可以使函数的一些参数是‘可选的’。

def say(msg, times =  1):
    print(msg * times)

say("Runsen")
say("Runsen", 3)复制代码
Copy after login

注意:只有在形参表末尾的那些参数可以有默认参数值,即不能在声明函数形参的时候,先声明有默认值的形参而后声明没有默认值的形参,只是因为赋给形参的值是根据位置而赋值的。  

4.4 关键参数

如果某个函数有很多参数,而现在只想指定其中的部分,那么可以通过命名为这些参数赋值(称为‘关键参数’)。 优点:不必担心参数的顺序,使函数变的更加简单;假设其他参数都有默认值,可以只给我们想要的那些参数赋值。

def func(a, b=2, c=3):
    print ("a is %s, b is %s, c is %s") % (a, b, c)

func(1) #a is 1, b is 2, c is 3func(1, 5) #a is 1, b is 5, c is 3func(1, c = 10) #a is 1, b is 2, c is 10func(c = 20, a = 30) #a is 30, b is 2, c is 20复制代码
Copy after login

4.5 return 语句

 return语句用来从一个函数返回,即跳出函数。可从函数返回一个值。  没有返回值的return语句等价于return None。None表示没有任何东西的特殊类型。

4.5 文档字符串

__doc__ (文档字符串)

def func():
    &#39;&#39;&#39;This is self-defined function
	Do nothing
	&#39;&#39;&#39;
    passprint(func.__doc__)#This is self-defined function##Do nothing复制代码
Copy after login

5、模块

模块就是一个包含了所有你定义的函数和变量的文件,模块必须以.py为扩展名。模块可以从其他程序中‘输入’(import)以便利用它的功能。

在python程序中导入其他模块使用'import', 所导入的模块必须在sys.path所列的目录中,因为sys.path第一个字符串是空串''即当前目录,所以程序中可导入当前目录的模块。

5.1 字节编译的.pyc文件

导入模块比较费时,python做了优化,以便导入模块更快些。一种方法是创建字节编译的文件,这些文件以.pyc为扩展名。

pyc是一种二进制文件,是py文件经编译后产生的一种byte code,而且是跨平台的(平台无关)字节码,是有python虚拟机执行的,类似于

java或.net虚拟机的概念。pyc的内容,是跟python的版本相关的,不同版本编译后的pyc文件是不同的。

5.2 from .. import

如果想直接使用其他模块的变量或其他,而不加'模块名+.'前缀,可以使用from .. import。

例如想直接使用sys的argv,from sys import argv 或 from sys import *

5.3 模块的__name__

每个模块都有一个名称,py文件对应模块名默认为py文件名,也可在py文件中为__name__赋值;如果是__name__,说明这个模块被用户

(4) dir()函数

  • dir(sys)返回sys模块的名称列表;如果不提供参数,即dir(),则返回当前模块中定义名称列表。

(5) del

del -> 删除一个变量/名称,del之后,该变量就不能再使用。

6、数据结构

python有三种内建的数据结构:列表、元组和字典。

6.1 列表

   list是处理一组有序项目的数据结构,列表是可变的数据结构。列表的项目包含在方括号[]中,

eg: [1, 2, 3], 空列表[]。判断列表中是否包含某项可以使用in,

比如 l = [1, 2, 3]; print 1 in l; #True;

支持索引和切片操作;索引时若超出范围,则IndexError;

使用函数len()查看长度;使用del可以删除列表中的项,eg: del l[0] # 如果超出范围,则IndexError      list函数如下:

append(value)  ---向列表尾添加项value
l = [1, 2, 2]
l.append(3) #[1, 2, 2, 3]count(value)  ---返回列表中值为value的项的个数
l = [1, 2, 2]
print( l.count(2)) # 2extend(list2)  ---向列表尾添加列表list2
l = [1, 2, 2]
l1 = [10, 20]
l.extend(l1)print (l )  #[1, 2, 2, 10, 20]index(value, [start, [stop]])  ---返回列表中第一个出现的值为value的索引,如果没有,则异常 ValueError

l = [1, 2, 2]
a = 4try:
    print( l.index(a))except ValueError, ve:
    print( "there is no %d in list" % a
    insert(i, value))  ---向列表i位置插入项vlaue,如果没有i,则添加到列表尾部

l = [1, 2, 2]

l.insert(1, 100)print l #[1, 100, 2, 2]l.insert(100, 1000)print l #[1, 100, 2, 2, 1000]pop([i])  ---返回i位置项,并从列表中删除;如果不提供参数,则删除最后一个项;如果提供,但是i超出索引范围,则异常IndexError

l = [0, 1, 2, 3, 4, 5]

print( l.pop()) # 5print( l) #[0, 1, 2, 3, 4]print( l.pop(1)) #1print( l) #[0, 2, 3, 4]try:
    l.pop(100)except IndexError, ie:
    print( "index out of range")

remove(value)  ---删除列表中第一次出现的value,如果列表中没有vlaue,则异常ValueError

l = [1, 2, 3, 1, 2, 3]

l.remove(2)print (l )#[1, 3, 1, 2, 3]try:
    l.remove(10)except ValueError, ve:    print ("there is no 10 in list")

reverse()  ---列表反转

l = [1, 2, 3]
l.reverse()print (l) #[3, 2, 1]sort(cmp=None, key=None, reverse=False)  ---列表排序

l5 = [10, 5, 20, 1, 30]
l5.sort()
print( l5) #[1, 5, 10, 20, 30]l6 = ["bcd", "abc", "cde", "bbb"]
l6.sort(cmp = lambda s1, s2: cmp(s1[0],s2[1]))
print( l6) #['abc', 'bbb', 'bcd', 'cde']l7 = ["bcd", "abc", "cde", "bbb", "faf"]
l7.sort(key = lambda s: s[1])print (l7) #['faf', 'abc', 'bbb', 'bcd', 'cde']复制代码
Copy after login

相关免费学习推荐:python视频教程

##<,<=,>,> =,!=,==
`
##& Bitwise AND
<<,>> Shift
Index
Bitwise flip
Attribute reference
Subscript
Addressing segment
Function call
Binding or tuple Display
List display

The above is the detailed content of The first Python knowledge points compiled for beginners. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.im
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!