搜尋
首頁後端開發Python教學六個方面詮釋Python的程式碼結構

六個方面詮釋Python的程式碼結構

Apr 03, 2018 am 10:39 AM
python程式碼

這篇文章主要介紹了六個面向詮釋Python的程式碼結構,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟著小編過來看看吧

一、註解

使用#或三引號註解。


#二、連接

使用反斜線\ 連接。

>>> alphabet = 'abcdefg' + \ 
...                         'hijklmnop' + \ 
...                         'qrstuv' + \ 
...                         'wxyz'

在Python表達式佔行很多的前提下,行連接符也是必須的。

>>> 1 + 2 + \
... 3
6


三、if、elif和else

常見的運算符:

算數運算子:

比較運算子:

賦值運算子:

邏輯運算子:

成員運算子:

身分運算子:

位元運算子:

*按位取反運算規則(位元取反再加1)   詳解http://blog.csdn .net/wenxinwukui234/article/details/42119265

運算子優先權:

#input()輸入的是字串;

字串與整數型之間的轉換--int()  str()

短路原則:

    and 第一個為假時就不會判斷後面的了,直接為false;

    or 第一個為真就不去判斷第二個了,直接為true。

會被認為是False的情況:

浮點型#空白字串 空列表空元組#空白字典空集合

布林

False

#null型別

##None

整數

0

0

0.0

''

[]

()

{}

#######set()############# ##



四、使用while进行循环

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

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

使用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

使用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

循环外使用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



五、使用for迭代

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

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

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

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

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

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

同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?

使用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

使用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;}

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

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


六、推导式

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

列表推导式

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

字典推导式

{ 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}

集合推导式

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

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

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

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

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

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

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

>>> try_ again = list( number_ thing) 
>>> try_ again 
[ ]

以上是六個方面詮釋Python的程式碼結構的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy陣列上可以執行哪些常見操作?在Numpy陣列上可以執行哪些常見操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的數據分析中如何使用陣列?Python的數據分析中如何使用陣列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

列表的內存足跡與python數組的內存足跡相比如何?列表的內存足跡與python數組的內存足跡相比如何?May 02, 2025 am 12:08 AM

列表sandnumpyArraysInpythonHavedIfferentMemoryfootprints:listSaremoreFlexibleButlessMemory-效率,而alenumpyArraySareSareOptimizedFornumericalData.1)listsStorReereReereReereReereFerenceStoObjects,with withOverHeadeBheadaroundAroundaround64byty64-bitsysysysysysysysysyssyssyssyssysssyssys2)

部署可執行的Python腳本時,如何處理特定環境的配置?部署可執行的Python腳本時,如何處理特定環境的配置?May 02, 2025 am 12:07 AM

toensurepythonscriptsbehavecorrectlyacrycrosdevelvermations,分期和生產,USETHESTERTATE:1)Environment varriablesForsimplesettings,2)configurationfilesfilesForcomPlexSetups,3)dynamiCofforComplexSetups,dynamiqualloadingForaptaptibality.eachmethodoffersuniquebeneiquebeneqeniquebenefitsandrefitsandrequiresandrequiresandrequiresca

您如何切成python陣列?您如何切成python陣列?May 01, 2025 am 12:18 AM

Python列表切片的基本語法是list[start:stop:step]。 1.start是包含的第一個元素索引,2.stop是排除的第一個元素索引,3.step決定元素之間的步長。切片不僅用於提取數據,還可以修改和反轉列表。

在什麼情況下,列表的表現比數組表現更好?在什麼情況下,列表的表現比數組表現更好?May 01, 2025 am 12:06 AM

ListSoutPerformarRaysin:1)DynamicsizicsizingandFrequentInsertions/刪除,2)儲存的二聚體和3)MemoryFeliceFiceForceforseforsparsedata,butmayhaveslightperformancecostsinclentoperations。

如何將Python數組轉換為Python列表?如何將Python數組轉換為Python列表?May 01, 2025 am 12:05 AM

toConvertapythonarraytoalist,usEthelist()constructororageneratorexpression.1)intimpthearraymoduleandcreateanArray.2)USELIST(ARR)或[XFORXINARR] to ConconverTittoalist,請考慮performorefformanceandmemoryfformanceandmemoryfformienceforlargedAtasetset。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器