{"id":722,"date":"2020-10-23T01:52:56","date_gmt":"2020-10-23T01:52:56","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=722"},"modified":"2025-03-31T03:53:36","modified_gmt":"2025-03-31T03:53:36","slug":"python-for-else","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/python-basics\/python-for-else\/","title":{"rendered":"Python for&#8230;else"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn about the Python <code>for...else<\/code> statement and how to use it effectively.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-the-python-for-else-statement'>Introduction to the Python for&#8230;else statement <a href=\"#introduction-to-the-python-for-else-statement\" class=\"anchor\" id=\"introduction-to-the-python-for-else-statement\" title=\"Anchor for Introduction to the Python for...else statement\">#<\/a><\/h2>\n\n\n\n<p>In Python, the <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-for-range\/\"><code>for<\/code> <\/a>statement can have an optional <code>else<\/code> clause, which you may not be familiar with especially if you&#8217;re coming from other languages such as Java or C#.<\/p>\n\n\n\n<p>The following shows the syntax of the <code>for<\/code> statement with the <code>else<\/code> clause:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-keyword\">for<\/span> item in iterables:\n    <span class=\"hljs-comment\"># Process item<\/span>\n    <span class=\"hljs-keyword\">if<\/span> condition:\n        <span class=\"hljs-keyword\">break<\/span>  <span class=\"hljs-comment\"># Terminate the loop prematurely<\/span>\n<span class=\"hljs-keyword\">else<\/span>:\n    <span class=\"hljs-comment\"># Executed if the loop completes without a break<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this syntax: <\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Python will execute the <code>else<\/code> block <strong>only if <\/strong>the <code>for<\/code> loop iterates all items in the <code>iterables<\/code> without hitting a <code>break <\/code>statement.<\/li>\n\n\n\n<li>If Python encounters a <code>break<\/code> statement, it&#8217;ll skip the <code>else<\/code> block entirely.<\/li>\n\n\n\n<li>If the <code>iterables<\/code> has no items, Python executes the <code>else<\/code> block <strong>immediately<\/strong>. <\/li>\n<\/ul>\n\n\n\n<p>Unlike the <code>break<\/code> statement, the <code><a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-continue\/\">continue<\/a><\/code> statement does not end the loop prematurely. Therefore, the else block will execute if the loop completes normarlly.<\/p>\n\n\n\n<p>The following flowchart illustrates logic of the <code>for...else<\/code> statement:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"469\" height=\"709\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/10\/python-for-else.png\" alt=\"\" class=\"wp-image-851\" srcset=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/10\/python-for-else.png 469w, https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/10\/python-for-else-198x300.png 198w\" sizes=\"auto, (max-width: 469px) 100vw, 469px\" \/><\/figure>\n<\/div>\n\n\n<p>The <code>else<\/code> clause is useful in some cases if you know how to apply it effectively.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='python-for-else-example'>Python for&#8230;else example <a href=\"#python-for-else-example\" class=\"anchor\" id=\"python-for-else-example\" title=\"Anchor for Python for...else example\">#<\/a><\/h2>\n\n\n\n<p>Suppose that you have a <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-list\/\">list<\/a> of people, where each person is a <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-dictionary\/\">dictionary<\/a> that consists of <code>name<\/code> and <code>age<\/code> like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">people = &#91;{<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'John'<\/span>, <span class=\"hljs-string\">'age'<\/span>: <span class=\"hljs-number\">25<\/span>},\n        {<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'Jane'<\/span>, <span class=\"hljs-string\">'age'<\/span>: <span class=\"hljs-number\">22<\/span>},\n        {<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'Peter'<\/span>, <span class=\"hljs-string\">'age'<\/span>: <span class=\"hljs-number\">30<\/span>},\n        {<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'Jenifer'<\/span>, <span class=\"hljs-string\">'age'<\/span>: <span class=\"hljs-number\">28<\/span>}]<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>And you want to search for a person by name.<\/p>\n\n\n\n<p>If the list contains the person, you want to display the information of that person. Otherwise, you want to show a message saying that the name is not found.<\/p>\n\n\n\n<p>To do it, you may come up with a program like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">people = &#91;{<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'John'<\/span>, <span class=\"hljs-string\">'age'<\/span>: <span class=\"hljs-number\">25<\/span>},\n        {<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'Jane'<\/span>, <span class=\"hljs-string\">'age'<\/span>: <span class=\"hljs-number\">22<\/span>},\n        {<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'Peter'<\/span>, <span class=\"hljs-string\">'age'<\/span>: <span class=\"hljs-number\">30<\/span>},\n        {<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'Jenifer'<\/span>, <span class=\"hljs-string\">'age'<\/span>: <span class=\"hljs-number\">28<\/span>}]\n\nname = <span class=\"hljs-string\">'Maria'<\/span>\n\nfound = <span class=\"hljs-keyword\">False<\/span>\n<span class=\"hljs-keyword\">for<\/span> person in people:\n    <span class=\"hljs-keyword\">if<\/span> person&#91;<span class=\"hljs-string\">'name'<\/span>] == name:\n        found = <span class=\"hljs-keyword\">True<\/span>\n        <span class=\"hljs-keyword\">print<\/span>(person)\n        <span class=\"hljs-keyword\">break<\/span>\n\n<span class=\"hljs-keyword\">if<\/span> not found:\n    <span class=\"hljs-keyword\">print<\/span>(f<span class=\"hljs-string\">'{name} not found!'<\/span>)\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=cGVvcGxlID0gW3snbmFtZSc6ICdKb2huJywgJ2FnZSc6IDI1fSwKICAgICAgICB7J25hbWUnOiAnSmFuZScsICdhZ2UnOiAyMn0sCiAgICAgICAgeyduYW1lJzogJ1BldGVyJywgJ2FnZSc6IDMwfSwKICAgICAgICB7J25hbWUnOiAnSmVuaWZlcicsICdhZ2UnOiAyOH1dCgpuYW1lID0gJ01hcmlhJwoKZm91bmQgPSBGYWxzZQpmb3IgcGVyc29uIGluIHBlb3BsZToKICAgIGlmIHBlcnNvblsnbmFtZSddID09IG5hbWU6CiAgICAgICAgZm91bmQgPSBUcnVlCiAgICAgICAgcHJpbnQocGVyc29uKQogICAgICAgIGJyZWFrCgppZiBub3QgZm91bmQ6CiAgICBwcmludChmJ3tuYW1lfSBub3QgZm91bmQhJyk\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">Maria not found!<\/code><\/span><\/pre>\n\n\n<p>How it works:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, initialize a variable with the name of person to search for (<code>Maria<\/code>).<\/li>\n\n\n\n<li>Then, set a flag (<code>found<\/code>) to <code>False<\/code>. If the input name matches with a person on the list, set its value to <code>True<\/code>, show the person&#8217;s information and exit the loop by using the <code>break<\/code> statement.<\/li>\n\n\n\n<li>Finally, check the <code>found<\/code> flag and show a message.<\/li>\n<\/ul>\n\n\n\n<p>However, if you use the <code>for else<\/code> statement, the program will be much shorter.<\/p>\n\n\n\n<p>The following shows the new version of the program that uses the <code>for else<\/code> statement:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">people = &#91;{<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'John'<\/span>, <span class=\"hljs-string\">'age'<\/span>: <span class=\"hljs-number\">25<\/span>},\n        {<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'Jane'<\/span>, <span class=\"hljs-string\">'age'<\/span>: <span class=\"hljs-number\">22<\/span>},\n        {<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'Peter'<\/span>, <span class=\"hljs-string\">'age'<\/span>: <span class=\"hljs-number\">30<\/span>},\n        {<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'Jenifer'<\/span>, <span class=\"hljs-string\">'age'<\/span>: <span class=\"hljs-number\">28<\/span>}]\n\nname = <span class=\"hljs-string\">'Maria'<\/span>\n\n<span class=\"hljs-keyword\">for<\/span> person in people:\n    <span class=\"hljs-keyword\">if<\/span> person&#91;<span class=\"hljs-string\">'name'<\/span>] == name:\n        <span class=\"hljs-keyword\">print<\/span>(person)\n        <span class=\"hljs-keyword\">break<\/span>\n<span class=\"hljs-keyword\">else<\/span>:\n    <span class=\"hljs-keyword\">print<\/span>(f<span class=\"hljs-string\">'{name} not found!'<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=cGVvcGxlID0gW3snbmFtZSc6ICdKb2huJywgJ2FnZSc6IDI1fSwKICAgICAgICB7J25hbWUnOiAnSmFuZScsICdhZ2UnOiAyMn0sCiAgICAgICAgeyduYW1lJzogJ1BldGVyJywgJ2FnZSc6IDMwfSwKICAgICAgICB7J25hbWUnOiAnSmVuaWZlcicsICdhZ2UnOiAyOH1dCgpuYW1lID0gJ01hcmlhJwoKZm9yIHBlcnNvbiBpbiBwZW9wbGU6CiAgICBpZiBwZXJzb25bJ25hbWUnXSA9PSBuYW1lOgogICAgICAgIHByaW50KHBlcnNvbikKICAgICAgICBicmVhawplbHNlOgogICAgcHJpbnQoZid7bmFtZX0gbm90IGZvdW5kIScp\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>By using the <code>for else<\/code> statement, the program doesn&#8217;t need to use a <code>flag<\/code> and an <code><a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-if\/\">if<\/a><\/code> statement after the loop.<\/p>\n\n\n\n<p>In this new program, if the input name matches a person on the list, it&#8217;ll show the person&#8217;s information and exit the loop by using the <code>break<\/code> statement.<\/p>\n\n\n\n<p>When the loop encounters the <code>break<\/code> statement, the <code>else<\/code> clause won&#8217;t execute.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='iterating-over-an-empty-list'>Iterating over an empty list <a href=\"#iterating-over-an-empty-list\" class=\"anchor\" id=\"iterating-over-an-empty-list\" title=\"Anchor for Iterating over an empty list\">#<\/a><\/h2>\n\n\n\n<p>The following example uses a <code>for...else<\/code>  statement to iterate over a list and display that the list is empty:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">people  = &#91;]\n\n<span class=\"hljs-keyword\">for<\/span> person in people:\n    <span class=\"hljs-keyword\">print<\/span>(person)\n<span class=\"hljs-keyword\">else<\/span>:\n    <span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"The list is empty.\"<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">The <span class=\"hljs-keyword\">list<\/span> is <span class=\"hljs-keyword\">empty<\/span>.<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use Python <code>for...else<\/code> statement to execute a code block if the loop doesn&#8217;t encounter a <code>break<\/code> statement or if the iterables object is empty.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id='quiz'>Quiz <a href=\"#quiz\" class=\"anchor\" id=\"quiz\" title=\"Anchor for Quiz\">#<\/a><\/h2>\n\n\n\n<iframe loading=\"lazy\"\n  name=\"quiz\"\n  src=\"\/quiz\/?quiz=for-else\"\n  height=\"700\"\n  width=\"600\"\n  class=\"iframe\"\n><\/iframe>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"722\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-basics\/python-for-else\/\"\n\t\t\t\tdata-post-title=\"Python for&#8230;else\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"722\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-basics\/python-for-else\/\"\n\t\t\t\tdata-post-title=\"Python for&#8230;else\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\t\t\t<input type=\"button\" name=\"wth-submit\" class=\"wth-btn wth-btn-submit\" id=\"wth-submit\" \/>\n\t\t\t<input type=\"button\" class=\"wth-btn wth-btn-cancel\" value=\"Cancel\" \/>\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Summary: in this tutorial, you&#8217;ll learn about the Python for&#8230;else statement and how to use it effectively. Introduction to the Python for&#8230;else statement # In Python, the for statement can have an optional else clause, which you may not be familiar with especially if you&#8217;re coming from other languages such as Java or C#. The [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":37,"menu_order":49,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-722","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/722","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/comments?post=722"}],"version-history":[{"count":5,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/722\/revisions"}],"predecessor-version":[{"id":7280,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/722\/revisions\/7280"}],"up":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/37"}],"wp:attachment":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/media?parent=722"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}