搜尋
首頁後端開發Python教學掌握條件語句和循環的藝術日

Day Mastering the Art of Conditional Statements and Loops

條件語句

與其他程式語言一樣,Python 也包含條件語句。但唯一的差別是,我們有 elif,而不是 else if
條件語句根據特定條件控製程式的流程。它們透過允許程式根據條件評估為 True 或 False 執行不同的程式碼區塊來實現決策。
我們不再單獨解釋ifelifelse

else
if a%2==0:
   print("The Number is an Even Composite")
elif not_prime(a):
   print("The Number is an Odd Composite")
else:
   print("The Number is a Prime")



else
else 🎜> 讓我們來介紹它們所有這些都在一個例子中。 這裡,讓數字為 3。 首先程式會檢查數字是否能被2整除(如果a%2==0) 因為它不是偶數,所以它轉到 elif 語句(if not_prime(a)) 由於
if

elif

都不為true,因此程式將轉到
age=19
if age>18 and age<h4 id="else">else</h4><p><br> 部分,它將列印:</p>
<pre class="brush:php;toolbar:false">age = 20
if age >= 18:
    if age 這個數字是素數<h4></h4>
<pre class="brush:php;toolbar:false">bob_score=87
alen_score=92
answer=bob_score if bob_score>alen_score else alen_score
print(answer)
主要特點:

1. 條件邏輯運算符

2. 巢狀條件語句

您可以將條件語句嵌套在一起以評估複雜的條件。

    3. 三元條件語句
  • 答案:
    92

  • ?今日絕招:
  • startswith() 和endswith()
  • startswith()和endswith()是傳回字串的方法 如果指定的字串以指定的開頭或結尾,則為 True 值。

    假設您要傳回清單中以
  • 開頭的所有名稱 「一。」
listl = ['lemon','Orange','apple', 'apricot']
new_list = [i for i in listl if i.startswith('a')]
pri nt(new_li st)

以下是如何使用startswith()來實現這一點。

  • 使用startswith():
listl = ['lemon','Orange','apple', 'apricot']
new_list = [i for i in listl if i.endswith('e')]]
pri nt(new_li st)

答案:

['蘋果', '杏子']

使用 endwith():

答案:

['蘋果', '柳橙']

循環

除了決策語句之外,Python程式設計也支援循環語句。有
a=[1,2,3,4]
for i in a:
   print(a)

1。同時

2.對於
1.For循環:

Python 中的 for 迴圈迭代序列(例如清單、元組、字串或範圍)並對該序列中的每個項目執行操作。

答案: 0n 1n 2n 3n 4n 這裡,for 迴圈迭代列表 a 中的所有元素並列印它們。 使用 range() 和 for: 您可以使用 range() 函數產生數字序列。
if a%2==0:
   print("The Number is an Even Composite")
elif not_prime(a):
   print("The Number is an Odd Composite")
else:
   print("The Number is a Prime")

答案: 0n 1 n 2n 3n

範圍():
range() 函數的基本語法是:

age=19
if age>18 and age



<p>這裡預設start=0,step=1。 <br>
</p>

<pre class="brush:php;toolbar:false">age = 20
if age >= 18:
    if age 



<p><strong>答案:1n 2n</strong><br>
          <strong>1n 3n</strong></p>
<h3>
  
  
  while 迴圈:
</h3>

<p>只要條件計算結果為 True,while 迴圈就會繼續執行程式碼區塊。 <br>
</p>

<pre class="brush:php;toolbar:false">bob_score=87
alen_score=92
answer=bob_score if bob_score>alen_score else alen_score
print(answer)

答案: 4n 3n 2n 1n

1.break語句

break 語句用於提前終止循環,無論其條件為何。一旦執行了break語句,控制就退出迴圈。

listl = ['lemon','Orange','apple', 'apricot']
new_list = [i for i in listl if i.startswith('a')]
pri nt(new_li st)

答案: 10n 9n 8n 7n 6n

2.繼續語句

continue 語句用於跳過目前迭代中的其餘程式碼並繼續循環的下一個迭代。

listl = ['lemon','Orange','apple', 'apricot']
new_list = [i for i in listl if i.endswith('e')]]
pri nt(new_li st)

答案: 1n 3n 5n 7n 9n

3.透過聲明

pass 語句是一個佔位符,當語法上需要一段程式碼但您不想執行任何程式碼時使用。它實際上什麼也沒做。

a=[1,2,3,4]
for i in a:
   print(a)

答案: 0n 1n 2n 4n

以上是掌握條件語句和循環的藝術日的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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

toAppendElementStoApythonList,usetheappend()方法forsingleements,Extend()formultiplelements,andinsert()forspecificpositions.1)useeAppend()foraddingoneOnelementAttheend.2)useextendTheEnd.2)useextendexendExendEnd(

您如何創建Python列表?舉一個例子。您如何創建Python列表?舉一個例子。May 04, 2025 am 12:16 AM

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

討論有效存儲和數值數據的處理至關重要的實際用例。討論有效存儲和數值數據的處理至關重要的實際用例。May 04, 2025 am 12:11 AM

金融、科研、医疗和AI等领域中,高效存储和处理数值数据至关重要。1)在金融中,使用内存映射文件和NumPy库可显著提升数据处理速度。2)科研领域,HDF5文件优化数据存储和检索。3)医疗中,数据库优化技术如索引和分区提高数据查询性能。4)AI中,数据分片和分布式训练加速模型训练。通过选择适当的工具和技术,并权衡存储与处理速度之间的trade-off,可以显著提升系统性能和可扩展性。

您如何創建Python數組?舉一個例子。您如何創建Python數組?舉一個例子。May 04, 2025 am 12:10 AM

pythonarraysarecreatedusiseThearrayModule,notbuilt-Inlikelists.1)importThearrayModule.2)指定tefifythetypecode,例如,'i'forineizewithvalues.arreaysofferbettermemoremorefferbettermemoryfforhomogeNogeNogeNogeNogeNogeNogeNATATABUTESFELLESSFRESSIFERSTEMIFICETISTHANANLISTS。

使用Shebang系列指定Python解釋器有哪些替代方法?使用Shebang系列指定Python解釋器有哪些替代方法?May 04, 2025 am 12:07 AM

除了shebang線,還有多種方法可以指定Python解釋器:1.直接使用命令行中的python命令;2.使用批處理文件或shell腳本;3.使用構建工具如Make或CMake;4.使用任務運行器如Invoke。每個方法都有其優缺點,選擇適合項目需求的方法很重要。

列表和陣列之間的選擇如何影響涉及大型數據集的Python應用程序的整體性能?列表和陣列之間的選擇如何影響涉及大型數據集的Python應用程序的整體性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

說明如何將內存分配給Python中的列表與數組。說明如何將內存分配給Python中的列表與數組。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python數組中指定元素的數據類型?您如何在Python數組中指定元素的數據類型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

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

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

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

EditPlus 中文破解版

EditPlus 中文破解版

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。