Home > Backend Development > Python Tutorial > Detailed analysis of Python keywords

Detailed analysis of Python keywords

WBOY
Release: 2022-03-22 17:52:00
forward
8598 people have browsed it

This article brings you relevant knowledge about python, which mainly introduces related issues about keywords. It analyzes Python’s keyword knowledge points in detail based on examples. I hope it will be useful to everyone. help.

Detailed analysis of Python keywords

Recommended learning: python detailed tutorial

1 and, or, not

and, or, not The keywords are all logical operators and are used as follows:

  • and: If both statements return True, the return value will be True only, otherwise it will return False.
  • or: If one of the statements returns True, the return value is True, otherwise it returns False.
  • not: If the statement is not True, the return value is True, otherwise it returns False.
x1 = (5 > 3 and 5  3 or 5 > 10)x2

x3 = Falsenot x3
Copy after login

The results are as follows:
Detailed analysis of Python keywords

2 if, elif, else

if, elif, else are mainly used for conditional statements. The usage is as follows :

  • if: Used to create conditional statements (if statements), and allows the if code block to be executed only when the condition is True.
  • elif: Used in conditional statements (if statements), it is the abbreviation of else if.
  • else: Used in conditional statements (if statements) and determines the code to be executed when the if condition is False.
def func(x):
    if x <p>The result is as follows: <br><img src="https://img.php.cn/upload/article/000/000/067/fe1421fd000ace756583a0e389d5c9c7-2.png" alt="Detailed analysis of Python keywords"><br> Among them, the else keyword is also used in the try...except block, please see the example below. </p><pre class="brush:php;toolbar:false">def func1(x):
    try:
        100//x    except:
        print("ZeropisionError: pision by zero(除数不能是0)")
    else:
        print(f"程序计算结果是{str(100//x)}")func1(10)func1(0)
Copy after login

The results are as follows:
Detailed analysis of Python keywords

3 for, while

for, while are mainly used to define a loop, the usage is as follows:

  • for: Used to create a for loop, which can be used to traverse sequences, such as lists, tuples, etc.
  • while: used to define a while loop, the while loop will continue until the condition of while is False.
name_list = ["张三","李四","王五"]for name in name_list:
    print(name)
Copy after login

The results are as follows:
Detailed analysis of Python keywords

x = 0while x<p>The results are as follows: <br><img src="https://img.php.cn/upload/article/000/000/067/fe1421fd000ace756583a0e389d5c9c7-5.png" alt="Detailed analysis of Python keywords"></p><h2>4 True, False</h2><p>True and False are the results returned by the comparison operation. The usage is as follows: </p>
Copy after login
  • True: The keyword True is the same as 1.
  • False: The keyword False is the same as 0.
print(9 > 6)print(6 in [11,6,33])print(5 is 5)print(5 == 5)print(5 == 5 and 7 == 7)print(5 == 5 or 6 == 7)print(not(5 == 7))
Copy after login

The results are as follows:
Detailed analysis of Python keywords

print(9 = 7)print(not(5 == 5))
Copy after login

The results are as follows:
Detailed analysis of Python keywords

5 continue、break

continue and break are mainly used in for loops and while loops. The usage is as follows:

  • continue: The continue keyword is used to end the current iteration in the for loop (or while loop) and continue to the next an iteration.
  • break: The break keyword is used to interrupt a for loop or while loop.
for i in range(10):
    if i <p>The results are as follows: <br><img src="https://img.php.cn/upload/article/000/000/067/33a9dc96ec9650f787ea254e66c73254-8.png" alt="Detailed analysis of Python keywords"></p><pre class="brush:php;toolbar:false">x = 0while x <p>The results are as follows: <br><img src="https://img.php.cn/upload/article/000/000/067/33a9dc96ec9650f787ea254e66c73254-9.png" alt="Detailed analysis of Python keywords"></p><h2>6 pass</h2><p>pass Statements serve as placeholders for future code. When the pass statement is executed, it will not have any effect. It is just a placeholder that represents blank code. However, if you do not write anything, an error will be reported. If empty code is not allowed in loops, function definitions, class definitions or if statements, pass can be used. <br><img src="https://img.php.cn/upload/article/000/000/067/33a9dc96ec9650f787ea254e66c73254-10.png" alt="Detailed analysis of Python keywords"></p><h2>7 try, except, finally, raise</h2><p>try, except, finally, and raise are all keywords related to exceptions. The usage is as follows: </p>
Copy after login
  • try:在try…except块中使用,它定义了一个代码块,并在没有问题的情况下执行块。如果包含任何错误,可以为不同的错误类型定义不同的块。
  • except:在try… except块中使用。 如果try块引发错误,并在有问题的情况下执行对应的代码块。
  • finally:在try…except块中使用。它定义了一个代码块,当try…except…else块结束时,该代码块将运行。无论try块是否引发错误,都将执行finally代码块。
  • raise:raise关键字用于引发异常,可以定义引发哪种错误,以及向用户显示错误信息。
def func(x):
    try:
        100 // x    except:
        print("ZeropisionError: pision by zero(除数不能是0)")
    else:
        print(f"结果是:{str(100 // x)}")
    finally:
        print("无论如何,都会执行!")
        func(10)func(0)
Copy after login

结果如下:
Detailed analysis of Python keywords

x = 15if x <p>结果如下:<br><img src="https://img.php.cn/upload/article/000/000/067/dcff06d9f769f18601bb11c4301d30c1-12.png" alt="Detailed analysis of Python keywords"></p><h2>8 import、from、as</h2><p>import、from、as均与模块的导入有关,用法如下:</p>
Copy after login
  • import:用于导入模块。
  • from:用于从模块中导入指定的部分,按需要导入指定子类或函数,减少不必要的资源浪费。
  • as:用于创建别名。
import openpyxlimport pandas as pdfrom openpyxl import load_workbook()
Copy after login

9 def、return

def、return均与函数有关的关键字,用法如下:

  • def:用于创建(或定义)一个函数。
  • return:用于结束所定义的函数,并返回值。
def func1():
    print("关注公众号:数据分析与统计学之美")
    func1()
Copy after login

结果如下:
Detailed analysis of Python keywords

def func2(x,y):
    return x + y

func2(x=2,y=8)
Copy after login

结果如下:
Detailed analysis of Python keywords

10 class

class关键字用于创建(或定义)一个类。

class Person:
    name = "张三"
    age = 18
    p = Person()p.name,p.age
Copy after login

结果如下:
Detailed analysis of Python keywords

11 lambda

lambda关键字用于创建一个 “匿名函数”

x = lambda a: a + 8x(2)y = lambda a,b: a + b
y(1,1)z = lambda a,b,c: a * c + b
z(2,5,5)
Copy after login

结果如下:
Detailed analysis of Python keywords

12 del

在Python中,一切皆对象。del关键字主要用于删除对象,还可以用于删除变量,列表或列表的一部分等。

x = 1del xprint(x)
Copy after login

结果如下:
Detailed analysis of Python keywords

x = ["张三","李四","王五"]del x[0]print(x)
Copy after login

结果如下:
Detailed analysis of Python keywords

13 global、nonlocal

global关键字用于创建一个全局变量。nonlocal关键字用于声明一个非局部变量,用于标识外部作用域的变量。

# 定义一个函数:def func():
    global x
    x = "函数中的变量"# 执行函数:func()# x定义在函数中,按说这里打印x会报错,我们看看print(x)
Copy after login

结果如下:
Detailed analysis of Python keywords

14 in、is

in、is这两个关键字大家一定要区别开来,用法如下:

  • in:一方面可以用于检查序列(list,range,字符串等)中是否存在某个值。也可以用于遍历for循环中的序列。
  • is:用于判断两个变量是否是同一个对象,如果两个对象是同一对象,则返回True,否则返回False。要与== 区别开来,使用==运算符判断两个变量是否相等。
x = ["张三","李四","王五"]"张三" in x# -------------------------for i in range(3):
    print(i)
Copy after login

结果如下:
Detailed analysis of Python keywords

x = 2.0y = 2.0x is y
x == y
Copy after login

结果如下:
Detailed analysis of Python keywords

15 None

None关键字用于定义一个空值(根本没有值),与0,False或空字符串不同。 None是其自身的数据类型(NoneType),只能为None。

x = Noneprint(x)if x:
    print("嘻嘻")else:
    print("哈哈")
Copy after login

结果如下:
Detailed analysis of Python keywords

16 assert

调试代码时,使用assert关键字。主要用于测试代码中的条件是否为True,如果为False,将引发AssertionError。

x = 666assert x == 666assert x == 888,"x应该等于666,你的输入有误!"
Copy after login

结果如下:
Detailed analysis of Python keywords

17 with

with常和open使用,用于读取或写入文件。

with open("哈哈.txt","r") as f:
    print(f.read())
Copy after login

结果如下:
Detailed analysis of Python keywords

18 yield

yield关键字结束一个函数,返回一个生成器,用于从函数依次返回值。

def f():
    yield 5f()next(f())
Copy after login

结果如下:
Detailed analysis of Python keywords

推荐学习:python教程

The above is the detailed content of Detailed analysis of Python keywords. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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