


A brief summary of judgment statements and loop statements in Python (with examples)
This article brings you a simple summary of judgment statements and loop statements in Python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Today I will mainly introduce if judgment and loop control in Python.
Originally the title I wrote before was "Python's flow control", but after thinking about it, I realized that flow control is not limited to conditional judgment and loop control. So I changed it honestly...aha
1. If conditional judgment
1. Grammar form
if conditions The judgment syntax form is as follows. The corresponding execution operation is determined based on the conditional judgment of each branch.
if <条件判断-1>: <操作-1> elif <条件判断-2>: <操作-2> elif <条件判断-3>: <操作-3> else: <操作-4>
if branch: If
is judged to be true, then go to the execution of , otherwise go to the elif statement at; elif: is the abbreviation of "else if". elif statements can exist, or there can be one or more. When entering this branch, if the judgment
is true, then execute , otherwise, go to the next elif statement or else statement. ##else: When all the above if and elif branches are completed, if they are all judged to be false, then finally enter the else branch and perform
.
2. A special formif judgment also has a special form. As follows.
It determines whether to execute based on the value of x. Among them, when x is a non-zero value, a non-empty string, a non-empty list, etc., it is judged to be True, and the execution is transferred to if x :
<actions>
2. The for loop
When I introduced the data types before, I introduced this part, so let’s briefly summarize it! is as follows:
for x in 可迭代序列: <actions>
- This loop statement uses x as a temporary variable to iterate out each element in the iterable object (string, list, tuple, etc.) in turn.
the_count = [1,2,3,4,5] # %d fruits = ['apples','oranges','pears','apricots'] # %s change = [1,'pennies',2,'dimes',3,'quarters'] # mixed list:%r for number in the_count: print("this is count %d " % number) for fruit in fruits: print("a fruit of type : %s " % fruit) # mixed lists : notice we have to use %r since we don't know what's in it for i in change: # %r print("i got %r " % i)
- ##enumerate()
Will The index and value of the sequence are retrieved. Let’s go straight to the example~
>>> l = ['a','b','c'] >>> for ind ,val in enumerate(l): print("%d %s" %(ind,val)) ... 0 a 1 b 2 c
Copy after login
- sorted( )
Form: sorted([sequence], key=function, reverse =True or False) Parsing: Receive a sequence and sort it. You can also sort based on the specified key form. The parameter reverse is the direction sorting, which takes effect when True.
For example:# 对list进行排序。 >>> sorted([36,5,-12,9,-21]) [-21, -12, 5, 9, 36] # 高阶函数 # 可以接收一个key函数来实现自定义的排序,例如,按照绝对值大小排序: >>> sorted([36,5,-12,9,-21],key=abs) [5, 9, -12, -21, 36] # 对字符串进行排序,默认情况下是按照首字母的ASCII的大小进行排序。 >>> sorted( ['bob','about','Zoo','Credit'] ) ['Credit', 'Zoo', 'about', 'bob'] # 忽略大小写的排序:(全部换成小写) >>> sorted( ['bob','about','Zoo','Credit'] ,key=str.lower) ['about', 'bob', 'Credit', 'Zoo'] # 忽略大小写,且进行方向排序: >>> sorted( ['bob','about','Zoo','Credit'] ,key=str.lower,reverse= True) ['Zoo', 'Credit', 'bob', 'about']
Copy after login
- Grammar form:
while <expression>: <actions>
Copy after login
- Analysis: As long as the condition
- For example:
i = 0 numbers = [] while i < 6 : print("at the top i is %d " % i) numbers.append(i) i = i + 1 print("numbers now : ",numbers) print("at the bottom i is %d " %i) # 当i=6时 退出循环 print("the numbers: ")
break keyword, its function is to exit the current layer loop early.
For example:while x<10 : if <判断-1>: #例如 x==3 break x + = 1
- When
The continue keyword is used to skip the loop immediately through the continue statement during the loop. , return to the top of the loop and start the next loop directly.
For example:while x<10 : if <判断-1>: #例如 x==3 break print(x) x + = 1
Related recommendations: Conditional judgment and looping in PythonConditional judgment in Python Summary of usage of statements and loop statements
The above is the detailed content of A brief summary of judgment statements and loop statements in Python (with examples). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

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 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 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.

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.

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.

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".

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.
