Table of Contents
1 and, or, not
2 if, elif, else
3 for, while
4 True, False
5 continue、break
6 pass
7 try, except, finally, raise
8 import、from、as
9 def、return
10 class
11 lambda
12 del
13 global、nonlocal
14 in、is
15 None
16 assert
17 with
18 yield
Home Backend Development Python Tutorial Detailed analysis of Python keywords

Detailed analysis of Python keywords

Mar 22, 2022 pm 05:52 PM
python

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="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/067/fe1421fd000ace756583a0e389d5c9c7-2.png" class="lazy" 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="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/067/fe1421fd000ace756583a0e389d5c9c7-5.png" class="lazy" alt="Detailed analysis of Python keywords"></p><h2 id="True-False">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="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/067/33a9dc96ec9650f787ea254e66c73254-8.png" class="lazy" 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="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/067/33a9dc96ec9650f787ea254e66c73254-9.png" class="lazy" alt="Detailed analysis of Python keywords"></p><h2 id="pass">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="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/067/33a9dc96ec9650f787ea254e66c73254-10.png" class="lazy" alt="Detailed analysis of Python keywords"></p><h2 id="try-except-finally-raise">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="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/067/dcff06d9f769f18601bb11c4301d30c1-12.png" class="lazy" alt="Detailed analysis of Python keywords"></p><h2 id="import-from-as">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!

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles