Home Backend Development Python Tutorial Six aspects to explain Python's code structure

Six aspects to explain Python's code structure

Apr 03, 2018 am 10:39 AM
python code

This article mainly introduces six aspects to explain the code structure of Python. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor and take a look.

1. Comment

Use # or triple quotation marks to comment.


2. Connect

Use reverse Slash\ connection.

>>> alphabet = 'abcdefg' + \ 
...                         'hijklmnop' + \ 
...                         'qrstuv' + \ 
...                         'wxyz'
Copy after login

On the premise that Python expressions occupy many lines, line connectors are also necessary.

>>> 1 + 2 + \
... 3
6
Copy after login


3. if, elif and else

Common operations Symbols:

Arithmetic operators:

Comparison operators:

Assignment operators:

Logical operators:

Membership operators:

Identity operators:

Bitwise operators:

*Bitwise negation operation rules (bitwise negation plus 1) Detailed explanationhttp://blog.csdn .net/wenxinwukui234/article/details/42119265

Operator priority:

input() input is a string;

Conversion between string and integer type————int() str()

Short-circuit principle:

and When the first one is false, the following will not be judged Yes, it will be false directly;

or If the first one is true, the second one will not be judged, and it will be true directly.

will be considered False:

# #Empty tuple()##Empty dictionaryEmpty set



四、使用while进行循环

使用if、elif和else条件判断的例子是自顶向下执行的,但是有时候我们需要重复一些操作——循环。

>>> count = 1
>>> while count <= 5:
...     print(count)
...     count += 1
...
1
2
3
4
5
Copy after login

使用break跳出循环

>>> while True:
...     stuff = input("String to capitalize [type q to quit]:")
...     if stuff == &#39;q&#39;:
...             break
...     print(stuff.capitalize())
...
String to capitalize [type q to quit]:test
Test
String to capitalize [type q to quit]:darren chen
Darren chen
String to capitalize [type q to quit]:q
Copy after login

使用continue调到循环开始

while True:
    value = input(&#39;Integer ,please [q to quit]:&#39;)
    if value == &#39;q&#39;:
        break
    number = int(value)
    if number % 2 == 0:
        continue
    print(number,&#39;squared is&#39;,number*number)
    
Integer ,please [q to quit]:>? 1
1 squared is 1
Integer ,please [q to quit]:>? 2
Integer ,please [q to quit]:>? 3
3 squared is 9
Integer ,please [q to quit]:>? 5
5 squared is 25
Integer ,please [q to quit]:>? 6
Integer ,please [q to quit]:>? q
Copy after login

循环外使用else:

当while循环正常结束(没有使用break跳出),程序将进入到可选的else段 。

numbers = [1,3,5]
position = 0
while position < len(numbers):
    number = numbers[position]
    if number % 2 == 0:
        print(&#39;Found even number&#39;,number)
        break
    position += 1
else:
    print(&#39;No even number found&#39;)
...No even number found
Copy after login



五、使用for迭代

表、字符串、元组、字典、集合等都是Python中可迭代的对象。元组或列表在一次迭代过程中产生一项,而字符串迭代会产生一个字符。

word = &#39;Darren Chen&#39;
for i in word:
    print(i)
    
D
a
r
r
e
n
C
h
e
n
Copy after login

对一个字典(或字典的key()函数)迭代将返回字典中的键

home = {"man":&#39;chenda&#39;,&#39;woman&#39;:&#39;lvpeipei&#39;}
for i in home:
    print(i)
    
man
woman
Copy after login

想对值迭代,可以使用字典的values()

>>> for value in accusation. values(): 
...         print( value) 
...     
ballroom 
lead pipe
Copy after login

同while一样,可以使用break跳出循环,使用continue调到循环开始。

循环外使用else:

>>> cheeses = [] 
>>> for cheese in cheeses: 
...             print(&#39; This shop has some lovely&#39;, cheese) 
...             break 
...      else: # 没有 break 表示 没有 找到 奶酪 .
..              print(&#39; This is not much of a cheese shop, is it?&#39;) 
... 
This is not much of a cheese shop, is it?
Copy after login

使用zip()对多个序列进行并行迭代:

>>> days = [&#39;Monday&#39;, &#39;Tuesday&#39;, &#39;Wednesday&#39;] 
>>> fruits = [&#39;banana&#39;, &#39;orange&#39;, &#39;peach&#39;] 
>>> drinks = [&#39;coffee&#39;, &#39;tea&#39;, &#39;beer&#39;] 
>>> desserts = [&#39;tiramisu&#39;, &#39;ice cream&#39;, &#39;pie&#39;, &#39;pudding&#39;] 
>>> for day, fruit, drink, dessert in zip( days, fruits, drinks, desserts): 
...         print( day, ": drink", drink, "- eat", fruit, "- enjoy", dessert) 
... 
Monday : drink coffee - eat banana - enjoy tiramisu 
Tuesday : drink tea - eat orange - enjoy ice cream 
Wednesday : drink beer - eat peach - enjoy pie
Copy after login

使用zip()函数配对两个元组。函数的返回值既不是元组也不是列表,而是一个整合在一起的可迭代变量:

>>> english = &#39;Monday&#39;, &#39;Tuesday&#39;, &#39;Wednesday&#39; 
>>> french = &#39;Lundi&#39;, &#39;Mardi&#39;, &#39;Mercredi&#39;
>>> list( zip( english, french) ) 
[(&#39;Monday&#39;, &#39;Lundi&#39;), (&#39;Tuesday&#39;, &#39;Mardi&#39;), (&#39;Wednesday&#39;, &#39;Mercredi&#39;)]
#配合dict()函数和zip()函数的返回值就可以得到一本微型的词典:
>>> dict( zip( english, french) ) 
{&#39;Monday&#39;: &#39;Lundi&#39;, &#39;Tuesday&#39;: &#39;Mardi&#39;, &#39;Wednesday&#39;: &#39;Mercredi&#39;}
Copy after login

使用range()生成自然数序列

>>> for x in range( 0, 3): 
...         print( x) 
... 
0 
1 
2
>>> list( range( 0, 11, 2) ) 
[0, 2, 4, 6, 8, 10]
Copy after login


六、推导式

推导式是从一个或者多个迭代器快速简介地创建数据结构的一种方法。

列表推导式

>>> number_ list = list( range( 1, 6)) 
>>> number_ list 
[1, 2, 3, 4, 5]
>>> number_ list = [number for number in range( 1, 6)] 
>>> number_ list 
[1, 2, 3, 4, 5]
>>> number_ list = [number- 1 for number in range( 1, 6)] 
>>> number_ list 
[0, 1, 2, 3, 4]
>>> a_ list = [number for number in range( 1, 6) if number % 2 == 1] 
>>> a_ list
[1,3,5]
#嵌套循环
>>> rows = range( 1, 4) 
>>> cols = range( 1, 3) 
>>> cells = [(row, col) for row in rows for col in cols] 
>>> for cell in cells: 
...         print( cell) 
... 
(1, 1) 
(1, 2) 
(2, 1) 
(2, 2) 
(3, 1) 
(3, 2)
Copy after login

字典推导式

{ key_ expression : value_ expression for expression in iterable }
>>> word = &#39;letters&#39; 
>>> letter_ counts = {letter: word. count( letter) for letter in set( word)} 
>>> letter_ counts 
{&#39;t&#39;: 2, &#39;l&#39;: 1, &#39;e&#39;: 2, &#39;r&#39;: 1, &#39;s&#39;: 1}
Copy after login

集合推导式

>>> a_ set = {number for number in range( 1, 6) if number % 3 == 1} 
>>> a_ set 
{1, 4}
Copy after login

生成器推导式——元组是没有推导式的,其实,圆括号之间的是生成器推导式,它返回的是一个生成器对象。

>>> number_ thing = (number for number in range( 1, 6))
>>> type( number_ thing) 
< class &#39;generotor&#39;>
#可以直接对生成器对象进行迭代
>>> for number in number_ thing: 
...             print( number) 
... 
1 
2 
3 
4 
5
Copy after login

#通过对一个生成器的推导式调用list()函数,使它类似于列表推导式

>>> number_ list = list( number_ thing) 
>>> number_ list 
[1, 2, 3, 4, 5]
    一个生成器只能运行一
Copy after login

次。列表、集合、字符串和字典都存储在内存中,但是生成器仅在运行中产生值,不会被存下来,所以不能重新使用或者备份一个生成器。

如果想再一次迭代此生成器,会发现它被擦除了:

>>> try_ again = list( number_ thing) 
>>> try_ again 
[ ]
Copy after login

The above is the detailed content of Six aspects to explain Python's code structure. 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
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
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)

Is the conversion speed fast when converting XML to PDF on mobile phone? Is the conversion speed fast when converting XML to PDF on mobile phone? Apr 02, 2025 pm 10:09 PM

The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

How to convert XML files to PDF on your phone? How to convert XML files to PDF on your phone? Apr 02, 2025 pm 10:12 PM

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

Is there a mobile app that can convert XML into PDF? Is there a mobile app that can convert XML into PDF? Apr 02, 2025 pm 09:45 PM

There is no APP that can convert all XML files into PDFs because the XML structure is flexible and diverse. The core of XML to PDF is to convert the data structure into a page layout, which requires parsing XML and generating PDF. Common methods include parsing XML using Python libraries such as ElementTree and generating PDFs using ReportLab library. For complex XML, it may be necessary to use XSLT transformation structures. When optimizing performance, consider using multithreaded or multiprocesses and select the appropriate library.

Recommended XML formatting tool Recommended XML formatting tool Apr 02, 2025 pm 09:03 PM

XML formatting tools can type code according to rules to improve readability and understanding. When selecting a tool, pay attention to customization capabilities, handling of special circumstances, performance and ease of use. Commonly used tool types include online tools, IDE plug-ins, and command-line tools.

How to convert XML to PDF on your phone? How to convert XML to PDF on your phone? Apr 02, 2025 pm 10:18 PM

It is not easy to convert XML to PDF directly on your phone, but it can be achieved with the help of cloud services. It is recommended to use a lightweight mobile app to upload XML files and receive generated PDFs, and convert them with cloud APIs. Cloud APIs use serverless computing services, and choosing the right platform is crucial. Complexity, error handling, security, and optimization strategies need to be considered when handling XML parsing and PDF generation. The entire process requires the front-end app and the back-end API to work together, and it requires some understanding of a variety of technologies.

How to open xml format How to open xml format Apr 02, 2025 pm 09:00 PM

Use most text editors to open XML files; if you need a more intuitive tree display, you can use an XML editor, such as Oxygen XML Editor or XMLSpy; if you process XML data in a program, you need to use a programming language (such as Python) and XML libraries (such as xml.etree.ElementTree) to parse.

How to convert xml into pictures How to convert xml into pictures Apr 03, 2025 am 07:39 AM

XML can be converted to images by using an XSLT converter or image library. XSLT Converter: Use an XSLT processor and stylesheet to convert XML to images. Image Library: Use libraries such as PIL or ImageMagick to create images from XML data, such as drawing shapes and text.

See all articles
## Boolean

False

null type

None

Integer

0

Floating point Type

0.0

Empty string

''

Empty list

[]

{}

set()