搜尋
首頁後端開發Python教學決策與重複循環:初學者的基本指南

Laços de Decisão e Repetição: O Guia Essencial para Iniciantes

程式設計本質上是教導電腦做出決定並重複操作。這是透過控制結構來完成的,控制結構是任何程式語言的基礎。在本文中,我們將透過實際範例探討決策循環重複循環的主要概念。

決策循環

決策循環,也稱為條件結構,允許程式根據某些條件選擇不同的路徑。這裡的主要概念是檢查條件是真是假。

如果,否則如果,否則

最常見的條件結構是 if。它檢查一個條件;如果為 true,則執行一段程式碼。否則,您可以跟隨 else if 或 else 來測試其他條件或提供替代方案。

Python 例:

idade = 18

if idade >= 18:
    print("Você é maior de idade.")
elif idade > 12:
    print("Você é adolescente.")
else:
    print("Você é criança.")

開關/外殼(或匹配)

在某些語言中,例如 JavaScript 或 C,switch/case 允許比多個 if/else 更有效地檢查多個條件。

JavaScript 範例:

let cor = "verde";

switch (cor) {
    case "vermelho":
        console.log("Pare!");
        break;
    case "amarelo":
        console.log("Atenção!");
        break;
    case "verde":
        console.log("Siga em frente!");
        break;
    default:
        console.log("Cor desconhecida.");
}

三元

在Python、JavaScript和Java等語言中,我們可以使用三元運算子在一行中做出簡單的決定。

Python 例:

idade = 18
print("Maior de idade" if idade >= 18 else "Menor de idade")

重複循環

重複循環用於多次執行一段程式碼。最常見的結構是 for、while 和 do-while。

為了

For 用於當我們事先知道一段程式碼必須重複的次數。它對於迭代列表、陣列和序列非常有用。

Python 例:

for i in range(5):
    print(f"Este é o loop número {i + 1}")

JavaScript 範例:

const frutas = ["Maçã", "Banana", "Laranja"];
for (let i = 0; i 



<h3>
  
  
  儘管
</h3>

<p>只要條件為真,While 就會重複一段程式碼。當我們事先不知道確切的重複次數時,就會使用這種類型的循環。 </p>

<p><strong>Python 例:</strong><br>
</p>

<pre class="brush:php;toolbar:false">contador = 0
while contador 



<h3>
  
  
  邊做邊做
</h3>

<p>Do-while 與 while 類似,但它保證區塊內的程式碼至少執行一次,即使條件從一開始就是 false。 </p>

<p><strong>JavaScript 範例:</strong><br>
</p>

<pre class="brush:php;toolbar:false">let contador = 0;
do {
    console.log(`Contagem: ${contador}`);
    contador++;
} while (contador 




<hr>

<h2>
  
  
  循環中的流量控制
</h2>

<p>除了做出決策和重複操作之外,通常還需要控制循環內的流程,例如中斷或跳過迭代。 </p>

<h3>
  
  
  休息
</h3>

<p>break 關鍵字立即中斷循環,跳過任何未來的迭代。 </p>

<p><strong>Python 例:</strong><br>
</p>

<pre class="brush:php;toolbar:false">for i in range(10):
    if i == 5:
        break
    print(i)

輸出:

0
1
2
3
4

繼續

continue 關鍵字跳到迴圈的下一個迭代,忽略目前迭代中的其餘程式碼。

Python 例:

for i in range(5):
    if i == 2:
        continue
    print(i)

輸出:

0
1
3
4

結論

決策和重複循環是任何程序的支柱。它們使我們能夠創建動態流,其中行為根據輸入和遇到的條件而變化。掌握這些概念對於成為一個高效的程式設計師至關重要,因為它們幾乎出現在您將編寫的每個程式碼中。

請記住針對每種情況選擇適當的結構,透過練習,您很快就能使用這些循環編寫乾淨且高效的程式碼。

以上是決策與重複循環:初學者的基本指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解釋嗎?揭穿神話Python:它是真正的解釋嗎?揭穿神話May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

與同一元素的Python串聯列表與同一元素的Python串聯列表May 11, 2025 am 12:08 AM

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

解釋與編譯語言:Python的位置解釋與編譯語言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循環時:您什麼時候在Python中使用?循環時:您什麼時候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

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

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

熱門文章

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具