From 276dae5fe88c94a56459b174a2e0aa2c74106b6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Thu, 23 Sep 2021 13:41:21 +0530 Subject: [PATCH 01/23] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c992ab3..6d9289c 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ Go [here](https://github.com/milaan9/03_Python_Flow_Control) if you aren't here 1. Go [here](https://github.com/milaan9/03_Python_Flow_Control) if you aren't here already. -2. Click the big green "Code" button in the top right of the page, then click "[Download ZIP](https://github.com/milaan9/03_Python_Flow_Control/archive/refs/heads/main.zip)". +2. Click the big green '`Code`' button in the top right of the page, then click '[`Download ZIP`](https://github.com/milaan9/03_Python_Flow_Control/archive/refs/heads/main.zip)". ![Download ZIP](img/dnld_rep.png) From d02df26eef65326e49f8f682b2cd85398dba5b46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Thu, 23 Sep 2021 13:41:50 +0530 Subject: [PATCH 02/23] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6d9289c..0f87564 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ Go [here](https://github.com/milaan9/03_Python_Flow_Control) if you aren't here 1. Go [here](https://github.com/milaan9/03_Python_Flow_Control) if you aren't here already. -2. Click the big green '`Code`' button in the top right of the page, then click '[`Download ZIP`](https://github.com/milaan9/03_Python_Flow_Control/archive/refs/heads/main.zip)". +2. Click the big green '`Code`' button in the top right of the page, then click '[`Download ZIP`](https://github.com/milaan9/03_Python_Flow_Control/archive/refs/heads/main.zip)'. ![Download ZIP](img/dnld_rep.png) From 3a5b369535089e8a5d47f9604d2028f03fca273d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Thu, 23 Sep 2021 15:34:41 +0530 Subject: [PATCH 03/23] Update README.md --- README.md | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 0f87564..50a5089 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ Decision Making statements are used when we want a set of instructions should be | 06 | **[Python_while_Loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/006_Python_while_Loop.ipynb)** | | 07 | **[Python_break_continue_pass_statements](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)** | -These are online **read-only** versions. However you can "Run ▶" the code **online** by clicking here → binder +These are online **read-only** versions. However you can **`Run ▶`** the code **online** by clicking here → binder --- @@ -68,17 +68,15 @@ These are online **read-only** versions. However you can "Run ▶" the code **on ### How can I thank you for writing and sharing this tutorial? 🌷 -You can ⭐ star this tutorial. Starring is free for you, but it tells me and other people that it was helpful and you like this tutorial. +You can Star Badge and Fork Badge Starring and Forking is free for you, but it tells me and other people that it was helpful and you like this tutorial. -Go [here](https://github.com/milaan9/03_Python_Flow_Control) if you aren't here already and click the "⭐ Star" button in the top right corner. You will be asked to create a GitHub account if you don't already have one. +Go [**`here`**](https://github.com/milaan9/03_Python_Flow_Control) if you aren't here already and click ➞ **`✰ Star`** and **`ⵖ Fork`** button in the top right corner. You will be asked to create a GitHub account if you don't already have one. --- ### How can I read this tutorial without an Internet connection? 🤔 -1. Go [here](https://github.com/milaan9/03_Python_Flow_Control) if you aren't here already. - -2. Click the big green '`Code`' button in the top right of the page, then click '[`Download ZIP`](https://github.com/milaan9/03_Python_Flow_Control/archive/refs/heads/main.zip)'. +1. Go [**`here`**](https://github.com/milaan9/03_Python_Flow_Control) and click the big green ➞ **`Code`** button in the top right of the page, then click ➞ [**`Download ZIP`**](https://github.com/milaan9/03_Python_Flow_Control/archive/refs/heads/main.zip)'. ![Download ZIP](img/dnld_rep.png) @@ -86,7 +84,7 @@ Go [here](https://github.com/milaan9/03_Python_Flow_Control) if you aren't here 4. Launch ipython notebook from the folder which contains the notebooks. Open each one of them - `Kernel > Restart & Clear Output` + **`Kernel > Restart & Clear Output`** This will clear all the outputs and now you can understand each statement and learn interactively. From 3f5562763ad6cd220a8fbe7d5085dcb5a8fd1d51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Thu, 23 Sep 2021 15:35:17 +0530 Subject: [PATCH 04/23] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 50a5089..023353c 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ Go [**`here`**](https://github.com/milaan9/03_Python_Flow_Control) if you aren't ### How can I read this tutorial without an Internet connection? 🤔 -1. Go [**`here`**](https://github.com/milaan9/03_Python_Flow_Control) and click the big green ➞ **`Code`** button in the top right of the page, then click ➞ [**`Download ZIP`**](https://github.com/milaan9/03_Python_Flow_Control/archive/refs/heads/main.zip)'. +1. Go [**`here`**](https://github.com/milaan9/03_Python_Flow_Control) and click the big green ➞ **`Code`** button in the top right of the page, then click ➞ [**`Download ZIP`**](https://github.com/milaan9/03_Python_Flow_Control/archive/refs/heads/main.zip). ![Download ZIP](img/dnld_rep.png) From 8f6f390d2f7707b85a9352b7b5ec35128f9d697c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Thu, 23 Sep 2021 15:37:50 +0530 Subject: [PATCH 05/23] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 023353c..7df87a8 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ Decision Making statements are used when we want a set of instructions should be | 06 | **[Python_while_Loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/006_Python_while_Loop.ipynb)** | | 07 | **[Python_break_continue_pass_statements](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)** | -These are online **read-only** versions. However you can **`Run ▶`** the code **online** by clicking here → binder +These are online **read-only** versions. However you can **`Run ▶`** the code **online** by clicking here ➞ binder --- From 1451abfbb1ccb7c14be55e354cb83df2daa92ded Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Thu, 23 Sep 2021 16:19:44 +0530 Subject: [PATCH 06/23] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7df87a8..14550b9 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,7 @@ Go [**`here`**](https://github.com/milaan9/03_Python_Flow_Control) if you aren't --- -### How can I read this tutorial without an Internet connection? 🤔 +### How can I read this tutorial without an Internet connection? GIF 1. Go [**`here`**](https://github.com/milaan9/03_Python_Flow_Control) and click the big green ➞ **`Code`** button in the top right of the page, then click ➞ [**`Download ZIP`**](https://github.com/milaan9/03_Python_Flow_Control/archive/refs/heads/main.zip). From 2681d25b3c5bb49d57880880ea1fff9210b48331 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Thu, 23 Sep 2021 21:06:58 +0530 Subject: [PATCH 07/23] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 14550b9..410efec 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,8 @@

-binder +binder +colab

# 03_Python_Flow_Control From a6678a73bc591bb58c3b4c4a2585dca2dac67da1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Thu, 23 Sep 2021 21:08:01 +0530 Subject: [PATCH 08/23] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 410efec..f9580a2 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ Decision Making statements are used when we want a set of instructions should be | 06 | **[Python_while_Loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/006_Python_while_Loop.ipynb)** | | 07 | **[Python_break_continue_pass_statements](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)** | -These are online **read-only** versions. However you can **`Run ▶`** the code **online** by clicking here ➞ binder +These are online **read-only** versions. However you can **`Run ▶`** the code **online** by clicking here ➞ binder --- From 365fd39bf56706a91add91fc9e1b77ce7b8e8a75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Mon, 4 Oct 2021 17:15:22 +0530 Subject: [PATCH 09/23] Add files via upload --- countries_details_data.py | 2620 +++++++++++++++++++++++++++++++++++++ 1 file changed, 2620 insertions(+) create mode 100644 countries_details_data.py diff --git a/countries_details_data.py b/countries_details_data.py new file mode 100644 index 0000000..f214fce --- /dev/null +++ b/countries_details_data.py @@ -0,0 +1,2620 @@ +[ + { + "name": "Afghanistan", + "capital": "Kabul", + "languages": [ + "Pashto", + "Uzbek", + "Turkmen" + ], + "population": 27657145, + "flag": "https://restcountries.eu/data/afg.svg", + "currency": "Afghan afghani" + }, + { + "name": "Åland Islands", + "capital": "Mariehamn", + "languages": [ + "Swedish" + ], + "population": 28875, + "flag": "https://restcountries.eu/data/ala.svg", + "currency": "Euro" + }, + { + "name": "Albania", + "capital": "Tirana", + "languages": [ + "Albanian" + ], + "population": 2886026, + "flag": "https://restcountries.eu/data/alb.svg", + "currency": "Albanian lek" + }, + { + "name": "Algeria", + "capital": "Algiers", + "languages": [ + "Arabic" + ], + "population": 40400000, + "flag": "https://restcountries.eu/data/dza.svg", + "currency": "Algerian dinar" + }, + { + "name": "American Samoa", + "capital": "Pago Pago", + "languages": [ + "English", + "Samoan" + ], + "population": 57100, + "flag": "https://restcountries.eu/data/asm.svg", + "currency": "United State Dollar" + }, + { + "name": "Andorra", + "capital": "Andorra la Vella", + "languages": [ + "Catalan" + ], + "population": 78014, + "flag": "https://restcountries.eu/data/and.svg", + "currency": "Euro" + }, + { + "name": "Angola", + "capital": "Luanda", + "languages": [ + "Portuguese" + ], + "population": 25868000, + "flag": "https://restcountries.eu/data/ago.svg", + "currency": "Angolan kwanza" + }, + { + "name": "Anguilla", + "capital": "The Valley", + "languages": [ + "English" + ], + "population": 13452, + "flag": "https://restcountries.eu/data/aia.svg", + "currency": "East Caribbean dollar" + }, + { + "name": "Antarctica", + "capital": "", + "languages": [ + "English", + "Russian" + ], + "population": 1000, + "flag": "https://restcountries.eu/data/ata.svg", + "currency": "Australian dollar" + }, + { + "name": "Antigua and Barbuda", + "capital": "Saint John's", + "languages": [ + "English" + ], + "population": 86295, + "flag": "https://restcountries.eu/data/atg.svg", + "currency": "East Caribbean dollar" + }, + { + "name": "Argentina", + "capital": "Buenos Aires", + "languages": [ + "Spanish", + "Guaraní" + ], + "population": 43590400, + "flag": "https://restcountries.eu/data/arg.svg", + "currency": "Argentine peso" + }, + { + "name": "Armenia", + "capital": "Yerevan", + "languages": [ + "Armenian", + "Russian" + ], + "population": 2994400, + "flag": "https://restcountries.eu/data/arm.svg", + "currency": "Armenian dram" + }, + { + "name": "Aruba", + "capital": "Oranjestad", + "languages": [ + "Dutch", + "(Eastern) Punjabi" + ], + "population": 107394, + "flag": "https://restcountries.eu/data/abw.svg", + "currency": "Aruban florin" + }, + { + "name": "Australia", + "capital": "Canberra", + "languages": [ + "English" + ], + "population": 24117360, + "flag": "https://restcountries.eu/data/aus.svg", + "currency": "Australian dollar" + }, + { + "name": "Austria", + "capital": "Vienna", + "languages": [ + "German" + ], + "population": 8725931, + "flag": "https://restcountries.eu/data/aut.svg", + "currency": "Euro" + }, + { + "name": "Azerbaijan", + "capital": "Baku", + "languages": [ + "Azerbaijani" + ], + "population": 9730500, + "flag": "https://restcountries.eu/data/aze.svg", + "currency": "Azerbaijani manat" + }, + { + "name": "Bahamas", + "capital": "Nassau", + "languages": [ + "English" + ], + "population": 378040, + "flag": "https://restcountries.eu/data/bhs.svg", + "currency": "Bahamian dollar" + }, + { + "name": "Bahrain", + "capital": "Manama", + "languages": [ + "Arabic" + ], + "population": 1404900, + "flag": "https://restcountries.eu/data/bhr.svg", + "currency": "Bahraini dinar" + }, + { + "name": "Bangladesh", + "capital": "Dhaka", + "languages": [ + "Bengali" + ], + "population": 161006790, + "flag": "https://restcountries.eu/data/bgd.svg", + "currency": "Bangladeshi taka" + }, + { + "name": "Barbados", + "capital": "Bridgetown", + "languages": [ + "English" + ], + "population": 285000, + "flag": "https://restcountries.eu/data/brb.svg", + "currency": "Barbadian dollar" + }, + { + "name": "Belarus", + "capital": "Minsk", + "languages": [ + "Belarusian", + "Russian" + ], + "population": 9498700, + "flag": "https://restcountries.eu/data/blr.svg", + "currency": "New Belarusian ruble" + }, + { + "name": "Belgium", + "capital": "Brussels", + "languages": [ + "Dutch", + "French", + "German" + ], + "population": 11319511, + "flag": "https://restcountries.eu/data/bel.svg", + "currency": "Euro" + }, + { + "name": "Belize", + "capital": "Belmopan", + "languages": [ + "English", + "Spanish" + ], + "population": 370300, + "flag": "https://restcountries.eu/data/blz.svg", + "currency": "Belize dollar" + }, + { + "name": "Benin", + "capital": "Porto-Novo", + "languages": [ + "French" + ], + "population": 10653654, + "flag": "https://restcountries.eu/data/ben.svg", + "currency": "West African CFA franc" + }, + { + "name": "Bermuda", + "capital": "Hamilton", + "languages": [ + "English" + ], + "population": 61954, + "flag": "https://restcountries.eu/data/bmu.svg", + "currency": "Bermudian dollar" + }, + { + "name": "Bhutan", + "capital": "Thimphu", + "languages": [ + "Dzongkha" + ], + "population": 775620, + "flag": "https://restcountries.eu/data/btn.svg", + "currency": "Bhutanese ngultrum" + }, + { + "name": "Bolivia (Plurinational State of)", + "capital": "Sucre", + "languages": [ + "Spanish", + "Aymara", + "Quechua" + ], + "population": 10985059, + "flag": "https://restcountries.eu/data/bol.svg", + "currency": "Bolivian boliviano" + }, + { + "name": "Bonaire, Sint Eustatius and Saba", + "capital": "Kralendijk", + "languages": [ + "Dutch" + ], + "population": 17408, + "flag": "https://restcountries.eu/data/bes.svg", + "currency": "United States dollar" + }, + { + "name": "Bosnia and Herzegovina", + "capital": "Sarajevo", + "languages": [ + "Bosnian", + "Croatian", + "Serbian" + ], + "population": 3531159, + "flag": "https://restcountries.eu/data/bih.svg", + "currency": "Bosnia and Herzegovina convertible mark" + }, + { + "name": "Botswana", + "capital": "Gaborone", + "languages": [ + "English", + "Tswana" + ], + "population": 2141206, + "flag": "https://restcountries.eu/data/bwa.svg", + "currency": "Botswana pula" + }, + { + "name": "Bouvet Island", + "capital": "", + "languages": [ + "Norwegian", + "Norwegian Bokmål", + "Norwegian Nynorsk" + ], + "population": 0, + "flag": "https://restcountries.eu/data/bvt.svg", + "currency": "Norwegian krone" + }, + { + "name": "Brazil", + "capital": "Brasília", + "languages": [ + "Portuguese" + ], + "population": 206135893, + "flag": "https://restcountries.eu/data/bra.svg", + "currency": "Brazilian real" + }, + { + "name": "British Indian Ocean Territory", + "capital": "Diego Garcia", + "languages": [ + "English" + ], + "population": 3000, + "flag": "https://restcountries.eu/data/iot.svg", + "currency": "United States dollar" + }, + { + "name": "United States Minor Outlying Islands", + "capital": "", + "languages": [ + "English" + ], + "population": 300, + "flag": "https://restcountries.eu/data/umi.svg", + "currency": "United States Dollar" + }, + { + "name": "Virgin Islands (British)", + "capital": "Road Town", + "languages": [ + "English" + ], + "population": 28514, + "flag": "https://restcountries.eu/data/vgb.svg", + "currency": "[D]" + }, + { + "name": "Virgin Islands (U.S.)", + "capital": "Charlotte Amalie", + "languages": [ + "English" + ], + "population": 114743, + "flag": "https://restcountries.eu/data/vir.svg", + "currency": "United States dollar" + }, + { + "name": "Brunei Darussalam", + "capital": "Bandar Seri Begawan", + "languages": [ + "Malay" + ], + "population": 411900, + "flag": "https://restcountries.eu/data/brn.svg", + "currency": "Brunei dollar" + }, + { + "name": "Bulgaria", + "capital": "Sofia", + "languages": [ + "Bulgarian" + ], + "population": 7153784, + "flag": "https://restcountries.eu/data/bgr.svg", + "currency": "Bulgarian lev" + }, + { + "name": "Burkina Faso", + "capital": "Ouagadougou", + "languages": [ + "French", + "Fula" + ], + "population": 19034397, + "flag": "https://restcountries.eu/data/bfa.svg", + "currency": "West African CFA franc" + }, + { + "name": "Burundi", + "capital": "Bujumbura", + "languages": [ + "French", + "Kirundi" + ], + "population": 10114505, + "flag": "https://restcountries.eu/data/bdi.svg", + "currency": "Burundian franc" + }, + { + "name": "Cambodia", + "capital": "Phnom Penh", + "languages": [ + "Khmer" + ], + "population": 15626444, + "flag": "https://restcountries.eu/data/khm.svg", + "currency": "Cambodian riel" + }, + { + "name": "Cameroon", + "capital": "Yaoundé", + "languages": [ + "English", + "French" + ], + "population": 22709892, + "flag": "https://restcountries.eu/data/cmr.svg", + "currency": "Central African CFA franc" + }, + { + "name": "Canada", + "capital": "Ottawa", + "languages": [ + "English", + "French" + ], + "population": 36155487, + "flag": "https://restcountries.eu/data/can.svg", + "currency": "Canadian dollar" + }, + { + "name": "Cabo Verde", + "capital": "Praia", + "languages": [ + "Portuguese" + ], + "population": 531239, + "flag": "https://restcountries.eu/data/cpv.svg", + "currency": "Cape Verdean escudo" + }, + { + "name": "Cayman Islands", + "capital": "George Town", + "languages": [ + "English" + ], + "population": 58238, + "flag": "https://restcountries.eu/data/cym.svg", + "currency": "Cayman Islands dollar" + }, + { + "name": "Central African Republic", + "capital": "Bangui", + "languages": [ + "French", + "Sango" + ], + "population": 4998000, + "flag": "https://restcountries.eu/data/caf.svg", + "currency": "Central African CFA franc" + }, + { + "name": "Chad", + "capital": "N'Djamena", + "languages": [ + "French", + "Arabic" + ], + "population": 14497000, + "flag": "https://restcountries.eu/data/tcd.svg", + "currency": "Central African CFA franc" + }, + { + "name": "Chile", + "capital": "Santiago", + "languages": [ + "Spanish" + ], + "population": 18191900, + "flag": "https://restcountries.eu/data/chl.svg", + "currency": "Chilean peso" + }, + { + "name": "China", + "capital": "Beijing", + "languages": [ + "Chinese" + ], + "population": 1377422166, + "flag": "https://restcountries.eu/data/chn.svg", + "currency": "Chinese yuan" + }, + { + "name": "Christmas Island", + "capital": "Flying Fish Cove", + "languages": [ + "English" + ], + "population": 2072, + "flag": "https://restcountries.eu/data/cxr.svg", + "currency": "Australian dollar" + }, + { + "name": "Cocos (Keeling) Islands", + "capital": "West Island", + "languages": [ + "English" + ], + "population": 550, + "flag": "https://restcountries.eu/data/cck.svg", + "currency": "Australian dollar" + }, + { + "name": "Colombia", + "capital": "Bogotá", + "languages": [ + "Spanish" + ], + "population": 48759958, + "flag": "https://restcountries.eu/data/col.svg", + "currency": "Colombian peso" + }, + { + "name": "Comoros", + "capital": "Moroni", + "languages": [ + "Arabic", + "French" + ], + "population": 806153, + "flag": "https://restcountries.eu/data/com.svg", + "currency": "Comorian franc" + }, + { + "name": "Congo", + "capital": "Brazzaville", + "languages": [ + "French", + "Lingala" + ], + "population": 4741000, + "flag": "https://restcountries.eu/data/cog.svg", + "currency": "Central African CFA franc" + }, + { + "name": "Congo (Democratic Republic of the)", + "capital": "Kinshasa", + "languages": [ + "French", + "Lingala", + "Kongo", + "Swahili", + "Luba-Katanga" + ], + "population": 85026000, + "flag": "https://restcountries.eu/data/cod.svg", + "currency": "Congolese franc" + }, + { + "name": "Cook Islands", + "capital": "Avarua", + "languages": [ + "English" + ], + "population": 18100, + "flag": "https://restcountries.eu/data/cok.svg", + "currency": "New Zealand dollar" + }, + { + "name": "Costa Rica", + "capital": "San José", + "languages": [ + "Spanish" + ], + "population": 4890379, + "flag": "https://restcountries.eu/data/cri.svg", + "currency": "Costa Rican colón" + }, + { + "name": "Croatia", + "capital": "Zagreb", + "languages": [ + "Croatian" + ], + "population": 4190669, + "flag": "https://restcountries.eu/data/hrv.svg", + "currency": "Croatian kuna" + }, + { + "name": "Cuba", + "capital": "Havana", + "languages": [ + "Spanish" + ], + "population": 11239004, + "flag": "https://restcountries.eu/data/cub.svg", + "currency": "Cuban convertible peso" + }, + { + "name": "Curaçao", + "capital": "Willemstad", + "languages": [ + "Dutch", + "(Eastern) Punjabi", + "English" + ], + "population": 154843, + "flag": "https://restcountries.eu/data/cuw.svg", + "currency": "Netherlands Antillean guilder" + }, + { + "name": "Cyprus", + "capital": "Nicosia", + "languages": [ + "Greek (modern)", + "Turkish", + "Armenian" + ], + "population": 847000, + "flag": "https://restcountries.eu/data/cyp.svg", + "currency": "Euro" + }, + { + "name": "Czech Republic", + "capital": "Prague", + "languages": [ + "Czech", + "Slovak" + ], + "population": 10558524, + "flag": "https://restcountries.eu/data/cze.svg", + "currency": "Czech koruna" + }, + { + "name": "Denmark", + "capital": "Copenhagen", + "languages": [ + "Danish" + ], + "population": 5717014, + "flag": "https://restcountries.eu/data/dnk.svg", + "currency": "Danish krone" + }, + { + "name": "Djibouti", + "capital": "Djibouti", + "languages": [ + "French", + "Arabic" + ], + "population": 900000, + "flag": "https://restcountries.eu/data/dji.svg", + "currency": "Djiboutian franc" + }, + { + "name": "Dominica", + "capital": "Roseau", + "languages": [ + "English" + ], + "population": 71293, + "flag": "https://restcountries.eu/data/dma.svg", + "currency": "East Caribbean dollar" + }, + { + "name": "Dominican Republic", + "capital": "Santo Domingo", + "languages": [ + "Spanish" + ], + "population": 10075045, + "flag": "https://restcountries.eu/data/dom.svg", + "currency": "Dominican peso" + }, + { + "name": "Ecuador", + "capital": "Quito", + "languages": [ + "Spanish" + ], + "population": 16545799, + "flag": "https://restcountries.eu/data/ecu.svg", + "currency": "United States dollar" + }, + { + "name": "Egypt", + "capital": "Cairo", + "languages": [ + "Arabic" + ], + "population": 91290000, + "flag": "https://restcountries.eu/data/egy.svg", + "currency": "Egyptian pound" + }, + { + "name": "El Salvador", + "capital": "San Salvador", + "languages": [ + "Spanish" + ], + "population": 6520675, + "flag": "https://restcountries.eu/data/slv.svg", + "currency": "United States dollar" + }, + { + "name": "Equatorial Guinea", + "capital": "Malabo", + "languages": [ + "Spanish", + "French" + ], + "population": 1222442, + "flag": "https://restcountries.eu/data/gnq.svg", + "currency": "Central African CFA franc" + }, + { + "name": "Eritrea", + "capital": "Asmara", + "languages": [ + "Tigrinya", + "Arabic", + "English" + ], + "population": 5352000, + "flag": "https://restcountries.eu/data/eri.svg", + "currency": "Eritrean nakfa" + }, + { + "name": "Estonia", + "capital": "Tallinn", + "languages": [ + "Estonian" + ], + "population": 1315944, + "flag": "https://restcountries.eu/data/est.svg", + "currency": "Euro" + }, + { + "name": "Ethiopia", + "capital": "Addis Ababa", + "languages": [ + "Amharic" + ], + "population": 92206005, + "flag": "https://restcountries.eu/data/eth.svg", + "currency": "Ethiopian birr" + }, + { + "name": "Falkland Islands (Malvinas)", + "capital": "Stanley", + "languages": [ + "English" + ], + "population": 2563, + "flag": "https://restcountries.eu/data/flk.svg", + "currency": "Falkland Islands pound" + }, + { + "name": "Faroe Islands", + "capital": "Tórshavn", + "languages": [ + "Faroese" + ], + "population": 49376, + "flag": "https://restcountries.eu/data/fro.svg", + "currency": "Danish krone" + }, + { + "name": "Fiji", + "capital": "Suva", + "languages": [ + "English", + "Fijian", + "Hindi", + "Urdu" + ], + "population": 867000, + "flag": "https://restcountries.eu/data/fji.svg", + "currency": "Fijian dollar" + }, + { + "name": "Finland", + "capital": "Helsinki", + "languages": [ + "Finnish", + "Swedish" + ], + "population": 5491817, + "flag": "https://restcountries.eu/data/fin.svg", + "currency": "Euro" + }, + { + "name": "France", + "capital": "Paris", + "languages": [ + "French" + ], + "population": 66710000, + "flag": "https://restcountries.eu/data/fra.svg", + "currency": "Euro" + }, + { + "name": "French Guiana", + "capital": "Cayenne", + "languages": [ + "French" + ], + "population": 254541, + "flag": "https://restcountries.eu/data/guf.svg", + "currency": "Euro" + }, + { + "name": "French Polynesia", + "capital": "Papeetē", + "languages": [ + "French" + ], + "population": 271800, + "flag": "https://restcountries.eu/data/pyf.svg", + "currency": "CFP franc" + }, + { + "name": "French Southern Territories", + "capital": "Port-aux-Français", + "languages": [ + "French" + ], + "population": 140, + "flag": "https://restcountries.eu/data/atf.svg", + "currency": "Euro" + }, + { + "name": "Gabon", + "capital": "Libreville", + "languages": [ + "French" + ], + "population": 1802278, + "flag": "https://restcountries.eu/data/gab.svg", + "currency": "Central African CFA franc" + }, + { + "name": "Gambia", + "capital": "Banjul", + "languages": [ + "English" + ], + "population": 1882450, + "flag": "https://restcountries.eu/data/gmb.svg", + "currency": "Gambian dalasi" + }, + { + "name": "Georgia", + "capital": "Tbilisi", + "languages": [ + "Georgian" + ], + "population": 3720400, + "flag": "https://restcountries.eu/data/geo.svg", + "currency": "Georgian Lari" + }, + { + "name": "Germany", + "capital": "Berlin", + "languages": [ + "German" + ], + "population": 81770900, + "flag": "https://restcountries.eu/data/deu.svg", + "currency": "Euro" + }, + { + "name": "Ghana", + "capital": "Accra", + "languages": [ + "English" + ], + "population": 27670174, + "flag": "https://restcountries.eu/data/gha.svg", + "currency": "Ghanaian cedi" + }, + { + "name": "Gibraltar", + "capital": "Gibraltar", + "languages": [ + "English" + ], + "population": 33140, + "flag": "https://restcountries.eu/data/gib.svg", + "currency": "Gibraltar pound" + }, + { + "name": "Greece", + "capital": "Athens", + "languages": [ + "Greek (modern)" + ], + "population": 10858018, + "flag": "https://restcountries.eu/data/grc.svg", + "currency": "Euro" + }, + { + "name": "Greenland", + "capital": "Nuuk", + "languages": [ + "Kalaallisut" + ], + "population": 55847, + "flag": "https://restcountries.eu/data/grl.svg", + "currency": "Danish krone" + }, + { + "name": "Grenada", + "capital": "St. George's", + "languages": [ + "English" + ], + "population": 103328, + "flag": "https://restcountries.eu/data/grd.svg", + "currency": "East Caribbean dollar" + }, + { + "name": "Guadeloupe", + "capital": "Basse-Terre", + "languages": [ + "French" + ], + "population": 400132, + "flag": "https://restcountries.eu/data/glp.svg", + "currency": "Euro" + }, + { + "name": "Guam", + "capital": "Hagåtña", + "languages": [ + "English", + "Chamorro", + "Spanish" + ], + "population": 184200, + "flag": "https://restcountries.eu/data/gum.svg", + "currency": "United States dollar" + }, + { + "name": "Guatemala", + "capital": "Guatemala City", + "languages": [ + "Spanish" + ], + "population": 16176133, + "flag": "https://restcountries.eu/data/gtm.svg", + "currency": "Guatemalan quetzal" + }, + { + "name": "Guernsey", + "capital": "St. Peter Port", + "languages": [ + "English", + "French" + ], + "population": 62999, + "flag": "https://restcountries.eu/data/ggy.svg", + "currency": "British pound" + }, + { + "name": "Guinea", + "capital": "Conakry", + "languages": [ + "French", + "Fula" + ], + "population": 12947000, + "flag": "https://restcountries.eu/data/gin.svg", + "currency": "Guinean franc" + }, + { + "name": "Guinea-Bissau", + "capital": "Bissau", + "languages": [ + "Portuguese" + ], + "population": 1547777, + "flag": "https://restcountries.eu/data/gnb.svg", + "currency": "West African CFA franc" + }, + { + "name": "Guyana", + "capital": "Georgetown", + "languages": [ + "English" + ], + "population": 746900, + "flag": "https://restcountries.eu/data/guy.svg", + "currency": "Guyanese dollar" + }, + { + "name": "Haiti", + "capital": "Port-au-Prince", + "languages": [ + "French", + "Haitian" + ], + "population": 11078033, + "flag": "https://restcountries.eu/data/hti.svg", + "currency": "Haitian gourde" + }, + { + "name": "Heard Island and McDonald Islands", + "capital": "", + "languages": [ + "English" + ], + "population": 0, + "flag": "https://restcountries.eu/data/hmd.svg", + "currency": "Australian dollar" + }, + { + "name": "Holy See", + "capital": "Rome", + "languages": [ + "Latin", + "Italian", + "French", + "German" + ], + "population": 451, + "flag": "https://restcountries.eu/data/vat.svg", + "currency": "Euro" + }, + { + "name": "Honduras", + "capital": "Tegucigalpa", + "languages": [ + "Spanish" + ], + "population": 8576532, + "flag": "https://restcountries.eu/data/hnd.svg", + "currency": "Honduran lempira" + }, + { + "name": "Hong Kong", + "capital": "City of Victoria", + "languages": [ + "English", + "Chinese" + ], + "population": 7324300, + "flag": "https://restcountries.eu/data/hkg.svg", + "currency": "Hong Kong dollar" + }, + { + "name": "Hungary", + "capital": "Budapest", + "languages": [ + "Hungarian" + ], + "population": 9823000, + "flag": "https://restcountries.eu/data/hun.svg", + "currency": "Hungarian forint" + }, + { + "name": "Iceland", + "capital": "Reykjavík", + "languages": [ + "Icelandic" + ], + "population": 334300, + "flag": "https://restcountries.eu/data/isl.svg", + "currency": "Icelandic króna" + }, + { + "name": "India", + "capital": "New Delhi", + "languages": [ + "Hindi", + "English" + ], + "population": 1295210000, + "flag": "https://restcountries.eu/data/ind.svg", + "currency": "Indian rupee" + }, + { + "name": "Indonesia", + "capital": "Jakarta", + "languages": [ + "Indonesian" + ], + "population": 258705000, + "flag": "https://restcountries.eu/data/idn.svg", + "currency": "Indonesian rupiah" + }, + { + "name": "Côte d'Ivoire", + "capital": "Yamoussoukro", + "languages": [ + "French" + ], + "population": 22671331, + "flag": "https://restcountries.eu/data/civ.svg", + "currency": "West African CFA franc" + }, + { + "name": "Iran (Islamic Republic of)", + "capital": "Tehran", + "languages": [ + "Persian (Farsi)" + ], + "population": 79369900, + "flag": "https://restcountries.eu/data/irn.svg", + "currency": "Iranian rial" + }, + { + "name": "Iraq", + "capital": "Baghdad", + "languages": [ + "Arabic", + "Kurdish" + ], + "population": 37883543, + "flag": "https://restcountries.eu/data/irq.svg", + "currency": "Iraqi dinar" + }, + { + "name": "Ireland", + "capital": "Dublin", + "languages": [ + "Irish", + "English" + ], + "population": 6378000, + "flag": "https://restcountries.eu/data/irl.svg", + "currency": "Euro" + }, + { + "name": "Isle of Man", + "capital": "Douglas", + "languages": [ + "English", + "Manx" + ], + "population": 84497, + "flag": "https://restcountries.eu/data/imn.svg", + "currency": "British pound" + }, + { + "name": "Israel", + "capital": "Jerusalem", + "languages": [ + "Hebrew (modern)", + "Arabic" + ], + "population": 8527400, + "flag": "https://restcountries.eu/data/isr.svg", + "currency": "Israeli new shekel" + }, + { + "name": "Italy", + "capital": "Rome", + "languages": [ + "Italian" + ], + "population": 60665551, + "flag": "https://restcountries.eu/data/ita.svg", + "currency": "Euro" + }, + { + "name": "Jamaica", + "capital": "Kingston", + "languages": [ + "English" + ], + "population": 2723246, + "flag": "https://restcountries.eu/data/jam.svg", + "currency": "Jamaican dollar" + }, + { + "name": "Japan", + "capital": "Tokyo", + "languages": [ + "Japanese" + ], + "population": 126960000, + "flag": "https://restcountries.eu/data/jpn.svg", + "currency": "Japanese yen" + }, + { + "name": "Jersey", + "capital": "Saint Helier", + "languages": [ + "English", + "French" + ], + "population": 100800, + "flag": "https://restcountries.eu/data/jey.svg", + "currency": "British pound" + }, + { + "name": "Jordan", + "capital": "Amman", + "languages": [ + "Arabic" + ], + "population": 9531712, + "flag": "https://restcountries.eu/data/jor.svg", + "currency": "Jordanian dinar" + }, + { + "name": "Kazakhstan", + "capital": "Astana", + "languages": [ + "Kazakh", + "Russian" + ], + "population": 17753200, + "flag": "https://restcountries.eu/data/kaz.svg", + "currency": "Kazakhstani tenge" + }, + { + "name": "Kenya", + "capital": "Nairobi", + "languages": [ + "English", + "Swahili" + ], + "population": 47251000, + "flag": "https://restcountries.eu/data/ken.svg", + "currency": "Kenyan shilling" + }, + { + "name": "Kiribati", + "capital": "South Tarawa", + "languages": [ + "English" + ], + "population": 113400, + "flag": "https://restcountries.eu/data/kir.svg", + "currency": "Australian dollar" + }, + { + "name": "Kuwait", + "capital": "Kuwait City", + "languages": [ + "Arabic" + ], + "population": 4183658, + "flag": "https://restcountries.eu/data/kwt.svg", + "currency": "Kuwaiti dinar" + }, + { + "name": "Kyrgyzstan", + "capital": "Bishkek", + "languages": [ + "Kyrgyz", + "Russian" + ], + "population": 6047800, + "flag": "https://restcountries.eu/data/kgz.svg", + "currency": "Kyrgyzstani som" + }, + { + "name": "Lao People's Democratic Republic", + "capital": "Vientiane", + "languages": [ + "Lao" + ], + "population": 6492400, + "flag": "https://restcountries.eu/data/lao.svg", + "currency": "Lao kip" + }, + { + "name": "Latvia", + "capital": "Riga", + "languages": [ + "Latvian" + ], + "population": 1961600, + "flag": "https://restcountries.eu/data/lva.svg", + "currency": "Euro" + }, + { + "name": "Lebanon", + "capital": "Beirut", + "languages": [ + "Arabic", + "French" + ], + "population": 5988000, + "flag": "https://restcountries.eu/data/lbn.svg", + "currency": "Lebanese pound" + }, + { + "name": "Lesotho", + "capital": "Maseru", + "languages": [ + "English", + "Southern Sotho" + ], + "population": 1894194, + "flag": "https://restcountries.eu/data/lso.svg", + "currency": "Lesotho loti" + }, + { + "name": "Liberia", + "capital": "Monrovia", + "languages": [ + "English" + ], + "population": 4615000, + "flag": "https://restcountries.eu/data/lbr.svg", + "currency": "Liberian dollar" + }, + { + "name": "Libya", + "capital": "Tripoli", + "languages": [ + "Arabic" + ], + "population": 6385000, + "flag": "https://restcountries.eu/data/lby.svg", + "currency": "Libyan dinar" + }, + { + "name": "Liechtenstein", + "capital": "Vaduz", + "languages": [ + "German" + ], + "population": 37623, + "flag": "https://restcountries.eu/data/lie.svg", + "currency": "Swiss franc" + }, + { + "name": "Lithuania", + "capital": "Vilnius", + "languages": [ + "Lithuanian" + ], + "population": 2872294, + "flag": "https://restcountries.eu/data/ltu.svg", + "currency": "Euro" + }, + { + "name": "Luxembourg", + "capital": "Luxembourg", + "languages": [ + "French", + "German", + "Luxembourgish" + ], + "population": 576200, + "flag": "https://restcountries.eu/data/lux.svg", + "currency": "Euro" + }, + { + "name": "Macao", + "capital": "", + "languages": [ + "Chinese", + "Portuguese" + ], + "population": 649100, + "flag": "https://restcountries.eu/data/mac.svg", + "currency": "Macanese pataca" + }, + { + "name": "Macedonia (the former Yugoslav Republic of)", + "capital": "Skopje", + "languages": [ + "Macedonian" + ], + "population": 2058539, + "flag": "https://restcountries.eu/data/mkd.svg", + "currency": "Macedonian denar" + }, + { + "name": "Madagascar", + "capital": "Antananarivo", + "languages": [ + "French", + "Malagasy" + ], + "population": 22434363, + "flag": "https://restcountries.eu/data/mdg.svg", + "currency": "Malagasy ariary" + }, + { + "name": "Malawi", + "capital": "Lilongwe", + "languages": [ + "English", + "Chichewa" + ], + "population": 16832910, + "flag": "https://restcountries.eu/data/mwi.svg", + "currency": "Malawian kwacha" + }, + { + "name": "Malaysia", + "capital": "Kuala Lumpur", + "languages": [ + "Malaysian" + ], + "population": 31405416, + "flag": "https://restcountries.eu/data/mys.svg", + "currency": "Malaysian ringgit" + }, + { + "name": "Maldives", + "capital": "Malé", + "languages": [ + "Divehi" + ], + "population": 344023, + "flag": "https://restcountries.eu/data/mdv.svg", + "currency": "Maldivian rufiyaa" + }, + { + "name": "Mali", + "capital": "Bamako", + "languages": [ + "French" + ], + "population": 18135000, + "flag": "https://restcountries.eu/data/mli.svg", + "currency": "West African CFA franc" + }, + { + "name": "Malta", + "capital": "Valletta", + "languages": [ + "Maltese", + "English" + ], + "population": 425384, + "flag": "https://restcountries.eu/data/mlt.svg", + "currency": "Euro" + }, + { + "name": "Marshall Islands", + "capital": "Majuro", + "languages": [ + "English", + "Marshallese" + ], + "population": 54880, + "flag": "https://restcountries.eu/data/mhl.svg", + "currency": "United States dollar" + }, + { + "name": "Martinique", + "capital": "Fort-de-France", + "languages": [ + "French" + ], + "population": 378243, + "flag": "https://restcountries.eu/data/mtq.svg", + "currency": "Euro" + }, + { + "name": "Mauritania", + "capital": "Nouakchott", + "languages": [ + "Arabic" + ], + "population": 3718678, + "flag": "https://restcountries.eu/data/mrt.svg", + "currency": "Mauritanian ouguiya" + }, + { + "name": "Mauritius", + "capital": "Port Louis", + "languages": [ + "English" + ], + "population": 1262879, + "flag": "https://restcountries.eu/data/mus.svg", + "currency": "Mauritian rupee" + }, + { + "name": "Mayotte", + "capital": "Mamoudzou", + "languages": [ + "French" + ], + "population": 226915, + "flag": "https://restcountries.eu/data/myt.svg", + "currency": "Euro" + }, + { + "name": "Mexico", + "capital": "Mexico City", + "languages": [ + "Spanish" + ], + "population": 122273473, + "flag": "https://restcountries.eu/data/mex.svg", + "currency": "Mexican peso" + }, + { + "name": "Micronesia (Federated States of)", + "capital": "Palikir", + "languages": [ + "English" + ], + "population": 102800, + "flag": "https://restcountries.eu/data/fsm.svg", + "currency": "[D]" + }, + { + "name": "Moldova (Republic of)", + "capital": "Chișinău", + "languages": [ + "Romanian" + ], + "population": 3553100, + "flag": "https://restcountries.eu/data/mda.svg", + "currency": "Moldovan leu" + }, + { + "name": "Monaco", + "capital": "Monaco", + "languages": [ + "French" + ], + "population": 38400, + "flag": "https://restcountries.eu/data/mco.svg", + "currency": "Euro" + }, + { + "name": "Mongolia", + "capital": "Ulan Bator", + "languages": [ + "Mongolian" + ], + "population": 3093100, + "flag": "https://restcountries.eu/data/mng.svg", + "currency": "Mongolian tögrög" + }, + { + "name": "Montenegro", + "capital": "Podgorica", + "languages": [ + "Serbian", + "Bosnian", + "Albanian", + "Croatian" + ], + "population": 621810, + "flag": "https://restcountries.eu/data/mne.svg", + "currency": "Euro" + }, + { + "name": "Montserrat", + "capital": "Plymouth", + "languages": [ + "English" + ], + "population": 4922, + "flag": "https://restcountries.eu/data/msr.svg", + "currency": "East Caribbean dollar" + }, + { + "name": "Morocco", + "capital": "Rabat", + "languages": [ + "Arabic" + ], + "population": 33337529, + "flag": "https://restcountries.eu/data/mar.svg", + "currency": "Moroccan dirham" + }, + { + "name": "Mozambique", + "capital": "Maputo", + "languages": [ + "Portuguese" + ], + "population": 26423700, + "flag": "https://restcountries.eu/data/moz.svg", + "currency": "Mozambican metical" + }, + { + "name": "Myanmar", + "capital": "Naypyidaw", + "languages": [ + "Burmese" + ], + "population": 51419420, + "flag": "https://restcountries.eu/data/mmr.svg", + "currency": "Burmese kyat" + }, + { + "name": "Namibia", + "capital": "Windhoek", + "languages": [ + "English", + "Afrikaans" + ], + "population": 2324388, + "flag": "https://restcountries.eu/data/nam.svg", + "currency": "Namibian dollar" + }, + { + "name": "Nauru", + "capital": "Yaren", + "languages": [ + "English", + "Nauruan" + ], + "population": 10084, + "flag": "https://restcountries.eu/data/nru.svg", + "currency": "Australian dollar" + }, + { + "name": "Nepal", + "capital": "Kathmandu", + "languages": [ + "Nepali" + ], + "population": 28431500, + "flag": "https://restcountries.eu/data/npl.svg", + "currency": "Nepalese rupee" + }, + { + "name": "Netherlands", + "capital": "Amsterdam", + "languages": [ + "Dutch" + ], + "population": 17019800, + "flag": "https://restcountries.eu/data/nld.svg", + "currency": "Euro" + }, + { + "name": "New Caledonia", + "capital": "Nouméa", + "languages": [ + "French" + ], + "population": 268767, + "flag": "https://restcountries.eu/data/ncl.svg", + "currency": "CFP franc" + }, + { + "name": "New Zealand", + "capital": "Wellington", + "languages": [ + "English", + "Māori" + ], + "population": 4697854, + "flag": "https://restcountries.eu/data/nzl.svg", + "currency": "New Zealand dollar" + }, + { + "name": "Nicaragua", + "capital": "Managua", + "languages": [ + "Spanish" + ], + "population": 6262703, + "flag": "https://restcountries.eu/data/nic.svg", + "currency": "Nicaraguan córdoba" + }, + { + "name": "Niger", + "capital": "Niamey", + "languages": [ + "French" + ], + "population": 20715000, + "flag": "https://restcountries.eu/data/ner.svg", + "currency": "West African CFA franc" + }, + { + "name": "Nigeria", + "capital": "Abuja", + "languages": [ + "English" + ], + "population": 186988000, + "flag": "https://restcountries.eu/data/nga.svg", + "currency": "Nigerian naira" + }, + { + "name": "Niue", + "capital": "Alofi", + "languages": [ + "English" + ], + "population": 1470, + "flag": "https://restcountries.eu/data/niu.svg", + "currency": "New Zealand dollar" + }, + { + "name": "Norfolk Island", + "capital": "Kingston", + "languages": [ + "English" + ], + "population": 2302, + "flag": "https://restcountries.eu/data/nfk.svg", + "currency": "Australian dollar" + }, + { + "name": "Korea (Democratic People's Republic of)", + "capital": "Pyongyang", + "languages": [ + "Korean" + ], + "population": 25281000, + "flag": "https://restcountries.eu/data/prk.svg", + "currency": "North Korean won" + }, + { + "name": "Northern Mariana Islands", + "capital": "Saipan", + "languages": [ + "English", + "Chamorro" + ], + "population": 56940, + "flag": "https://restcountries.eu/data/mnp.svg", + "currency": "United States dollar" + }, + { + "name": "Norway", + "capital": "Oslo", + "languages": [ + "Norwegian", + "Norwegian Bokmål", + "Norwegian Nynorsk" + ], + "population": 5223256, + "flag": "https://restcountries.eu/data/nor.svg", + "currency": "Norwegian krone" + }, + { + "name": "Oman", + "capital": "Muscat", + "languages": [ + "Arabic" + ], + "population": 4420133, + "flag": "https://restcountries.eu/data/omn.svg", + "currency": "Omani rial" + }, + { + "name": "Pakistan", + "capital": "Islamabad", + "languages": [ + "English", + "Urdu" + ], + "population": 194125062, + "flag": "https://restcountries.eu/data/pak.svg", + "currency": "Pakistani rupee" + }, + { + "name": "Palau", + "capital": "Ngerulmud", + "languages": [ + "English" + ], + "population": 17950, + "flag": "https://restcountries.eu/data/plw.svg", + "currency": "[E]" + }, + { + "name": "Palestine, State of", + "capital": "Ramallah", + "languages": [ + "Arabic" + ], + "population": 4682467, + "flag": "https://restcountries.eu/data/pse.svg", + "currency": "Israeli new sheqel" + }, + { + "name": "Panama", + "capital": "Panama City", + "languages": [ + "Spanish" + ], + "population": 3814672, + "flag": "https://restcountries.eu/data/pan.svg", + "currency": "Panamanian balboa" + }, + { + "name": "Papua New Guinea", + "capital": "Port Moresby", + "languages": [ + "English" + ], + "population": 8083700, + "flag": "https://restcountries.eu/data/png.svg", + "currency": "Papua New Guinean kina" + }, + { + "name": "Paraguay", + "capital": "Asunción", + "languages": [ + "Spanish", + "Guaraní" + ], + "population": 6854536, + "flag": "https://restcountries.eu/data/pry.svg", + "currency": "Paraguayan guaraní" + }, + { + "name": "Peru", + "capital": "Lima", + "languages": [ + "Spanish" + ], + "population": 31488700, + "flag": "https://restcountries.eu/data/per.svg", + "currency": "Peruvian sol" + }, + { + "name": "Philippines", + "capital": "Manila", + "languages": [ + "English" + ], + "population": 103279800, + "flag": "https://restcountries.eu/data/phl.svg", + "currency": "Philippine peso" + }, + { + "name": "Pitcairn", + "capital": "Adamstown", + "languages": [ + "English" + ], + "population": 56, + "flag": "https://restcountries.eu/data/pcn.svg", + "currency": "New Zealand dollar" + }, + { + "name": "Poland", + "capital": "Warsaw", + "languages": [ + "Polish" + ], + "population": 38437239, + "flag": "https://restcountries.eu/data/pol.svg", + "currency": "Polish złoty" + }, + { + "name": "Portugal", + "capital": "Lisbon", + "languages": [ + "Portuguese" + ], + "population": 10374822, + "flag": "https://restcountries.eu/data/prt.svg", + "currency": "Euro" + }, + { + "name": "Puerto Rico", + "capital": "San Juan", + "languages": [ + "Spanish", + "English" + ], + "population": 3474182, + "flag": "https://restcountries.eu/data/pri.svg", + "currency": "United States dollar" + }, + { + "name": "Qatar", + "capital": "Doha", + "languages": [ + "Arabic" + ], + "population": 2587564, + "flag": "https://restcountries.eu/data/qat.svg", + "currency": "Qatari riyal" + }, + { + "name": "Republic of Kosovo", + "capital": "Pristina", + "languages": [ + "Albanian", + "Serbian" + ], + "population": 1733842, + "flag": "https://restcountries.eu/data/kos.svg", + "currency": "Euro" + }, + { + "name": "Réunion", + "capital": "Saint-Denis", + "languages": [ + "French" + ], + "population": 840974, + "flag": "https://restcountries.eu/data/reu.svg", + "currency": "Euro" + }, + { + "name": "Romania", + "capital": "Bucharest", + "languages": [ + "Romanian" + ], + "population": 19861408, + "flag": "https://restcountries.eu/data/rou.svg", + "currency": "Romanian leu" + }, + { + "name": "Russian Federation", + "capital": "Moscow", + "languages": [ + "Russian" + ], + "population": 146599183, + "flag": "https://restcountries.eu/data/rus.svg", + "currency": "Russian ruble" + }, + { + "name": "Rwanda", + "capital": "Kigali", + "languages": [ + "Kinyarwanda", + "English", + "French" + ], + "population": 11553188, + "flag": "https://restcountries.eu/data/rwa.svg", + "currency": "Rwandan franc" + }, + { + "name": "Saint Barthélemy", + "capital": "Gustavia", + "languages": [ + "French" + ], + "population": 9417, + "flag": "https://restcountries.eu/data/blm.svg", + "currency": "Euro" + }, + { + "name": "Saint Helena, Ascension and Tristan da Cunha", + "capital": "Jamestown", + "languages": [ + "English" + ], + "population": 4255, + "flag": "https://restcountries.eu/data/shn.svg", + "currency": "Saint Helena pound" + }, + { + "name": "Saint Kitts and Nevis", + "capital": "Basseterre", + "languages": [ + "English" + ], + "population": 46204, + "flag": "https://restcountries.eu/data/kna.svg", + "currency": "East Caribbean dollar" + }, + { + "name": "Saint Lucia", + "capital": "Castries", + "languages": [ + "English" + ], + "population": 186000, + "flag": "https://restcountries.eu/data/lca.svg", + "currency": "East Caribbean dollar" + }, + { + "name": "Saint Martin (French part)", + "capital": "Marigot", + "languages": [ + "English", + "French", + "Dutch" + ], + "population": 36979, + "flag": "https://restcountries.eu/data/maf.svg", + "currency": "Euro" + }, + { + "name": "Saint Pierre and Miquelon", + "capital": "Saint-Pierre", + "languages": [ + "French" + ], + "population": 6069, + "flag": "https://restcountries.eu/data/spm.svg", + "currency": "Euro" + }, + { + "name": "Saint Vincent and the Grenadines", + "capital": "Kingstown", + "languages": [ + "English" + ], + "population": 109991, + "flag": "https://restcountries.eu/data/vct.svg", + "currency": "East Caribbean dollar" + }, + { + "name": "Samoa", + "capital": "Apia", + "languages": [ + "Samoan", + "English" + ], + "population": 194899, + "flag": "https://restcountries.eu/data/wsm.svg", + "currency": "Samoan tālā" + }, + { + "name": "San Marino", + "capital": "City of San Marino", + "languages": [ + "Italian" + ], + "population": 33005, + "flag": "https://restcountries.eu/data/smr.svg", + "currency": "Euro" + }, + { + "name": "Sao Tome and Principe", + "capital": "São Tomé", + "languages": [ + "Portuguese" + ], + "population": 187356, + "flag": "https://restcountries.eu/data/stp.svg", + "currency": "São Tomé and Príncipe dobra" + }, + { + "name": "Saudi Arabia", + "capital": "Riyadh", + "languages": [ + "Arabic" + ], + "population": 32248200, + "flag": "https://restcountries.eu/data/sau.svg", + "currency": "Saudi riyal" + }, + { + "name": "Senegal", + "capital": "Dakar", + "languages": [ + "French" + ], + "population": 14799859, + "flag": "https://restcountries.eu/data/sen.svg", + "currency": "West African CFA franc" + }, + { + "name": "Serbia", + "capital": "Belgrade", + "languages": [ + "Serbian" + ], + "population": 7076372, + "flag": "https://restcountries.eu/data/srb.svg", + "currency": "Serbian dinar" + }, + { + "name": "Seychelles", + "capital": "Victoria", + "languages": [ + "French", + "English" + ], + "population": 91400, + "flag": "https://restcountries.eu/data/syc.svg", + "currency": "Seychellois rupee" + }, + { + "name": "Sierra Leone", + "capital": "Freetown", + "languages": [ + "English" + ], + "population": 7075641, + "flag": "https://restcountries.eu/data/sle.svg", + "currency": "Sierra Leonean leone" + }, + { + "name": "Singapore", + "capital": "Singapore", + "languages": [ + "English", + "Malay", + "Tamil", + "Chinese" + ], + "population": 5535000, + "flag": "https://restcountries.eu/data/sgp.svg", + "currency": "Brunei dollar" + }, + { + "name": "Sint Maarten (Dutch part)", + "capital": "Philipsburg", + "languages": [ + "Dutch", + "English" + ], + "population": 38247, + "flag": "https://restcountries.eu/data/sxm.svg", + "currency": "Netherlands Antillean guilder" + }, + { + "name": "Slovakia", + "capital": "Bratislava", + "languages": [ + "Slovak" + ], + "population": 5426252, + "flag": "https://restcountries.eu/data/svk.svg", + "currency": "Euro" + }, + { + "name": "Slovenia", + "capital": "Ljubljana", + "languages": [ + "Slovene" + ], + "population": 2064188, + "flag": "https://restcountries.eu/data/svn.svg", + "currency": "Euro" + }, + { + "name": "Solomon Islands", + "capital": "Honiara", + "languages": [ + "English" + ], + "population": 642000, + "flag": "https://restcountries.eu/data/slb.svg", + "currency": "Solomon Islands dollar" + }, + { + "name": "Somalia", + "capital": "Mogadishu", + "languages": [ + "Somali", + "Arabic" + ], + "population": 11079000, + "flag": "https://restcountries.eu/data/som.svg", + "currency": "Somali shilling" + }, + { + "name": "South Africa", + "capital": "Pretoria", + "languages": [ + "Afrikaans", + "English", + "Southern Ndebele", + "Southern Sotho", + "Swati", + "Tswana", + "Tsonga", + "Venda", + "Xhosa", + "Zulu" + ], + "population": 55653654, + "flag": "https://restcountries.eu/data/zaf.svg", + "currency": "South African rand" + }, + { + "name": "South Georgia and the South Sandwich Islands", + "capital": "King Edward Point", + "languages": [ + "English" + ], + "population": 30, + "flag": "https://restcountries.eu/data/sgs.svg", + "currency": "British pound" + }, + { + "name": "Korea (Republic of)", + "capital": "Seoul", + "languages": [ + "Korean" + ], + "population": 50801405, + "flag": "https://restcountries.eu/data/kor.svg", + "currency": "South Korean won" + }, + { + "name": "South Sudan", + "capital": "Juba", + "languages": [ + "English" + ], + "population": 12131000, + "flag": "https://restcountries.eu/data/ssd.svg", + "currency": "South Sudanese pound" + }, + { + "name": "Spain", + "capital": "Madrid", + "languages": [ + "Spanish" + ], + "population": 46438422, + "flag": "https://restcountries.eu/data/esp.svg", + "currency": "Euro" + }, + { + "name": "Sri Lanka", + "capital": "Colombo", + "languages": [ + "Sinhalese", + "Tamil" + ], + "population": 20966000, + "flag": "https://restcountries.eu/data/lka.svg", + "currency": "Sri Lankan rupee" + }, + { + "name": "Sudan", + "capital": "Khartoum", + "languages": [ + "Arabic", + "English" + ], + "population": 39598700, + "flag": "https://restcountries.eu/data/sdn.svg", + "currency": "Sudanese pound" + }, + { + "name": "Suriname", + "capital": "Paramaribo", + "languages": [ + "Dutch" + ], + "population": 541638, + "flag": "https://restcountries.eu/data/sur.svg", + "currency": "Surinamese dollar" + }, + { + "name": "Svalbard and Jan Mayen", + "capital": "Longyearbyen", + "languages": [ + "Norwegian" + ], + "population": 2562, + "flag": "https://restcountries.eu/data/sjm.svg", + "currency": "Norwegian krone" + }, + { + "name": "Swaziland", + "capital": "Lobamba", + "languages": [ + "English", + "Swati" + ], + "population": 1132657, + "flag": "https://restcountries.eu/data/swz.svg", + "currency": "Swazi lilangeni" + }, + { + "name": "Sweden", + "capital": "Stockholm", + "languages": [ + "Swedish" + ], + "population": 9894888, + "flag": "https://restcountries.eu/data/swe.svg", + "currency": "Swedish krona" + }, + { + "name": "Switzerland", + "capital": "Bern", + "languages": [ + "German", + "French", + "Italian" + ], + "population": 8341600, + "flag": "https://restcountries.eu/data/che.svg", + "currency": "Swiss franc" + }, + { + "name": "Syrian Arab Republic", + "capital": "Damascus", + "languages": [ + "Arabic" + ], + "population": 18564000, + "flag": "https://restcountries.eu/data/syr.svg", + "currency": "Syrian pound" + }, + { + "name": "Taiwan", + "capital": "Taipei", + "languages": [ + "Chinese" + ], + "population": 23503349, + "flag": "https://restcountries.eu/data/twn.svg", + "currency": "New Taiwan dollar" + }, + { + "name": "Tajikistan", + "capital": "Dushanbe", + "languages": [ + "Tajik", + "Russian" + ], + "population": 8593600, + "flag": "https://restcountries.eu/data/tjk.svg", + "currency": "Tajikistani somoni" + }, + { + "name": "Tanzania, United Republic of", + "capital": "Dodoma", + "languages": [ + "Swahili", + "English" + ], + "population": 55155000, + "flag": "https://restcountries.eu/data/tza.svg", + "currency": "Tanzanian shilling" + }, + { + "name": "Thailand", + "capital": "Bangkok", + "languages": [ + "Thai" + ], + "population": 65327652, + "flag": "https://restcountries.eu/data/tha.svg", + "currency": "Thai baht" + }, + { + "name": "Timor-Leste", + "capital": "Dili", + "languages": [ + "Portuguese" + ], + "population": 1167242, + "flag": "https://restcountries.eu/data/tls.svg", + "currency": "United States dollar" + }, + { + "name": "Togo", + "capital": "Lomé", + "languages": [ + "French" + ], + "population": 7143000, + "flag": "https://restcountries.eu/data/tgo.svg", + "currency": "West African CFA franc" + }, + { + "name": "Tokelau", + "capital": "Fakaofo", + "languages": [ + "English" + ], + "population": 1411, + "flag": "https://restcountries.eu/data/tkl.svg", + "currency": "New Zealand dollar" + }, + { + "name": "Tonga", + "capital": "Nuku'alofa", + "languages": [ + "English", + "Tonga (Tonga Islands)" + ], + "population": 103252, + "flag": "https://restcountries.eu/data/ton.svg", + "currency": "Tongan paʻanga" + }, + { + "name": "Trinidad and Tobago", + "capital": "Port of Spain", + "languages": [ + "English" + ], + "population": 1349667, + "flag": "https://restcountries.eu/data/tto.svg", + "currency": "Trinidad and Tobago dollar" + }, + { + "name": "Tunisia", + "capital": "Tunis", + "languages": [ + "Arabic" + ], + "population": 11154400, + "flag": "https://restcountries.eu/data/tun.svg", + "currency": "Tunisian dinar" + }, + { + "name": "Turkey", + "capital": "Ankara", + "languages": [ + "Turkish" + ], + "population": 78741053, + "flag": "https://restcountries.eu/data/tur.svg", + "currency": "Turkish lira" + }, + { + "name": "Turkmenistan", + "capital": "Ashgabat", + "languages": [ + "Turkmen", + "Russian" + ], + "population": 4751120, + "flag": "https://restcountries.eu/data/tkm.svg", + "currency": "Turkmenistan manat" + }, + { + "name": "Turks and Caicos Islands", + "capital": "Cockburn Town", + "languages": [ + "English" + ], + "population": 31458, + "flag": "https://restcountries.eu/data/tca.svg", + "currency": "United States dollar" + }, + { + "name": "Tuvalu", + "capital": "Funafuti", + "languages": [ + "English" + ], + "population": 10640, + "flag": "https://restcountries.eu/data/tuv.svg", + "currency": "Australian dollar" + }, + { + "name": "Uganda", + "capital": "Kampala", + "languages": [ + "English", + "Swahili" + ], + "population": 33860700, + "flag": "https://restcountries.eu/data/uga.svg", + "currency": "Ugandan shilling" + }, + { + "name": "Ukraine", + "capital": "Kiev", + "languages": [ + "Ukrainian" + ], + "population": 42692393, + "flag": "https://restcountries.eu/data/ukr.svg", + "currency": "Ukrainian hryvnia" + }, + { + "name": "United Arab Emirates", + "capital": "Abu Dhabi", + "languages": [ + "Arabic" + ], + "population": 9856000, + "flag": "https://restcountries.eu/data/are.svg", + "currency": "United Arab Emirates dirham" + }, + { + "name": "United Kingdom of Great Britain and Northern Ireland", + "capital": "London", + "languages": [ + "English" + ], + "population": 65110000, + "flag": "https://restcountries.eu/data/gbr.svg", + "currency": "British pound" + }, + { + "name": "United States of America", + "capital": "Washington, D.C.", + "languages": [ + "English" + ], + "population": 323947000, + "flag": "https://restcountries.eu/data/usa.svg", + "currency": "United States dollar" + }, + { + "name": "Uruguay", + "capital": "Montevideo", + "languages": [ + "Spanish" + ], + "population": 3480222, + "flag": "https://restcountries.eu/data/ury.svg", + "currency": "Uruguayan peso" + }, + { + "name": "Uzbekistan", + "capital": "Tashkent", + "languages": [ + "Uzbek", + "Russian" + ], + "population": 31576400, + "flag": "https://restcountries.eu/data/uzb.svg", + "currency": "Uzbekistani so'm" + }, + { + "name": "Vanuatu", + "capital": "Port Vila", + "languages": [ + "Bislama", + "English", + "French" + ], + "population": 277500, + "flag": "https://restcountries.eu/data/vut.svg", + "currency": "Vanuatu vatu" + }, + { + "name": "Venezuela (Bolivarian Republic of)", + "capital": "Caracas", + "languages": [ + "Spanish" + ], + "population": 31028700, + "flag": "https://restcountries.eu/data/ven.svg", + "currency": "Venezuelan bolívar" + }, + { + "name": "Viet Nam", + "capital": "Hanoi", + "languages": [ + "Vietnamese" + ], + "population": 92700000, + "flag": "https://restcountries.eu/data/vnm.svg", + "currency": "Vietnamese đồng" + }, + { + "name": "Wallis and Futuna", + "capital": "Mata-Utu", + "languages": [ + "French" + ], + "population": 11750, + "flag": "https://restcountries.eu/data/wlf.svg", + "currency": "CFP franc" + }, + { + "name": "Western Sahara", + "capital": "El Aaiún", + "languages": [ + "Spanish" + ], + "population": 510713, + "flag": "https://restcountries.eu/data/esh.svg", + "currency": "Moroccan dirham" + }, + { + "name": "Yemen", + "capital": "Sana'a", + "languages": [ + "Arabic" + ], + "population": 27478000, + "flag": "https://restcountries.eu/data/yem.svg", + "currency": "Yemeni rial" + }, + { + "name": "Zambia", + "capital": "Lusaka", + "languages": [ + "English" + ], + "population": 15933883, + "flag": "https://restcountries.eu/data/zmb.svg", + "currency": "Zambian kwacha" + }, + { + "name": "Zimbabwe", + "capital": "Harare", + "languages": [ + "English", + "Shona", + "Northern Ndebele" + ], + "population": 14240168, + "flag": "https://restcountries.eu/data/zwe.svg", + "currency": "Botswana pula" + } +] \ No newline at end of file From c5cfa57c2e044197f49eafe12bf2ec1c6996b804 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Thu, 7 Oct 2021 00:51:24 +0530 Subject: [PATCH 10/23] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f9580a2..bc10040 100644 --- a/README.md +++ b/README.md @@ -81,9 +81,9 @@ Go [**`here`**](https://github.com/milaan9/03_Python_Flow_Control) if you aren't ![Download ZIP](img/dnld_rep.png) -3. Extract the ZIP and open it. Unfortunately I don't have any more specific instructions because how exactly this is done depends on which operating system you run. +2. Extract the ZIP and open it. Unfortunately I don't have any more specific instructions because how exactly this is done depends on which operating system you run. -4. Launch ipython notebook from the folder which contains the notebooks. Open each one of them +3. Launch ipython notebook from the folder which contains the notebooks. Open each one of them **`Kernel > Restart & Clear Output`** From d58e9a95b52733fa32c58c57ff9b29cb4331b8aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Mon, 11 Oct 2021 20:24:58 +0530 Subject: [PATCH 11/23] Delete 007_Python_break_continue_pass_statements.ipynb --- ...ython_break_continue_pass_statements.ipynb | 1308 ----------------- 1 file changed, 1308 deletions(-) delete mode 100644 007_Python_break_continue_pass_statements.ipynb diff --git a/007_Python_break_continue_pass_statements.ipynb b/007_Python_break_continue_pass_statements.ipynb deleted file mode 100644 index e583bb5..0000000 --- a/007_Python_break_continue_pass_statements.ipynb +++ /dev/null @@ -1,1308 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "All the IPython Notebooks in this lecture series by Dr. Milan Parmar are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)**\n", - "" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Control Statements in Python\n", - "\n", - "As you may know, loops in Python are used to iterate repeatedly over a block of code. But at times, you might want to **shift the control once a particular condition is satisfied**. This is where control statements in Python come into the picture.\n", - "\n", - "Control statements in python are **used to control the flow of execution of the program based on the specified conditions**. Python supports **3 types of control statements**:\n", - "\n", - "| | Statement | Description |\n", - "|:----|:----| :--- |\n", - "|1| **`break`** | Terminate the current loop. Use the **`break`** statement to come out of the loop instantly. |\n", - "|2| **`continue`** | Skip the current iteration of a loop and move to the next iteration |\n", - "|3| **`pass`** | Do nothing. Ignore the condition in which it occurred and proceed to run the program as usual |\n", - "\n", - "Loops iterate over a block of code until the test expression is **`False`**, but sometimes we wish to terminate the current iteration or even the whole loop without checking test expression.\n", - "\n", - "The **`break`** and **`continue`** statements are part of a control flow statements that helps you to understand the basics of Python.\n", - "\n", - "
\n", - "\n", - "
" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# 1. Python `break` statement\n", - "\n", - "In Python, the **`break`** statement provides you with the opportunity to **exit out** of a loop when an external condition is **triggered**, and the program control transfer to the next statement following the loop.\n", - "\n", - "If the **`break`** statement is inside a nested loop (loop inside another loop), the **`break`** statement will terminate the innermost loop.\n", - "\n", - "You’ll put the **`break`** statement within the block of code under your loop statement, usually after a conditional **[if statement](https://github.com/milaan9/03_Python_Flow_Control/blob/main/001_Python_if_statement.ipynb)**. This statement can only be used in **[for loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/005_Python_for_Loop.ipynb)** and **[while loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/006_Python_while_Loop.ipynb)**.\n", - "\n", - "
\n", - "\n", - "
\n", - "\n", - "The working of **`break`** statement in **`for`** loop and **`while`** loop is shown below.\n", - "\n", - "
\n", - "\n", - "
" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:08:12.834872Z", - "start_time": "2021-06-12T16:08:12.824130Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "current number 10\n", - "current number 30\n" - ] - } - ], - "source": [ - "# Example 1:\n", - "\n", - "numbers = [10, 30, 120, 330]\n", - "for i in numbers:\n", - " if i > 100:\n", - " break\n", - " print('current number', i)" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:08:13.037991Z", - "start_time": "2021-06-12T16:08:13.020416Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Number is 1\n", - "Number is 2\n", - "Number is 3\n", - "Number is 4\n", - "Out of loop\n" - ] - } - ], - "source": [ - "# Example 2: Let’s look at an example that uses the break statement in a `for` loop\n", - "\n", - "number = 0\n", - "for number in range(10):\n", - " number = number + 1\n", - " if number == 5:\n", - " break # break here\n", - " print('Number is ' + str(number))\n", - "print('Out of loop')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "1. In this small program, the variable number is initialized at **`0`**. Then a **`for`** statement constructs the loop as long as the variable number is **less than 10**.\n", - "\n", - "2. Within the **`for`** loop, the number increases incrementally by **`1`** with each pass because of the line **number = number + 1**.\n", - "\n", - "3. Then, there is an **`if`** statement that presents the condition that if the variable number is **equivalent** to the integer **`5`**, then the loop will break.\n", - "\n", - "4. Within the loop is also a **[print()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/051_Python_print%28%29.ipynb)** statement that will execute with each iteration of the **`for`** loop until the loop breaks, since it is after the **`break`** statement.\n", - "\n", - "5. To see when we are out of the loop, we have included a final **`print()`** statement outside of the **`for`** loop.\n", - "\n", - "This shows that once the integer number is evaluated as equivalent to **`5`**, the loop breaks, as the program is told to do so with the **`break`** statement." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Nested `break` loops" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 1. `break` Statement in Nested Loop\n", - "\n", - "To terminate the nested loop, use a **`break`** statement inside the inner loop. For example:" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:08:13.736228Z", - "start_time": "2021-06-12T16:08:13.719632Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "0...1...2...3...4...5...6...7...8...9...10...completed.\n" - ] - } - ], - "source": [ - "# Example 1:\n", - "\n", - "for i in range(100):\n", - " print(i,end=\"...\")\n", - " if i>=10:\n", - " break\n", - "print(\"completed.\")" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:08:13.954002Z", - "start_time": "2021-06-12T16:08:13.938378Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "s\n", - "t\n", - "r\n", - "The end\n" - ] - } - ], - "source": [ - "# Example 2: Use of break statement inside the loop\n", - "\n", - "for val in \"string\":\n", - " if val == \"i\":\n", - " break\n", - " print(val)\n", - "print(\"The end\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "In this program, we iterate through the \"**`string`**\" sequence. We check if the letter is **`i`**, upon which we break from the loop. Hence, we see in our output that all the letters up till **`i`** gets printed. After that, the loop terminates." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Print the letters in \"HELLOWORLD\" one by one untill the letter R is reached using break statement in Python." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:08:14.842176Z", - "start_time": "2021-06-12T16:08:14.824110Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "H\n", - "E\n", - "L\n", - "L\n", - "O\n", - "W\n", - "O\n", - "untill letter R printed\n" - ] - } - ], - "source": [ - "# Example 3: \n", - "\n", - "for letter in \"HELLOWORLD\": # letter is a variable which could have been with any name. each iteration the letter is advanced in the string \"FACEPREP\" and stored in variable letter.\n", - " if letter == \"R\": #check for condition\n", - " break # if condition true, then break out of the loop and print the final print statement.\n", - " print(letter) # if condition false, then print that letter.\n", - "print('untill letter R printed') #once the for loop is terminated, print this. \n", - "\n", - "# Note: observe the indentations carefully" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:08:22.314280Z", - "start_time": "2021-06-12T16:08:15.161023Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Enter a word: Happy\n", - "A not found\n" - ] - } - ], - "source": [ - "# Example 4: program to check if letter 'A' is present in the input\n", - "\n", - "a = input (\"Enter a word: \")\n", - "for i in a:\n", - " if (i == 'A'):\n", - " print (\"A is found\")\n", - " break \n", - "else:\n", - " print (\"A not found\")\n", - " \n", - "# Note: Python is case-sensitive language." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:08:22.376783Z", - "start_time": "2021-06-12T16:08:22.364087Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "A l a n 9 9 " - ] - } - ], - "source": [ - "# Example 5: bested `while` loop with `break`\n", - "\n", - "name = 'Alan99 White'\n", - "\n", - "size = len(name)\n", - "i = 0\n", - "# iterate loop till the last character\n", - "while i < size:\n", - " # break loop if current character is space\n", - " if name[i].isspace():\n", - " break\n", - " # print current character\n", - " print(name[i], end=' ')\n", - " i = i + 1" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:08:27.087188Z", - "start_time": "2021-06-12T16:08:27.056921Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Multiplication table of 1\n", - "1 2 3 4 5 6 7 8 9 10 \n", - "Multiplication table of 2\n", - "2 4 6 8 10 12 14 16 18 20 \n", - "Multiplication table of 3\n", - "3 6 9 12 15 18 21 24 27 30 \n", - "Multiplication table of 4\n", - "4 8 12 16 20 24 28 32 36 40 \n", - "Multiplication table of 5\n", - "5 10 15 20 25 30 35 40 45 50 \n", - "Multiplication table of 6\n", - "6 12 18 24 30 \n", - "Multiplication table of 7\n", - "7 14 21 28 35 \n", - "Multiplication table of 8\n", - "8 16 24 32 40 \n", - "Multiplication table of 9\n", - "9 18 27 36 45 \n", - "Multiplication table of 10\n", - "10 20 30 40 50 \n" - ] - } - ], - "source": [ - "# Example 6:\n", - "\n", - "for i in range(1, 11):\n", - " print('Multiplication table of', i)\n", - " for j in range(1, 11):\n", - " # condition to break inner loop\n", - " if i > 5 and j > 5:\n", - " break\n", - " print(i * j, end=' ')\n", - " print('')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "We have two loops, the outer loop, and the inner loop. The outer for loop iterates the first 10 numbers using the **[range()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/053_Python_range%28%29.ipynb)** function, and the internal loop prints the multiplication table of each number.\n", - "\n", - "But if the current number of both the outer loop and the inner loop is greater than 5 then terminate the inner loop using the **`break`** statement." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 2. `break` Statement in Outer Loop\n", - "\n", - "To terminate the outside loop, use a **`break`** statement inside the outer loop. For example:" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:08:29.111587Z", - "start_time": "2021-06-12T16:08:29.095964Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Multiplication table of 1\n", - "1 2 3 4 5 6 7 8 9 10 \n", - "Multiplication table of 2\n", - "2 4 6 8 10 12 14 16 18 20 \n", - "Multiplication table of 3\n", - "3 6 9 12 15 18 21 24 27 30 \n", - "Multiplication table of 4\n", - "4 8 12 16 20 24 28 32 36 40 \n", - "Multiplication table of 5\n", - "5 10 15 20 25 30 35 40 45 50 \n" - ] - } - ], - "source": [ - "# Example 1: Break nested loop\n", - "\n", - "for i in range(1, 11):\n", - " # condition to break outer loop\n", - " if i > 5:\n", - " break\n", - " print('Multiplication table of', i)\n", - " for j in range(1, 11):\n", - " print(i * j, end=' ')\n", - " print('')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "We have two loops, the outer loop, and the inner loop. The outer loop iterates the first 10 numbers, and the internal loop prints the multiplication table of each number.\n", - "\n", - "But if the current number of the outer loop is greater than 5 then terminate the outer loop using the **`break`** statement." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:08:30.062754Z", - "start_time": "2021-06-12T16:08:30.048105Z" - }, - "scrolled": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Current Number is: 3\n", - "Square of a current number is: 9\n", - "Current Number is: 6\n", - "Square of a current number is: 36\n", - "Current Number is: 12\n", - "Current Number is: 9\n", - "Square of a current number is: 81\n" - ] - } - ], - "source": [ - "# Example 2:\n", - "\n", - "numbers = [3, 6, 12, 9]\n", - "for i in numbers:\n", - " print('Current Number is:', i)\n", - " # skip below statement if number is greater than 10\n", - " if i > 10:\n", - " continue\n", - " square = i * i\n", - " print('Square of a current number is:', square)" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:08:30.717046Z", - "start_time": "2021-06-12T16:08:30.705325Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "3\n", - "5\n", - "End of Loop\n" - ] - } - ], - "source": [ - "# Example 3: Python Continue Statement Example:\n", - "\n", - "a=0\n", - "\n", - "while a<=5:\n", - " a=a+1\n", - " if a%2==0: \n", - " continue\n", - " print (a)\n", - "print (\"End of Loop\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "You can use the **`continue`** statement to avoid deeply nested conditional code, or to optimize a loop by eliminating frequently occurring cases that you would like to reject.\n", - "\n", - "The **`continue`** statement causes a program to skip certain factors that come up within a loop, but then continue through the rest of the loop." - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:08:32.292716Z", - "start_time": "2021-06-12T16:08:32.273183Z" - }, - "scrolled": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "s\n", - "t\n", - "r\n", - "n\n", - "g\n", - "The end\n" - ] - } - ], - "source": [ - "# Example 4: Program to show the use of continue statement inside loops\n", - "\n", - "for val in \"string\":\n", - " if val == \"i\":\n", - " continue\n", - " print(val)\n", - "\n", - "print(\"The end\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation**:\n", - "\n", - "This program is same as the above example except the **`break`** statement has been replaced with **`continue`**.\n", - "\n", - "We continue with the loop, if the string is **`i`**, not executing the rest of the block. Hence, we see in our output that all the letters except **`i`** gets printed." - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:08:33.883035Z", - "start_time": "2021-06-12T16:08:33.872290Z" - }, - "scrolled": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Processed 0\n", - "Processed 1\n", - "Processed 2\n", - "Processed 3\n", - "Processed 4\n", - "Ignored 5\n", - "Ignored 6\n", - "Ignored 7\n", - "Ignored 8\n", - "Ignored 9\n" - ] - } - ], - "source": [ - "# Example 5:\n", - "\n", - "for i in range(10):\n", - " if i>4:\n", - " print(\"Ignored\",i)\n", - " continue\n", - " # this statement is not reach if i > 4\n", - " print(\"Processed\",i)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Write a program to skip all \"O\"s in a given string \"HELLOWORLD\"" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:08:34.880584Z", - "start_time": "2021-06-12T16:08:34.863981Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "H\n", - "e\n", - "l\n", - "l\n", - "o\n", - "W\n", - "o\n", - "r\n", - "l\n", - "d\n", - "The End\n" - ] - } - ], - "source": [ - "# Example 6:\n", - "\n", - "for letters in \"HelloWorld\": # for every letter in FACEPREP\n", - " if letters == \"O\": # if letter is E, then skip printing the letter and go to the next iteration with the next alphabet\n", - " continue # Remember that loop is not terminated like break statement.\n", - " print(letters)\n", - "print(\"The End\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# 2. Python `continue` statement\n", - "\n", - "In Python, the **`continue`** statement is a **jump statement** which is used to skip execution of current iteration. After **skipping**, loop **`continue`** with next iteration. We can use **`continue`** statement **only** with **[for loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/005_Python_for_Loop.ipynb)** as well as **[while loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/006_Python_while_Loop.ipynb)** in Python. It is typically **only** used within an **[if statement](https://github.com/milaan9/03_Python_Flow_Control/blob/main/001_Python_if_statement.ipynb)** (otherwise the remainder of the loop would never be executed).\n", - "\n", - "
\n", - "\n", - "
\n", - "\n", - "The working of **`continue`** statement in **`for`** loop and **`while`** loop is shown below.\n", - "\n", - "
\n", - "\n", - "
" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## `continue` statement in `while` loop\n", - "\n", - "We can also use the **`continue`** statement inside a **`while`** loop. For example:\n", - "\n", - "Write a **[while loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/006_Python_while_Loop.ipynb)** to display each character from a string and if a character is a space, then don’t display it and move to the next character.\n", - "\n", - "Use the if condition with the **`continue`** statement to jump to the next iteration. If the current character is space, then the condition evaluates to true, then the **`continue`** statement will execute, and the loop will move to the next iteration by skipping the remeaning body." - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:08:38.606624Z", - "start_time": "2021-06-12T16:08:38.592955Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "A r t h u r " - ] - } - ], - "source": [ - "# Example 1: use the `continue` statement inside a `while` loop\n", - "\n", - "name = 'Art hu r'\n", - "\n", - "size = len(name)\n", - "i = -1\n", - "# iterate loop till the last character\n", - "while i < size - 1:\n", - " i = i + 1\n", - " # skip loop body if current character is space\n", - " if name[i].isspace():\n", - " continue\n", - " # print current character\n", - " print(name[i], end=' ')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## `continue` statement with `else` statements\n", - "\n", - "Sometimes we want to know if a loop exited 'normally' or via a **`break`** statement. This can be achieved with an **`else:`** statement in a loop which only executes if there was no **`break`** statement." - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:08:51.357492Z", - "start_time": "2021-06-12T16:08:39.913255Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Enter a word: Honey is sweet\n" - ] - } - ], - "source": [ - "# Example 1: program to check if letter 'A' is present in the input\n", - "\n", - "a = input (\"Enter a word: \")\n", - "for i in a:\n", - " if(i != 'A'): \n", - " continue \n", - " else:\n", - " print(\"A is found\")\n", - " break\n", - " print(\"A is not found\")\n", - " \n", - "# Enter a word: Honey is sweet" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:09:00.030274Z", - "start_time": "2021-06-12T16:08:53.753959Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Enter a word: Honey is sweet\n", - "A is not found\n" - ] - } - ], - "source": [ - "# Example 1 :without using continue\n", - "\n", - "a = input (\"Enter a word: \")\n", - "for i in a:\n", - " if (i == 'A'):\n", - " print(\"A is found\")\n", - " break\n", - "else:\n", - " print (\"A is not found\")\n", - " \n", - "# Enter a word: Honey is sweet" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:09:06.199166Z", - "start_time": "2021-06-12T16:09:06.188425Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "count = 1\n", - "count = 5\n", - "count = 9\n", - "Normal exit with 12\n" - ] - } - ], - "source": [ - "# Example 2:\n", - "\n", - "count = 0\n", - "while count < 10:\n", - " count += 1\n", - " if count % 2 == 0: # even number\n", - " count += 2\n", - " continue\n", - " elif 5 < count < 9:\n", - " break # abnormal exit if we get here!\n", - " print(\"count =\",count)\n", - "else: # while-else\n", - " print(\"Normal exit with\",count)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Nested `continue` loops" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 1. `continue` Statement in Nested Loop\n", - "\n", - "To skip the current iteration of the nested loop, use the **`continue`** statement inside the body of the inner loop. For example:" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:09:08.793873Z", - "start_time": "2021-06-12T16:09:08.770437Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Multiplication table of 1\n", - "1 2 3 4 6 7 8 9 10 \n", - "Multiplication table of 2\n", - "2 4 6 8 12 14 16 18 20 \n", - "Multiplication table of 3\n", - "3 6 9 12 18 21 24 27 30 \n", - "Multiplication table of 4\n", - "4 8 12 16 24 28 32 36 40 \n", - "Multiplication table of 5\n", - "5 10 15 20 30 35 40 45 50 \n", - "Multiplication table of 6\n", - "6 12 18 24 36 42 48 54 60 \n", - "Multiplication table of 7\n", - "7 14 21 28 42 49 56 63 70 \n", - "Multiplication table of 8\n", - "8 16 24 32 48 56 64 72 80 \n", - "Multiplication table of 9\n", - "9 18 27 36 54 63 72 81 90 \n", - "Multiplication table of 10\n", - "10 20 30 40 60 70 80 90 100 \n" - ] - } - ], - "source": [ - "# Example 1: `continue` statement in nested loop\n", - "\n", - "for i in range(1, 11):\n", - " print('Multiplication table of', i)\n", - " for j in range(1, 11):\n", - " # condition to skip current iteration\n", - " if j == 5:\n", - " continue\n", - " print(i * j, end=' ')\n", - " print('')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "We have the outer loop and the inner loop. The outer loop iterates the first 10 numbers, and the internal loop prints the multiplication table of each number.\n", - "\n", - "But if the current number of the inner loop is equal to 5, then skip the current iteration and move to the next iteration of the inner loop using the **`continue`** statement." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 2. `continue` Statement in Outer Loop\n", - "\n", - "To skip the current iteration of an outside loop, use the **`continue`** statement inside the outer loop. For example:" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:09:11.154202Z", - "start_time": "2021-06-12T16:09:11.131744Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Multiplication table of 1\n", - "1 2 3 4 5 6 7 8 9 10 \n", - "Multiplication table of 3\n", - "3 6 9 12 15 18 21 24 27 30 \n", - "Multiplication table of 5\n", - "5 10 15 20 25 30 35 40 45 50 \n", - "Multiplication table of 7\n", - "7 14 21 28 35 42 49 56 63 70 \n", - "Multiplication table of 9\n", - "9 18 27 36 45 54 63 72 81 90 \n" - ] - } - ], - "source": [ - "# Example 1: `continue` statement in outer loop\n", - "\n", - "for i in range(1, 11):\n", - " # condition to skip iteration\n", - " # Don't print multiplication table of even numbers\n", - " if i % 2 == 0:\n", - " continue\n", - " print('Multiplication table of', i)\n", - " for j in range(1, 11):\n", - " print(i * j, end=' ')\n", - " print('')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "The outer loop iterates the first 10 numbers, and the internal loop prints the multiplication table of each number.\n", - "\n", - "But if the current number of the outer loop is even, then skip the current iteration of the outer loop and move to the next iteration.\n", - "\n", - ">**Note:** If we skip the current iteration of an outer loop, the inner loop will not be executed for that iteration because the inner loop is part of the body of an outer loop." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Catching exceptions with `continue` statement\n", - "\n", - "Sometimes it is desirable to deal with errors without stopping the whole program. This can be achieved using a **try** statement. Appart from dealing with with system errors, it also alows aborting from somewhere deep down in nested execution. It is possible to attach multiple error handlers depending on the type of the exception\n", - "\n", - "```python\n", - "try:\n", - " code\n", - "except as :\n", - " # deal with error of this type\n", - "except:\n", - " # deal with any error\n", - "finally:\n", - " # execute irrespective of whether an exception occured or not\n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:09:14.039436Z", - "start_time": "2021-06-12T16:09:14.025766Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Looping\n", - "Looping\n", - "Looping\n", - "Looping\n", - "Caught exception: abort\n", - "All done\n" - ] - } - ], - "source": [ - "try:\n", - " count=0\n", - " while True:\n", - " while True:\n", - " while True:\n", - " print(\"Looping\")\n", - " count = count + 1\n", - " if count > 3:\n", - " raise Exception(\"abort\") # exit every loop or function\n", - " if count > 4:\n", - " raise StopIteration(\"I'm bored\") # built in exception type\n", - "except StopIteration as e:\n", - " print(\"Stopped iteration:\",e)\n", - "except Exception as e: # this is where we go when an exception is raised\n", - " print(\"Caught exception:\",e)\n", - "finally:\n", - " print(\"All done\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This can also be useful to handle unexpected system errors more gracefully:" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:09:14.897340Z", - "start_time": "2021-06-12T16:09:14.890500Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Cannot calculate inverse because: float division by zero\n" - ] - } - ], - "source": [ - "try:\n", - " for i in [2,1.5,0.0,3]:\n", - " inverse = 1.0/i\n", - "except Exception as e: # no matter what exception\n", - " print(\"Cannot calculate inverse because:\", e)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# 3. Python `pass` statement\n", - "\n", - "In Python, **`pass`** keyword is used to execute **nothing**; it means, when we don't want to execute code, the pass can be used to execute empty. It is same as the name refers to. It just makes the control to pass by without executing any code. If we want to bypass any code pass statement can be used.\n", - "\n", - "It is used as a placeholder for future implementation of functions, loops, etc.\n", - "\n", - "Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They cannot have an empty body. The interpreter would give an error. So, we use the **`pass`** statement to construct a body that does nothing.\n", - "\n", - "### Example:\n", - "\n", - "```python\n", - "'''pass is just a placeholder for\n", - "functionality to be added later.'''\n", - ">>> sequence = {'p', 'a', 's', 's'}\n", - ">>> for val in sequence:\n", - ">>> pass\n", - "```\n", - "\n", - "We can do the same thing in an empty **function** or **class** as well.\n", - "\n", - "```python\n", - ">>> def function(args):\n", - ">>> pass\n", - "```\n", - "or\n", - "```python\n", - ">>> class Example:\n", - ">>> pass\n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:09:17.500828Z", - "start_time": "2021-06-12T16:09:17.481302Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "['January', 'June', 'March', 'April']\n" - ] - } - ], - "source": [ - "# Example 1:\n", - "\n", - "months = ['January', 'June', 'March', 'April']\n", - "for mon in months:\n", - " pass\n", - "print(months)" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-12T16:09:18.217623Z", - "start_time": "2021-06-12T16:09:18.195650Z" - }, - "scrolled": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Number is 1\n", - "Number is 2\n", - "Number is 3\n", - "Number is 4\n", - "Number is 5\n", - "Number is 6\n", - "Number is 7\n", - "Number is 8\n", - "Number is 9\n", - "Number is 10\n", - "Out of loop\n" - ] - } - ], - "source": [ - "# Example 2: Python Pass Statement\n", - "\n", - "number = 0\n", - "\n", - "for number in range(10):\n", - " number = number + 1\n", - " if number == 5:\n", - " pass # pass here\n", - " print('Number is ' + str(number))\n", - "print('Out of loop')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation**:\n", - "\n", - "By using the **`pass`** statement in this program, we notice that the program runs exactly as it would if there were no conditional statement in the program. The **`pass`** statement tells the program to **disregard that condition** and **continue to run** the program as usual." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Control Statements in Python FAQs\n", - "\n", - "1. How many control statements are present in Python?\n", - "> In Python, there are 3 types of control statements. Namely, break, continue and pass statements.\n", - "\n", - "2. How to break from a loop in Python?\n", - ">The keyword break is used to break or terminate from the current loop. The control shifts to the next statement outside the loop.\n", - "\n", - "3. What is the difference between break and continue statements in Python?\n", - ">Break statement exits out of the loop, but the continue statement shifts the control to the next iteration and doesn’t exit out of the loop.\n", - "\n", - "4. Can we use continue in if statement in Python?\n", - ">Yes. Continue statements can be used within an if statement.\n", - "\n", - "5. What is the use of pass keyword in Python?\n", - ">Pass keyword helps in avoiding errors that result due to an empty loop." - ] - } - ], - "metadata": { - "hide_input": false, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.8.8" - }, - "toc": { - "base_numbering": 1, - "nav_menu": {}, - "number_sections": true, - "sideBar": true, - "skip_h1_title": false, - "title_cell": "Table of Contents", - "title_sidebar": "Contents", - "toc_cell": false, - "toc_position": {}, - "toc_section_display": true, - "toc_window_display": false - }, - "varInspector": { - "cols": { - "lenName": 16, - "lenType": 16, - "lenVar": 40 - }, - "kernels_config": { - "python": { - "delete_cmd_postfix": "", - "delete_cmd_prefix": "del ", - "library": "var_list.py", - "varRefreshCmd": "print(var_dic_list())" - }, - "r": { - "delete_cmd_postfix": ") ", - "delete_cmd_prefix": "rm(", - "library": "var_list.r", - "varRefreshCmd": "cat(var_dic_list()) " - } - }, - "types_to_exclude": [ - "module", - "function", - "builtin_function_or_method", - "instance", - "_Feature" - ], - "window_display": false - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} From 5098a6b0d8e2dbb440b31cb4b1d57a45f39c1385 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Mon, 11 Oct 2021 20:25:11 +0530 Subject: [PATCH 12/23] Delete 000_Python_Flow_Control_statement .ipynb --- 000_Python_Flow_Control_statement .ipynb | 168 ----------------------- 1 file changed, 168 deletions(-) delete mode 100644 000_Python_Flow_Control_statement .ipynb diff --git a/000_Python_Flow_Control_statement .ipynb b/000_Python_Flow_Control_statement .ipynb deleted file mode 100644 index d9269ec..0000000 --- a/000_Python_Flow_Control_statement .ipynb +++ /dev/null @@ -1,168 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "All the IPython Notebooks in this lecture series by Dr. Milan Parmar are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)**\n", - "" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Python Flow-Control (Decision-Making) Statements\n", - "\n", - "In Python programming, decision-making statements are those that **help in deciding the flow of the program**. \n", - "\n", - "For example, at times, you might want to execute a block of code only if a particular condition is satisfied. Well, in this case, decision-making statement will be of great help. Let us consider an example to understand this better.\n", - "\n", - "Decision making is required when we want to execute a code only if a certain condition is satisfied.\n", - "\n", - "The key thing to note about Python's control flow statements and program structure is that it uses **`_indentation_`** to mark blocks. Hence the amount of white space (space or tab characters) at the start of a line is very important. This generally helps to make code more readable but can catch out new users of python." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "* Suppose you are given a number and are asked to check if it is an even number or not. How would you do it?\n", - "\n", - "> The first thought that would pop up your mind is this - **\"If the number is divisible by 2, then it is an even number, else it is an odd number\"**. That's absolutely the right logic. But when this has to be coded, you will need the help of decision-making statements. To understand this, let's now look at how they function." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Control Flow Statements\n", - "\n", - "The flow control statements are divided into **three** categories:\n", - "\n", - "1. **Conditional statements**\n", - "2. **Iterative statements**\n", - "3. **Transfer/Control statements**\n", - "\n", - "
\n", - "\n", - "
" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Conditional statements\n", - "\n", - "In Python, condition statements act depending on whether a given condition is true or false. You can execute different blocks of codes depending on the outcome of a condition. Condition statements always evaluate to either **`True`** or **`False`**.\n", - "\n", - "There are **four** types of conditional statements:\n", - "\n", - "1. **[if](https://github.com/milaan9/03_Python_Flow_Control/blob/main/001_Python_if_statement.ipynb)**\n", - "2. **[if-else](https://github.com/milaan9/03_Python_Flow_Control/blob/main/002_Python_if_else_statement.ipynb)**\n", - "3. **[if-elif-else](https://github.com/milaan9/03_Python_Flow_Control/blob/main/003_Python_if_elif_else_statement%20.ipynb)**\n", - "4. **[nested-if](https://github.com/milaan9/03_Python_Flow_Control/blob/main/004_Python_Nested_if_statement.ipynb)**" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Iterative statements\n", - "\n", - "In Python, iterative statements allow us to execute a block of code repeatedly as long as the condition is **`True`**. We also call it a loop statements.\n", - "\n", - "Python provides us the following **two** loop statement to perform some actions repeatedly\n", - "\n", - "1. **[for loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/005_Python_for_Loop.ipynb)**\n", - "2. **[while loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/006_Python_while_Loop.ipynb)**" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Transfer statements\n", - "\n", - "In Python, transfer statements are used to alter the program’s way of execution in a certain manner. For this purpose, we use **three** types of transfer statements.\n", - "\n", - "1. **[break statement](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)**\n", - "2. **[continue statement](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)**\n", - "3. **[pass statements](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)**" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "hide_input": false, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.8.8" - }, - "toc": { - "base_numbering": 1, - "nav_menu": {}, - "number_sections": true, - "sideBar": true, - "skip_h1_title": false, - "title_cell": "Table of Contents", - "title_sidebar": "Contents", - "toc_cell": false, - "toc_position": {}, - "toc_section_display": true, - "toc_window_display": false - }, - "varInspector": { - "cols": { - "lenName": 16, - "lenType": 16, - "lenVar": 40 - }, - "kernels_config": { - "python": { - "delete_cmd_postfix": "", - "delete_cmd_prefix": "del ", - "library": "var_list.py", - "varRefreshCmd": "print(var_dic_list())" - }, - "r": { - "delete_cmd_postfix": ") ", - "delete_cmd_prefix": "rm(", - "library": "var_list.r", - "varRefreshCmd": "cat(var_dic_list()) " - } - }, - "types_to_exclude": [ - "module", - "function", - "builtin_function_or_method", - "instance", - "_Feature" - ], - "window_display": false - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} From 8aec872e10a24844250d6e95ccbea0a9a2d43403 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Mon, 11 Oct 2021 20:25:19 +0530 Subject: [PATCH 13/23] Delete 001_Python_if_statement.ipynb --- 001_Python_if_statement.ipynb | 423 ---------------------------------- 1 file changed, 423 deletions(-) delete mode 100644 001_Python_if_statement.ipynb diff --git a/001_Python_if_statement.ipynb b/001_Python_if_statement.ipynb deleted file mode 100644 index 07fff89..0000000 --- a/001_Python_if_statement.ipynb +++ /dev/null @@ -1,423 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "All the IPython Notebooks in this lecture series by Dr. Milan Parmar are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)**\n", - "" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Python `if` statement\n", - "\n", - "In control statements, The **`if`** statement is the simplest form. It takes a condition and evaluates to either **`True`** or **`False`**.\n", - "\n", - "If the condition is **`True`**, then the **`True`** block of code will be executed, and if the condition is **`False`**, then the block of code is skipped, and The controller moves to the next line." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Syntax:\n", - "\n", - "```python\n", - "if(condition):\n", - " statement 1\n", - " statement 2\n", - " statement n\n", - "```\n", - "\n", - "* An **`if`** statement should be preceded by the keyword **`if`** and ended with a colon **`:`**. The condition of an if statement can be written with or without round brackets **`()`**.\n", - "\n", - "* In Python, the body of the **`if`** statement is indicated by the indentation. The body starts with an indentation and the first unindented line marks the end.\n", - "\n", - "* Python interprets non-zero values as **`True`**. **`None`** and **`0`** are interpreted as **`False`**.\n", - "\n", - "
\n", - "\n", - "
" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Example: of `if` statement:**\n", - "\n", - "```python\n", - ">>> grade = 70\n", - ">>> if grade >= 65:\n", - ">>> print(\"Passing grade\")\n", - "\n", - "Passing grade\n", - "```\n", - "\n", - "With this code, we have the variable grade and are giving it the integer value of 70. We are then using the **`if`** statement to evaluate whether or not the variable grade is **greater than or equal `>=`** to 65. If it does meet this **condition**, we are telling the program to print out the string Passing grade. \n", - "\n", - "Again, if we change the grade to 50 or < 65 number, we will receive no output." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-10T20:03:33.690723Z", - "start_time": "2021-06-10T20:03:33.674172Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Passing grade\n" - ] - } - ], - "source": [ - "# Example 1:\n", - "grade = 70\n", - "if grade >= 65:\n", - " print(\"Passing grade\")" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-10T20:03:34.440566Z", - "start_time": "2021-06-10T20:03:34.422066Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "3 is a positive number.\n", - "This is always printed.\n", - "This is also always printed.\n" - ] - } - ], - "source": [ - "# Example 2: If the number is positive, we print an appropriate message\n", - "\n", - "num = 3\n", - "if (num > 0): # if condition is TRUE: enter the body of if\n", - " print(num, \"is a positive number.\")\n", - "print(\"This is always printed.\")\n", - "\n", - "num = -1\n", - "if num > 0: # if condition is FALSE: do not enter the body of if\n", - " print(num, \"is a negative number.\")\n", - "print(\"This is also always printed.\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation**:\n", - "\n", - "In the above example, **`num > 0`** is the test expression.\n", - "\n", - "The body of **`if`** is executed only if this evaluates to **`True`**.\n", - "\n", - "When the variable **`num`** is equal to 3, test expression is true and statements inside the body of **`if`** are executed.\n", - "\n", - "If the variable **`num`** is equal to -1, test expression is false and statements inside the body of **`if`** are skipped.\n", - "\n", - "The **[print()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/051_Python_print%28%29.ipynb)** statement falls outside of the **`if`** block (unindented). Hence, it is executed regardless of the test expression." - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-10T20:03:35.580430Z", - "start_time": "2021-06-10T20:03:35.571663Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "81\n", - "Next lines of code\n" - ] - } - ], - "source": [ - "# Example 3: Calculate the square of a number if it greater than 6\n", - "\n", - "number = 9\n", - "if number > 6:\n", - " # Calculate square\n", - " print(number * number)\n", - "print('Next lines of code')" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-10T20:03:36.158393Z", - "start_time": "2021-06-10T20:03:36.145731Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "num1 is less than num2\n" - ] - } - ], - "source": [ - "# Example 4: Check if num1 is less than num2\n", - "\n", - "num1, num2 = 6, 9\n", - "if(num1 < num2):\n", - " print(\"num1 is less than num2\")" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-10T20:03:36.548892Z", - "start_time": "2021-06-10T20:03:36.529417Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Hello\n" - ] - } - ], - "source": [ - "x = 12\n", - "if x > 10:\n", - " print(\"Hello\")" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-10T20:03:37.032393Z", - "start_time": "2021-06-10T20:03:37.017791Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Hooray!\n" - ] - } - ], - "source": [ - "if 5 != 3 * 6:\n", - " print (\"Hooray!\")" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-10T20:03:38.014494Z", - "start_time": "2021-06-10T20:03:37.995993Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Horray!\n" - ] - } - ], - "source": [ - "if 5 == 15/3:\n", - " print (\"Horray!\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Shortcut for `if` statement (Short-hand `if` or one-line `if`)\n", - "\n", - "If you have only one statement to execute, then you can put it on the same line as the `if` statement. Let's try doing this for the above example." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-10T20:03:38.795011Z", - "start_time": "2021-06-10T20:03:38.778459Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "num1 is less than num2\n" - ] - } - ], - "source": [ - "num1, num2 = 5, 6\n", - "if(num1 < num2): print(\"num1 is less than num2\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### The Difference....\n", - "\n", - "Now, try to execute the below-given code and observe the difference." - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-10T20:03:44.293701Z", - "start_time": "2021-06-10T20:03:44.275199Z" - } - }, - "outputs": [], - "source": [ - "#program to check if num1 is less than num 2\n", - "num1, num2 = 6, 5\n", - "if (num1 < num2):\n", - " print(\"num1 is less than num2\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "**Did your Python IDE print anything?** No, it will not.\n", - "\n", - "In the above-given code, the value 6 is greater than 5, this means the condition is False. We have instructed the interpreter to print only when the condition is True and hence it in this case, nothing gets printed. However, **you can also instruct the interpreter what to do when the condition is False and this can be done using else statement**." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-10T20:03:48.495255Z", - "start_time": "2021-06-10T20:03:48.478701Z" - } - }, - "outputs": [], - "source": [ - "if 5 == 18/3:\n", - " print (\"Hooray!\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "hide_input": false, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.8.8" - }, - "toc": { - "base_numbering": 1, - "nav_menu": {}, - "number_sections": true, - "sideBar": true, - "skip_h1_title": false, - "title_cell": "Table of Contents", - "title_sidebar": "Contents", - "toc_cell": false, - "toc_position": {}, - "toc_section_display": true, - "toc_window_display": false - }, - "varInspector": { - "cols": { - "lenName": 16, - "lenType": 16, - "lenVar": 40 - }, - "kernels_config": { - "python": { - "delete_cmd_postfix": "", - "delete_cmd_prefix": "del ", - "library": "var_list.py", - "varRefreshCmd": "print(var_dic_list())" - }, - "r": { - "delete_cmd_postfix": ") ", - "delete_cmd_prefix": "rm(", - "library": "var_list.r", - "varRefreshCmd": "cat(var_dic_list()) " - } - }, - "types_to_exclude": [ - "module", - "function", - "builtin_function_or_method", - "instance", - "_Feature" - ], - "window_display": false - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} From 73e86913c52bea997cc09db6d28d0bc9a76d411f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Mon, 11 Oct 2021 20:25:26 +0530 Subject: [PATCH 14/23] Delete 002_Python_if_else_statement.ipynb --- 002_Python_if_else_statement.ipynb | 539 ----------------------------- 1 file changed, 539 deletions(-) delete mode 100644 002_Python_if_else_statement.ipynb diff --git a/002_Python_if_else_statement.ipynb b/002_Python_if_else_statement.ipynb deleted file mode 100644 index 218cddc..0000000 --- a/002_Python_if_else_statement.ipynb +++ /dev/null @@ -1,539 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "All the IPython Notebooks in this lecture series by Dr. Milan Parmar are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)**\n", - "" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Python `if-else` statement\n", - "\n", - "It is likely that we will want the program to do something even when an **[if statement](https://github.com/milaan9/03_Python_Flow_Control/blob/main/001_Python_if_statement.ipynb)** **evaluates to false**. In our grade example of previous tutorial, we will want output whether the grade is passing or failing." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:16:15.066732Z", - "start_time": "2021-06-26T15:16:15.053061Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Case 2\n" - ] - } - ], - "source": [ - "x = 1\n", - "\n", - "if x > 3:\n", - " print (\"Case 1\")\n", - "if x <= 3:\n", - " print (\"Case 2\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The **`if-else`** statement checks the condition and executes the **`if`** block of code when the condition is **`True`**, and **`if`** the condition is **`False`**, it will execute the **`else`** block of code." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Syntax :\n", - "\n", - "```python\n", - "if condition:\n", - " statement 1\n", - "else:\n", - " statement 2\n", - "```\n", - "\n", - "1. The **`if..else`** statement evaluates **`condition`** and will execute the body of **`if`** only when the test condition is **`True`**.\n", - "\n", - "2. If the condition is **`False`**, the body of **`else`** is executed. Indentation is used to separate the blocks.\n", - "\n", - "
\n", - "\n", - "
\n", - "\n", - "To do this, we will add an else statement to the grade condition above that is constructed like this:\n", - "\n", - "```python\n", - ">>> grade = 60 \n", - ">>> if grade >= 65:\n", - ">>> print(\"Passing grade\")\n", - ">>> else:\n", - ">>> print(\"Failing grade\")\n", - "\n", - "Failing grade\n", - "```\n", - "\n", - "Since the grade variable above has the value of 60, the if statement evaluates as false, so the program will not print out Passing grade. The else statement that follows tells the program to do **something anyway**.\n", - "\n", - "If we then rewrite the program to give the grade a value of 65 or higher, we will instead receive the output Passing grade." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:16:16.487612Z", - "start_time": "2021-06-26T15:16:16.469061Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Failing grade\n" - ] - } - ], - "source": [ - "# Example 1:\n", - "\n", - "grade = 60\n", - " \n", - "if grade >= 65:\n", - " print(\"Passing grade\")\n", - "else:\n", - " print(\"Failing grade\")" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:16:17.126278Z", - "start_time": "2021-06-26T15:16:17.108704Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Positive or Zero\n" - ] - } - ], - "source": [ - "# Example 2: Program checks if the number is positive or negative and displays an appropriate message\n", - "\n", - "num = 3\n", - "\n", - "# Try these two variations as well. \n", - "# num = -5\n", - "# num = 0\n", - "\n", - "if num >= 0:\n", - " print(\"Positive or Zero\")\n", - "else:\n", - " print(\"Negative number\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation**\n", - "\n", - "In the above example, when **`num`** is equal to 3, the test expression is true and the body of **`if`** is executed and the **`body`** of else is skipped.\n", - "\n", - "If **`num`** is equal to -5, the test expression is false and the body of **`else`** is executed and the body of **`if`** is skipped.\n", - "\n", - "If **`num`** is equal to 0, the test expression is true and body of **`if`** is executed and **`body`** of else is skipped." - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:16:18.030567Z", - "start_time": "2021-06-26T15:16:18.019827Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "num2 is less than num1\n" - ] - } - ], - "source": [ - "# Example 3: program to check if a num1 is less than num2\n", - "\n", - "num1, num2 = 6, 5\n", - "if (num1 < num2):\n", - " print(\"num1 is less than num2\")\n", - "else:\n", - " print(\"num2 is less than num1\")" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:16:18.498333Z", - "start_time": "2021-06-26T15:16:18.488571Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Correct password\n", - "Incorrect Password\n" - ] - } - ], - "source": [ - "# Example 4:\n", - "\n", - "def password_check(password):\n", - " if password == \"Python@99>\":\n", - " print(\"Correct password\")\n", - " else:\n", - " print(\"Incorrect Password\")\n", - "\n", - "password_check(\"Python@99>\")\n", - "# Output Correct password\n", - "\n", - "password_check(\"Python99\")\n", - "# Output Incorrect Password" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Shortcut of `if else` (Short Hand if ... else or One line `if else`)\n", - "\n", - "If you have **only one statement each for if and else, then they can be put in the same line**. This can be done as shown below" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:16:19.498326Z", - "start_time": "2021-06-26T15:16:19.484656Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Feed the bear now!\n" - ] - } - ], - "source": [ - "hungry = True\n", - "x = 'Feed the bear now!' if hungry else 'Do not feed the bear.'\n", - "print(x)" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:16:19.950469Z", - "start_time": "2021-06-26T15:16:19.936797Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "num2 is less than num1\n" - ] - } - ], - "source": [ - "num1, num2 = 6, 5\n", - "print(\"num1 is less than num2\") if (num1 < num2) else print(\"num2 is less than num1\")" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:16:20.466084Z", - "start_time": "2021-06-26T15:16:20.445582Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "positive\n" - ] - } - ], - "source": [ - "number = 96\n", - "if number > 0: print(\"positive\") \n", - "else: print(\"negative\")" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:16:20.933857Z", - "start_time": "2021-06-26T15:16:20.917257Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "world\n" - ] - } - ], - "source": [ - "x = 12\n", - "if 10 < x < 11:\n", - " print(\"hello\")\n", - "else:\n", - " print(\"world\")" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:16:21.402602Z", - "start_time": "2021-06-26T15:16:21.384048Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Case 2\n" - ] - } - ], - "source": [ - "'''\n", - "x = 1\n", - "\n", - "if x > 3:\n", - " print (\"Case 1\")\n", - "if x <= 3:\n", - " print (\"Case 2\")\n", - "'''\n", - "\n", - "x = 1\n", - "\n", - "if x > 3:\n", - " print (\"Case 1\")\n", - "else:\n", - " print (\"Case 2\")" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:16:21.901620Z", - "start_time": "2021-06-26T15:16:21.891856Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Incorrect\n" - ] - } - ], - "source": [ - "x = 2\n", - "\n", - "if x > 4:\n", - " print (\"Correct\")\n", - "else:\n", - " print(\"Incorrect\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### The difference....\n", - "\n", - "Now, let us try to execute the same above discussed code with different input values." - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:16:22.838622Z", - "start_time": "2021-06-26T15:16:22.804444Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "num2 is less than num1\n" - ] - }, - { - "data": { - "text/plain": [ - "'\\nOutput: num2 is lesser than num1\\n'" - ] - }, - "execution_count": 12, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "#program to check if num1 is less than num2\n", - "\n", - "num1, num2 = 5, 5\n", - "if (num1 < num2):\n", - " print(\"num1 is less than num2\")\n", - "else:\n", - " print(\"num2 is less than num1\")\n", - "\n", - "'''\n", - "Output: num2 is lesser than num1\n", - "'''" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "* **Why was the output wrong?**\n", - "\n", - "Since both the input values are equal, the condition **`num1 Date: Mon, 11 Oct 2021 20:25:35 +0530 Subject: [PATCH 15/23] Delete 003_Python_if_elif_else_statement .ipynb --- 003_Python_if_elif_else_statement .ipynb | 313 ----------------------- 1 file changed, 313 deletions(-) delete mode 100644 003_Python_if_elif_else_statement .ipynb diff --git a/003_Python_if_elif_else_statement .ipynb b/003_Python_if_elif_else_statement .ipynb deleted file mode 100644 index b15ea1b..0000000 --- a/003_Python_if_elif_else_statement .ipynb +++ /dev/null @@ -1,313 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "All the IPython Notebooks in this lecture series by Dr. Milan Parmar are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)**\n", - "" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Python `if-elif-else` statement\n", - "\n", - "So far, we have presented a Boolean option for conditional statements, with each **[if statement](https://github.com/milaan9/03_Python_Flow_Control/blob/main/001_Python_if_statement.ipynb)** evaluating to either **`True`** or **`False`**. In Python, the **`if-elif-else`** condition statement has an **`elif`** keyword used to chain multiple conditions one after another." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Syntax:\n", - "\n", - "```python\n", - "if condition-1: \n", - " statement 1 \n", - "elif condition-2:\n", - " stetement 2 \n", - "elif condition-3:\n", - " stetement 3 \n", - " ... \n", - "else: \n", - " statement \n", - "```\n", - "\n", - "1. The **`elif`** is short for else if. It allows us to check for multiple expressions.\n", - "\n", - "2. If the condition for **`if`** is **`False`**, it checks the condition of the next **`elif`** block and so on.\n", - "\n", - "3. If all the conditions are **`False`**, the body of **`else`** is executed.\n", - "\n", - "4. Only one block among the several **`if-elif-else`** blocks is executed according to the condition.\n", - "\n", - "5. The **`if`** block can have only one **`else`** block. But it can have multiple **`elif`** blocks.\n", - "\n", - "
\n", - "\n", - "
" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-10T21:32:27.675471Z", - "start_time": "2021-06-10T21:32:27.667679Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Zero\n" - ] - } - ], - "source": [ - "# Example 1:\n", - "\n", - "'''In this program, we check if the number is positive or negative or zero and \n", - "display an appropriate message'''\n", - "\n", - "num = 0\n", - "\n", - "# Try these two variations as well:\n", - "# num = 0\n", - "# num = -4.5\n", - "\n", - "if num > 0:\n", - " print(\"Positive number\")\n", - "elif num == 0:\n", - " print(\"Zero\")\n", - "else:\n", - " print(\"Negative number\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "When variable **`num`** is positive, **`Positive number`** is printed.\n", - "\n", - "If **`num`** is equal to 0, **`Zero`** is printed.\n", - "\n", - "If **`num`** is negative, **`Negative number`** is printed. " - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-10T21:32:28.784651Z", - "start_time": "2021-06-10T21:32:28.767125Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "num1 is equal to num2\n" - ] - } - ], - "source": [ - "# Example 2:\n", - "\n", - "num1, num2 = 5, 5\n", - "if(num1 > num2):\n", - " print(\"num1 is greater than num2\")\n", - "elif(num1 == num2):\n", - " print(\"num1 is equal to num2\")\n", - "else:\n", - " print(\"num1 is less than num2\")" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-10T21:32:29.034921Z", - "start_time": "2021-06-10T21:32:29.016422Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "x y:\n", - " print(\"x>y\")\n", - "elif x < y:\n", - " print(\"x= 90:\n", - " print(\"A grade\")\n", - "elif grade >=80:\n", - " print(\"B grade\")\n", - "elif grade >=70:\n", - " print(\"C grade\")\n", - "elif grade >= 65:\n", - " print(\"D grade\")\n", - "else:\n", - " print(\"Failing grade\")" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-10T21:32:30.066200Z", - "start_time": "2021-06-10T21:32:30.053055Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Admin\n", - "Editor\n", - "Guest\n", - "Wrong entry\n" - ] - } - ], - "source": [ - "# Example 5:\n", - "\n", - "def user_check(choice):\n", - " if choice == 1:\n", - " print(\"Admin\")\n", - " elif choice == 2:\n", - " print(\"Editor\")\n", - " elif choice == 3:\n", - " print(\"Guest\")\n", - " else:\n", - " print(\"Wrong entry\")\n", - "\n", - "user_check(1) # Admin\n", - "user_check(2) # Editor\n", - "user_check(3) # Guest\n", - "user_check(4) # Wrong entry" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "hide_input": false, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.8.8" - }, - "toc": { - "base_numbering": 1, - "nav_menu": {}, - "number_sections": true, - "sideBar": true, - "skip_h1_title": false, - "title_cell": "Table of Contents", - "title_sidebar": "Contents", - "toc_cell": false, - "toc_position": {}, - "toc_section_display": true, - "toc_window_display": false - }, - "varInspector": { - "cols": { - "lenName": 16, - "lenType": 16, - "lenVar": 40 - }, - "kernels_config": { - "python": { - "delete_cmd_postfix": "", - "delete_cmd_prefix": "del ", - "library": "var_list.py", - "varRefreshCmd": "print(var_dic_list())" - }, - "r": { - "delete_cmd_postfix": ") ", - "delete_cmd_prefix": "rm(", - "library": "var_list.r", - "varRefreshCmd": "cat(var_dic_list()) " - } - }, - "types_to_exclude": [ - "module", - "function", - "builtin_function_or_method", - "instance", - "_Feature" - ], - "window_display": false - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} From 886e564149a876c00a02e00962e55c1e9ed66fa4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Mon, 11 Oct 2021 20:25:45 +0530 Subject: [PATCH 16/23] Delete 004_Python_Nested_if_statement.ipynb --- 004_Python_Nested_if_statement.ipynb | 304 --------------------------- 1 file changed, 304 deletions(-) delete mode 100644 004_Python_Nested_if_statement.ipynb diff --git a/004_Python_Nested_if_statement.ipynb b/004_Python_Nested_if_statement.ipynb deleted file mode 100644 index e7e9229..0000000 --- a/004_Python_Nested_if_statement.ipynb +++ /dev/null @@ -1,304 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "All the IPython Notebooks in this lecture series by Dr. Milan Parmar are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)**\n", - "" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Python Nested `if` statement\n", - "\n", - "We can have a nested-**[if-else](https://github.com/milaan9/03_Python_Flow_Control/blob/main/002_Python_if_else_statement.ipynb)** or nested-**[if-elif-else](https://github.com/milaan9/03_Python_Flow_Control/blob/main/003_Python_if_elif_else_statement%20.ipynb)** statement inside another **`if-else`** statement. This is called **nesting** in computer programming. The nested if statements is useful when we want to make a series of decisions.\n", - "\n", - "Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. They can get confusing, so they must be avoided unless necessary.\n", - "\n", - "We can use nested if statements for situations where we want to check for a **secondary condition** if the first condition executes as **`True`**." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Syntax:\n", - "\n", - "#### Example 1:\n", - "```python\n", - "if conditon_outer:\n", - " if condition_inner:\n", - " statement of nested if\n", - " else:\n", - " statement of nested if else:\n", - " statement ot outer if\n", - "else:\n", - " Outer else \n", - "statement outside if block\n", - "```\n", - "\n", - "#### Example 2:\n", - "```python\n", - "if expression1:\n", - " statement(s)\n", - " if expression2:\n", - " statement(s)\n", - " elif expression3:\n", - " statement(s)\n", - " elif expression4:\n", - " statement(s)\n", - " else:\n", - " statement(s)\n", - "else:\n", - " statement(s)\n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-10T21:32:46.158585Z", - "start_time": "2021-06-10T21:32:46.150794Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "All Conditions are false\n" - ] - } - ], - "source": [ - "# Example 1:\n", - "\n", - "a=10\n", - "if a>=20: # Condition FALSE\n", - " print (\"Condition is True\")\n", - "else: # Code will go to ELSE body\n", - " if a>=15: # Condition FALSE\n", - " print (\"Checking second value\")\n", - " else: # Code will go to ELSE body\n", - " print (\"All Conditions are false\")" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-10T21:32:46.684934Z", - "start_time": "2021-06-10T21:32:46.672274Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "x y:\n", - " print( \"x>y\")\n", - "elif x < y:\n", - " print( \"x 0): \n", - " print(\"num1 is a positive number\")\n", - " else: \n", - " print(\"num1 is a negative number\")\n", - "else: # For zero condition is TRUE\n", - " print(\"num1 is neither positive nor negative\")" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-10T21:33:30.124628Z", - "start_time": "2021-06-10T21:33:16.450727Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Enter a number: 9\n", - "Positive number\n" - ] - } - ], - "source": [ - "# Example 4:\n", - "\n", - "'''In this program, we input a number check if the number is \n", - "positive or negative or zero and display an appropriate message. \n", - "This time we use nested if statement'''\n", - "\n", - "num = float(input(\"Enter a number: \"))\n", - "if num >= 0:\n", - " if num == 0:\n", - " print(\"Zero\")\n", - " else:\n", - " print(\"Positive number\")\n", - "else:\n", - " print(\"Negative number\")" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-10T21:33:37.996992Z", - "start_time": "2021-06-10T21:33:37.975571Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "96 is greater than 66\n", - "96 and 96 are equal\n" - ] - } - ], - "source": [ - "# Example 5:\n", - "\n", - "def number_arithmetic(num1, num2):\n", - " if num1 >= num2:\n", - " if num1 == num2:\n", - " print(f'{num1} and {num2} are equal')\n", - " else:\n", - " print(f'{num1} is greater than {num2}')\n", - " else:\n", - " print(f'{num1} is smaller than {num2}')\n", - "\n", - "number_arithmetic(96, 66)\n", - "# Output 96 is greater than 66\n", - "number_arithmetic(96, 96)\n", - "# Output 56 and 56 are equal" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "hide_input": false, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.8.8" - }, - "toc": { - "base_numbering": 1, - "nav_menu": {}, - "number_sections": true, - "sideBar": true, - "skip_h1_title": false, - "title_cell": "Table of Contents", - "title_sidebar": "Contents", - "toc_cell": false, - "toc_position": {}, - "toc_section_display": true, - "toc_window_display": false - }, - "varInspector": { - "cols": { - "lenName": 16, - "lenType": 16, - "lenVar": 40 - }, - "kernels_config": { - "python": { - "delete_cmd_postfix": "", - "delete_cmd_prefix": "del ", - "library": "var_list.py", - "varRefreshCmd": "print(var_dic_list())" - }, - "r": { - "delete_cmd_postfix": ") ", - "delete_cmd_prefix": "rm(", - "library": "var_list.r", - "varRefreshCmd": "cat(var_dic_list()) " - } - }, - "types_to_exclude": [ - "module", - "function", - "builtin_function_or_method", - "instance", - "_Feature" - ], - "window_display": false - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} From 83c0abae4866244cdf9fe4d8de54377c9da94229 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Mon, 11 Oct 2021 20:25:54 +0530 Subject: [PATCH 17/23] Delete 005_Python_for_Loop.ipynb --- 005_Python_for_Loop.ipynb | 2878 ------------------------------------- 1 file changed, 2878 deletions(-) delete mode 100644 005_Python_for_Loop.ipynb diff --git a/005_Python_for_Loop.ipynb b/005_Python_for_Loop.ipynb deleted file mode 100644 index de6e99b..0000000 --- a/005_Python_for_Loop.ipynb +++ /dev/null @@ -1,2878 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "All the IPython Notebooks in this lecture series by Dr. Milan Parmar are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)**\n", - "" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Loops in Python\n", - "\n", - "Loops in Python programming function similar to loops in C, C++, Java or other languages. Python loops are used to repeatedly execute a block of statements until a given condition returns to be **`False`**. In Python, we have **two types of looping statements**, namely:\n", - "
\n", - "\n", - "
" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Python `for` Loop\n", - "\n", - "In this class, you'll learn to iterate over a sequence of elements using the different variations of **`for`** loop. We use a **`for`** loop when we want to repeat a code block for a **fixed number of times**." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## What is for loop in Python? \n", - "\n", - "The for loop in Python is used to iterate over a sequence (**[string](https://github.com/milaan9/02_Python_Datatypes/blob/main/002_Python_String.ipynb)**, **[list](https://github.com/milaan9/02_Python_Datatypes/blob/main/003_Python_List.ipynb)**, **[dictionary](https://github.com/milaan9/02_Python_Datatypes/blob/main/005_Python_Dictionary.ipynb)**, **[set](https://github.com/milaan9/02_Python_Datatypes/blob/main/006_Python_Sets.ipynb)**, or **[tuple](https://github.com/milaan9/02_Python_Datatypes/blob/main/004_Python_Tuple.ipynb)**). Iterating over a sequence is called traversal." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Why use `for` loop?\n", - "\n", - "Let’s see the use **`for`** loop in Python.\n", - "\n", - "* **Definite Iteration:** When we know how many times we wanted to run a loop, then we use count-controlled loops such as **`for`** loops. It is also known as definite iteration. For example, Calculate the percentage of 50 students. here we know we need to iterate a loop 50 times (1 iteration for each student).\n", - "* **Reduces the code’s complexity:** Loop repeats a specific block of code a fixed number of times. It reduces the repetition of lines of code, thus reducing the complexity of the code. Using **`for`** loops and while loops we can automate and repeat tasks in an efficient manner.\n", - "* **Loop through sequences:** used for iterating over lists, strings, tuples, dictionaries, etc., and perform various operations on it, based on the conditions specified by the user." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Syntax :\n", - "\n", - "```python \n", - "for element in sequence:\n", - " body of for loop \n", - "```\n", - "\n", - "1. First, **`element`** is the variable that takes the value of the item inside the sequence on each iteration.\n", - "\n", - "2. Second, all the **`statements`** in the body of the for loop are executed with the same value. The body of for loop is separated from the rest of the code using indentation.\n", - "\n", - "3. Finally, loop continues until we reach the last item in the **`sequence`**. The body of for loop is separated from the rest of the code using indentation.\n", - "\n", - "
\n", - "\n", - "
" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:19:57.228517Z", - "start_time": "2021-06-26T15:19:57.214846Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "one\n", - "two\n", - "three\n", - "four\n", - "five\n" - ] - } - ], - "source": [ - "# Example 1:\n", - "\n", - "words = ['one', 'two', 'three', 'four', 'five']\n", - "\n", - "for i in words:\n", - " print(i)" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:19:58.273428Z", - "start_time": "2021-06-26T15:19:58.254876Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "30.0\n" - ] - } - ], - "source": [ - "# Example 2: Calculate the average of list of numbers\n", - "\n", - "numbers = [10, 20, 30, 40, 50]\n", - "\n", - "# definite iteration\n", - "# run loop 5 times because list contains 5 items\n", - "sum = 0\n", - "for i in numbers:\n", - " sum = sum + i\n", - "list_size = len(numbers)\n", - "average = sum / list_size\n", - "print(average)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## `for` loop with `range()` function\n", - "\n", - "The **[range()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/053_Python_range%28%29.ipynb)** function returns a sequence of numbers starting from 0 (by default) if the initial limit is not specified and it increments by 1 (by default) until a final limit is reached.\n", - "\n", - "The **`range()`** function is used with a loop to specify the range (how many times) the code block will be executed. Let us see with an example.\n", - "\n", - "We can generate a sequence of numbers using **`range()`** function. **`range(5)`** will generate numbers from 0 to 4 (5 numbers). \n", - "\n", - "
\n", - "\n", - "
\n", - "\n", - "The **`range()`** function is \"lazy\" in a sense because it doesn't generate every number that it \"contains\" when we create it. However, it is not an iterator since it supports **[len()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/040_Python_len%28%29.ipynb)** and **`__getitem__`** operations.\n", - "\n", - "This **`range()`** function does not store all the values in memory; it would be inefficient. So it remembers the start, stop, step size and generates the next number on the go.\n", - "\n", - "We can also define the start, stop and step size as **`range(start, stop,step_size)`**. **`step_size`** defaults to 1 if not provided." - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:02.985782Z", - "start_time": "2021-06-26T15:20:02.968204Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[]\n", - "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n", - "[1, 2, 3, 4, 5, 6, 7, 8, 9]\n" - ] - } - ], - "source": [ - "# Example 1: How range works in Python?\n", - "\n", - "# empty range\n", - "print(list(range(0)))\n", - "\n", - "# using range(stop)\n", - "print(list(range(10)))\n", - "\n", - "# using range(start, stop)\n", - "print(list(range(1, 10)))" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:03.828544Z", - "start_time": "2021-06-26T15:20:03.814876Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "0\n", - "1\n", - "2\n", - "3\n", - "4\n", - "5\n", - "6\n", - "7\n", - "8\n", - "9\n" - ] - } - ], - "source": [ - "# Example 2:\n", - "\n", - "for num in range(10):\n", - " print(num)" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:04.421313Z", - "start_time": "2021-06-26T15:20:04.411551Z" - }, - "scrolled": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "2\n", - "3\n", - "4\n", - "5\n", - "6\n", - "7\n", - "8\n", - "9\n", - "10\n" - ] - } - ], - "source": [ - "# Example 3:\n", - "\n", - "for i in range(1, 11):\n", - " print(i)" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:06.028717Z", - "start_time": "2021-06-26T15:20:06.015050Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "2\n", - "4\n", - "6\n", - "8\n", - "10\n" - ] - } - ], - "source": [ - "# Example 4:\n", - "\n", - "for i in range (2, 12, 2): # beginning 2 with distance of 2 and stop before 12\n", - " print (i)" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:09.633664Z", - "start_time": "2021-06-26T15:20:09.622924Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "2\n", - "4\n", - "6\n", - "8\n", - "10\n" - ] - } - ], - "source": [ - "# Example 5:\n", - "\n", - "num=2\n", - "\n", - "for a in range (1,6): # range (1,6) means numbers from 1 to 5, i.e., (1,2,3,4,5)\n", - " print (num * a)" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:10.711777Z", - "start_time": "2021-06-26T15:20:10.687367Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "3\n", - "6\n", - "10\n", - "15\n", - "21\n", - "28\n", - "36\n", - "45\n", - "55\n" - ] - }, - { - "data": { - "text/plain": [ - "'\\n0+1 = 1\\n1+2 = 3\\n3+3 = 6\\n6+4 = 10\\n10+5 =15\\n21\\n28\\n36\\n45\\n45+10 = 55\\n'" - ] - }, - "execution_count": 8, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# Example 6: Find Sum of 10 Numbers\n", - "\n", - "sum=0\n", - "for n in range(1,11): # range (1,11) means numbers from 1 to 5, i.e., (1,2,3,4,5,6,7,8,9,10)\n", - " sum+=n \n", - " print (sum)\n", - " \n", - "'''\n", - "0+1 = 1\n", - "1+2 = 3\n", - "3+3 = 6\n", - "6+4 = 10\n", - "10+5 =15\n", - "21\n", - "28\n", - "36\n", - "45\n", - "45+10 = 55\n", - "'''" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:11.756688Z", - "start_time": "2021-06-26T15:20:11.743020Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Case 1:\n", - "0\n", - "1\n", - "2\n", - "3\n", - "4\n", - "Case 2:\n", - "5\n", - "6\n", - "7\n", - "8\n", - "9\n", - "Case 3:\n", - "5\n", - "7\n", - "9\n" - ] - } - ], - "source": [ - "# Example 7: printing a series of numbers using for and range\n", - "\n", - "print(\"Case 1:\")\n", - "for i in range(5): # Print numbers from 0 to 4\n", - " print (i)\n", - "\n", - "print(\"Case 2:\") \n", - "for i in range(5, 10): # Print numbers from 5 to 9\n", - " print (i)\n", - "\n", - "print(\"Case 3:\")\n", - "for i in range(5, 10, 2): # Print numbers from 5 with distace 2 and stop before 10\n", - " print (i)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## `for` loop with `if-else`\n", - "\n", - "A **`for`** loop can have an optional **[if-else](https://github.com/milaan9/03_Python_Flow_Control/blob/main/002_Python_if_else_statement.ipynb)** block. The **`if-else`** checks the condition and if the condition is **`True`** it executes the block of code present inside the **`if`** block and if the condition is **`False`**, it will execute the block of code present inside the **`else`** block." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:13.519364Z", - "start_time": "2021-06-26T15:20:13.494956Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Odd Number: 1\n", - "Even Number: 2\n", - "Odd Number: 3\n", - "Even Number: 4\n", - "Odd Number: 5\n", - "Even Number: 6\n", - "Odd Number: 7\n", - "Even Number: 8\n", - "Odd Number: 9\n", - "Even Number: 10\n" - ] - } - ], - "source": [ - "# Example 1: Print all even and odd numbers\n", - "\n", - "for i in range(1, 11):\n", - " if i % 2 == 0:\n", - " print('Even Number:', i)\n", - " else:\n", - " print('Odd Number:', i)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## `for` loop with `else`\n", - "\n", - "A **`for`** loop can have an optional **`else`** block as well. The **`else`** part is executed if the items in the sequence used in for loop exhausts.\n", - "\n", - "**`else`** block will be skipped/ignored when:\n", - "\n", - "* **`for`** loop terminate abruptly\n", - "* the **[break statement](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)** is used to break the **`for`** loop." - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:14.893374Z", - "start_time": "2021-06-26T15:20:14.881658Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "0\n", - "1\n", - "5\n", - "No items left.\n" - ] - } - ], - "source": [ - "# Example 1:\n", - "\n", - "digits = [0, 1, 5]\n", - "\n", - "for i in digits:\n", - " print(i)\n", - "else:\n", - " print(\"No items left.\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "Here, the for loop prints items of the list until the loop exhausts. When the for loop exhausts, it executes the block of code in the **`else`** and prints **`No items left`**." - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:16.235158Z", - "start_time": "2021-06-26T15:20:16.222466Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "2\n", - "3\n", - "4\n", - "5\n", - "Done\n" - ] - } - ], - "source": [ - "# Example 2: Else block in for loop\n", - "\n", - "for i in range(1, 6):\n", - " print(i)\n", - "else:\n", - " print(\"Done\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This **`for-else`** statement can be used with the **`break`** keyword to run the **`else`** block only when the **`break`** keyword was not executed. Let's take an example:" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:17.390420Z", - "start_time": "2021-06-26T15:20:17.382611Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "No entry with that name found.\n" - ] - } - ], - "source": [ - "# Example 3:\n", - "\n", - "student_name = 'Arthur'\n", - "\n", - "marks = {'Alan': 99, 'Bill': 55, 'Cory': 77}\n", - "\n", - "for student in marks:\n", - " if student == student_name:\n", - " print(marks[student])\n", - " break\n", - "else:\n", - " print('No entry with that name found.')" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:18.107699Z", - "start_time": "2021-06-26T15:20:18.095006Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "2\n" - ] - } - ], - "source": [ - "# Example 4:\n", - "\n", - "count = 0\n", - "for i in range(1, 6):\n", - " count = count + 1\n", - " if count > 2:\n", - " break\n", - " else:\n", - " print(i)\n", - "else:\n", - " print(\"Done\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Using Control Statement in `for` loops in Python\n", - "\n", - "**[Control statements](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)** in Python like **`break`**, **`continue`**, etc can be used to control the execution flow of **`for`** loop in Python. Let us now understand how this can be done.\n", - "\n", - "It is used when you want to exit a loop or skip a part of the loop based on the given condition. It also knows as **transfer statements**." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### a) `break` in `for` loop\n", - "\n", - "Using the **`break`** statement, we can exit from the **`for`** loop before it has looped through all the elements in the sequence as shown below. As soon as it breaks out of the **`for`** loop, the control shifts to the immediate next line of code. For example," - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:19.934827Z", - "start_time": "2021-06-26T15:20:19.920184Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Pink\n" - ] - } - ], - "source": [ - "# Example 1:\n", - "\n", - "color = ['Green', 'Pink', 'Blue']\n", - "for i in color:\n", - " if(i == 'Pink'):\n", - " break\n", - "print (i)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "Here, in the second iteration, the **`if`** condition becomes **`True`**. Hence the loop beaks out of the for loop and the immediate next line of code i.e **`print (i)`** is executed and as a result, pink is outputted." - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:20.715093Z", - "start_time": "2021-06-26T15:20:20.694590Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "4\n", - "7\n", - "8\n", - "15\n" - ] - } - ], - "source": [ - "# Example 2:\n", - "\n", - "numbers = [1, 4, 7, 8, 15, 20, 35, 45, 55]\n", - "for i in numbers:\n", - " if i > 15:\n", - " # break the loop\n", - " break\n", - " else:\n", - " print(i)" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:21.246338Z", - "start_time": "2021-06-26T15:20:21.232668Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1 0\n", - "2 0\n", - "2 1\n", - "3 0\n", - "3 1\n", - "3 2\n", - "4 0\n", - "4 1\n", - "4 2\n", - "4 3\n" - ] - } - ], - "source": [ - "# Example 3:\n", - "\n", - "for i in range(5):\n", - " for j in range(5):\n", - " if j == i:\n", - " break\n", - " print(i, j)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "We have two loops. The outer **`for`** loop iterates the first four numbers using the **[range()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/053_Python_range%28%29.ipynb)** function, and the inner **`for`** loop also iterates the first four numbers. If the outer number and a current number of the inner loop are the same, then break the inner (nested) loop." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### b) `continue` in `for` loop\n", - "\n", - "The **`continue`** statement is used to stop/skip the block of code in the loop for the current iteration only and continue with the next iteration. For example," - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:22.523672Z", - "start_time": "2021-06-26T15:20:22.503164Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Blue\n" - ] - } - ], - "source": [ - "# Example 1:\n", - "\n", - "color = ['Green', 'Pink', 'Blue']\n", - "for i in color:\n", - " if(i == 'Pink'):\n", - " continue\n", - "print (i)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "Here, in the second iteration, the condition becomes **`True`**. Hence the interpreter skips the **`print (i)`** statement and immediately executes the next iteration." - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:23.975801Z", - "start_time": "2021-06-26T15:20:23.959205Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "3 * 6 = 18\n", - "3 * 9 = 27\n", - "6 * 3 = 18\n", - "6 * 9 = 54\n", - "9 * 3 = 27\n", - "9 * 6 = 54\n" - ] - } - ], - "source": [ - "# Example 2:\n", - "\n", - "first = [3, 6, 9]\n", - "second = [3, 6, 9]\n", - "for i in first:\n", - " for j in second:\n", - " if i == j:\n", - " continue\n", - " print(i, '*', j, '= ', i * j)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "We have two loops. The outer for loop iterates the first list, and the inner loop also iterates the second list of numbers. If the outer number and the inner loop’s current number are the same, then move to the next iteration of an inner loop.\n", - "\n", - "As you can see in the output, no same numbers multiplying to each other." - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:25.132041Z", - "start_time": "2021-06-26T15:20:25.119350Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Total number of m is: 2\n" - ] - } - ], - "source": [ - "# Example 3:\n", - "\n", - "name = \"mariya mennen\"\n", - "count = 0\n", - "for char in name:\n", - " if char != 'm':\n", - " continue\n", - " else:\n", - " count = count + 1\n", - "\n", - "print('Total number of m is:', count)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### c) `pass` in `for` loop\n", - "\n", - "The **`pass`** statement is a null statement, i.e., nothing happens when the statement is executed. Primarily it is used in empty functions or classes. When the interpreter finds a pass statement in the program, it returns no operation." - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:26.147657Z", - "start_time": "2021-06-26T15:20:26.142777Z" - } - }, - "outputs": [], - "source": [ - "# Example 1:\n", - "\n", - "num = [1, 4, 5, 3, 7, 8]\n", - "for i in num:\n", - " # calculate multiplication in future if required\n", - " pass" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Reverse for loop\n", - "\n", - "Till now, we have learned about forward looping in **`for`** loop with various examples. Now we will learn about the backward iteration of a loop.\n", - "\n", - "Sometimes we require to do reverse looping, which is quite useful. For example, to reverse a list.\n", - "\n", - "There are three ways to iterating the **`for`** loop backward:\n", - "\n", - "* Reverse **`for`** loop using **[range()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/053_Python_range%28%29.ipynb)** function\n", - "* Reverse **`for`** loop using the **[reversed()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/055_Python_reversed%28%29.ipynb)** function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Backward Iteration using the `reversed()` function\n", - "\n", - "We can use the built-in function **[reversed()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/055_Python_reversed%28%29.ipynb)** with **`for`** loop to change the order of elements, and this is the simplest way to perform a reverse looping." - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:27.628597Z", - "start_time": "2021-06-26T15:20:27.607116Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "40\n", - "30\n", - "20\n", - "10\n" - ] - } - ], - "source": [ - "# Example 1: Reversed numbers using `reversed()` function\n", - "\n", - "list1 = [10, 20, 30, 40]\n", - "for num in reversed(list1):\n", - " print(num)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Reverse for loop using `range()`\n", - "\n", - "We can use the built-in **[range()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/053_Python_range%28%29.ipynb)** function with the **`for`** loop to reverse the elements order. The **`range()`** generates the integer numbers between the given start integer to the stop integer." - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:28.455739Z", - "start_time": "2021-06-26T15:20:28.439141Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Reverse numbers using for loop\n", - "5\n", - "4\n", - "3\n", - "2\n", - "1\n", - "0\n" - ] - } - ], - "source": [ - "# Example 1:\n", - "\n", - "print(\"Reverse numbers using for loop\")\n", - "num = 5\n", - "# start = 5\n", - "# stop = -1\n", - "# step = -1\n", - "for num in (range(num, -1, -1)):\n", - " print(num)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "There are many helper functions that make **`for`** loops even more powerful and easy to use. For example **[enumerate()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/018_Python_enumerate%28%29.ipynb)**, **[zip()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/066_Python_zip%28%29.ipynb)**, **[sorted()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/060_Python_sorted%28%29.ipynb)**, **[reversed()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/055_Python_reversed%28%29.ipynb)**" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:29.267253Z", - "start_time": "2021-06-26T15:20:29.239914Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "reversed: \tc;b;a;\n", - "enuemerated:\t0 = a; 1 = b; 2 = c; \n", - "zip'ed: \n", - "a : x\n", - "b : y\n", - "c : z\n" - ] - } - ], - "source": [ - "# Example 2:\n", - "\n", - "print(\"reversed: \\t\",end=\"\")\n", - "for ch in reversed(\"abc\"):\n", - " print(ch,end=\";\")\n", - "\n", - "print(\"\\nenuemerated:\\t\",end=\"\")\n", - "for i,ch in enumerate(\"abc\"):\n", - " print(i,\"=\",ch,end=\"; \")\n", - " \n", - "print(\"\\nzip'ed: \")\n", - "for a,x in zip(\"abc\",\"xyz\"):\n", - " print(a,\":\",x)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Nested `for` loops\n", - "\n", - "**Nested `for` loop** is a **`for`** loop inside another **`for`** a loop. \n", - "\n", - "A nested loop has one loop inside of another. In Python, you can use any loop inside any other loop. For instance, a **`for`** loop inside a **[while loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/006_Python_while_Loop.ipynb)**, a **`while`** inside **`for`** in and so on. It is mainly used with two-dimensional arrays.\n", - "\n", - "In nested loops, the inner loop finishes all of its iteration for each iteration of the outer loop. i.e., For each iteration of the outer loop inner loop restart and completes all its iterations, then the next iteration of the outer loop begins.\n", - "\n", - "**Syntax:**\n", - "\n", - "```python\n", - "# outer for loop\n", - "for element in sequence \n", - " # inner for loop\n", - " for element in sequence:\n", - " body of inner for loop\n", - " body of outer for loop\n", - "other statements\n", - "```" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### `for` loop inside `for` loop" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Example: Nested `for` loop \n", - "\n", - "In this example, we are using a **`for`** loop inside a **`for`** loop. In this example, we are printing a multiplication table of the first ten numbers.\n", - "\n", - "
\n", - "\n", - "
\n", - "\n", - "1. The outer **`for`** loop uses the **[range()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/053_Python_range%28%29.ipynb)** function to iterate over the first ten numbers\n", - "2. The inner **`for`** loop will execute ten times for each outer number\n", - "3. In the body of the inner loop, we will print the multiplication of the outer number and current number\n", - "4. The inner loop is nothing but a body of an outer loop." - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:30.735014Z", - "start_time": "2021-06-26T15:20:30.711577Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1 2 3 4 5 6 7 8 9 10 \n", - "2 4 6 8 10 12 14 16 18 20 \n", - "3 6 9 12 15 18 21 24 27 30 \n", - "4 8 12 16 20 24 28 32 36 40 \n", - "5 10 15 20 25 30 35 40 45 50 \n", - "6 12 18 24 30 36 42 48 54 60 \n", - "7 14 21 28 35 42 49 56 63 70 \n", - "8 16 24 32 40 48 56 64 72 80 \n", - "9 18 27 36 45 54 63 72 81 90 \n", - "10 20 30 40 50 60 70 80 90 100 \n" - ] - } - ], - "source": [ - "# Example 1: printing a multiplication table of the first ten numbers\n", - "\n", - "# outer loop\n", - "for i in range(1, 11):\n", - " # nested loop \n", - " for j in range(1, 11): # to iterate from 1 to 10 \n", - " print(i * j, end=' ') # print multiplication\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "* In this program, the outer **`for`** loop is iterate numbers from 1 to 10. The **`range()`** return 10 numbers. So total number of iteration of the outer loop is 10.\n", - "* In the first iteration of the nested loop, the number is 1. In the next, it 2. and so on till 10.\n", - "* Next, the inner loop will also execute ten times because we rea printing multiplication table up to ten. For each iteration of the outer loop, the inner loop will execute ten times.\n", - "* In each iteration of an inner loop, we calculated the multiplication of two numbers." - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:31.327781Z", - "start_time": "2021-06-26T15:20:31.318992Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "17\n", - "19\n", - "23\n", - "29\n", - "31\n", - "37\n", - "41\n", - "43\n", - "47\n", - "53\n", - "340\n" - ] - } - ], - "source": [ - "# Example 2: Write a code to add all the prime numbers between 17 to 53 using while loop\n", - "# 17, 19, 23, 29, 31, 37, 41, 43, 47, 53\n", - "\n", - "sum=0\n", - "for i in range(17,54): \n", - " for j in range(2,i): \n", - " if i%j ==0: \n", - " break \n", - " else: \n", - " sum=sum+i\n", - " print(i)\n", - "print(sum)" - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:31.984022Z", - "start_time": "2021-06-26T15:20:31.961565Z" - }, - "code_folding": [] - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Red flower\n", - "Red watch\n", - "Pink flower\n", - "Pink watch\n" - ] - } - ], - "source": [ - "# Example 3: iterating through nested for loops\n", - "\n", - "color = ['Red', 'Pink']\n", - "element = ['flower', 'watch']\n", - "for i in color:\n", - " for j in element:\n", - " print(i, j)" - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:32.326796Z", - "start_time": "2021-06-26T15:20:32.317030Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "45\n" - ] - } - ], - "source": [ - "# Example 4: A use case of a nested for loop in `list_of_lists` case would be\n", - "\n", - "list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n", - "total=0\n", - "for list1 in list_of_lists:\n", - " for i in list1:\n", - " total = total+i\n", - "print(total)" - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:32.842413Z", - "start_time": "2021-06-26T15:20:32.825816Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "iteration 0: 1\n", - "iteration 1: 2\n", - "iteration 2: 3\n", - "iteration 3: 4\n", - "iteration 4: 5\n", - "iteration 5: 6\n" - ] - } - ], - "source": [ - "# Example 5:\n", - "\n", - "numbers = [[1, 2, 3], [4, 5, 6]]\n", - "\n", - "cnt = 0\n", - "for i in numbers:\n", - " for j in i:\n", - " print('iteration', cnt, end=': ')\n", - " print(j)\n", - " cnt = cnt + 1" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Example: Nested `for` loop to print pattern\n", - "\n", - "```python\n", - "*\n", - "* *\n", - "* * *\n", - "* * * *\n", - "* * * * *\n", - "```\n", - "\n", - "```python\n", - ">>>rows = 5\n", - " # outer loop\n", - ">>>for i in range(1, rows + 1):\n", - " # inner loop\n", - ">>> for j in range(1, i + 1):\n", - ">>> print(\"*\", end=\" \")\n", - ">>> print('')\n", - "```\n", - "\n", - "
\n", - "\n", - "
\n", - "\n", - "**Explanation:**\n", - "\n", - "* In this program, the outer loop is the number of rows print. \n", - "* The number of rows is five, so the outer loop will execute five times\n", - "* Next, the inner loop is the total number of columns in each row.\n", - "* For each iteration of the outer loop, the columns count gets incremented by 1\n", - "* In the first iteration of the outer loop, the column count is 1, in the next it 2. and so on.\n", - "* The inner loop iteration is equal to the count of columns.\n", - "* In each iteration of an inner loop, we print star" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:33.467407Z", - "start_time": "2021-06-26T15:20:33.455691Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "* \n", - "* * \n", - "* * * \n", - "* * * * \n", - "* * * * * \n" - ] - } - ], - "source": [ - "# Example 1:\n", - "\n", - "rows = 5\n", - "for i in range(1, rows + 1): # outer loop \n", - " for j in range(1, i + 1): # inner loop\n", - " print(\"*\", end=\" \")\n", - " print('')" - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:33.825803Z", - "start_time": "2021-06-26T15:20:33.816038Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1 \n", - "2 2 \n", - "3 3 3 \n", - "4 4 4 4 \n", - "5 5 5 5 5 \n" - ] - } - ], - "source": [ - "# Example 2: Method 1\n", - "\n", - "for i in range(1,6): # numbers from 0,1,2,3,4,5\n", - " for j in range(1, i+1): \n", - " print(i, end=\" \") # print number \n", - " print(\" \") # line after each row to display pattern correctly" - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:34.091422Z", - "start_time": "2021-06-26T15:20:34.073847Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - " \n", - "1 \n", - "2 2 \n", - "3 3 3 \n", - "4 4 4 4 \n", - "5 5 5 5 5 \n" - ] - } - ], - "source": [ - "# Example 2: Method 2\n", - "\n", - "rows = 6 \n", - "for num in range(rows): # from 0,1,2,3,4,5\n", - " for i in range(num):\n", - " print(num,end=\" \") # print the number\n", - " print(\" \") # line after each row to print" - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:34.247671Z", - "start_time": "2021-06-26T15:20:34.234002Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1 \n", - "2 2 \n", - "3 3 3 \n", - "4 4 4 4 \n", - "5 5 5 5 5 \n" - ] - } - ], - "source": [ - "# Example 3: Method 3\n", - "\n", - "n=5 # giving number of rows i want\n", - "x = 0\n", - "for i in range(0 , n): # from 0 to 4\n", - " x += 1 # equivalent to x=x+1\n", - " for j in range(0, i + 1): # 0,1,2,3,4,5\n", - " print(x , end=\" \") \n", - " print(\" \") " - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:34.450794Z", - "start_time": "2021-06-26T15:20:34.426385Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1 \n", - "1 2 \n", - "1 2 3 \n", - "1 2 3 4 \n", - "1 2 3 4 5 \n" - ] - } - ], - "source": [ - "# Example 4: Method 1\n", - "\n", - "rows = 5\n", - "for row in range(1, rows+1): # from 1\n", - " for column in range(1, row+1): # from 1,2,3,4,5\n", - " print(column, end=\" \")\n", - " print(\" \")" - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:34.792590Z", - "start_time": "2021-06-26T15:20:34.770129Z" - }, - "scrolled": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1 \n", - "1 2 \n", - "1 2 3 \n", - "1 2 3 4 \n", - "1 2 3 4 5 \n" - ] - } - ], - "source": [ - "# Example 4: Method 2\n", - "\n", - "for i in range (1, 6): # rows from 1 to 5\n", - " for j in range(i): # column range(i)\n", - " print (j + 1, end = ' ')\n", - " print ()" - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:35.057233Z", - "start_time": "2021-06-26T15:20:35.040634Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1 \n", - "2 1 \n", - "3 2 1 \n", - "4 3 2 1 \n", - "5 4 3 2 1 \n" - ] - }, - { - "data": { - "text/plain": [ - "'\\ni = 1 2 3 4 5 \\n\\n# loop 1\\nfor i = 1, range (1,0,-1): j=1\\ni = 1, print: 1 \\n\\n# loop 2\\nfor i =2, range (2,0,-1): j = 2,1\\ni = 2, print: 2,1\\n'" - ] - }, - "execution_count": 36, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# Example 5: Method 1\n", - "\n", - "for i in range (1,6):\n", - " for j in range (i,0,-1):\n", - " print(j, end=\" \")\n", - " print(\" \")\n", - " \n", - "\"\"\"\n", - "i = 1 2 3 4 5 \n", - "\n", - "# loop 1\n", - "for i = 1, range (1,0,-1): j=1\n", - "i = 1, print: 1 \n", - "\n", - "# loop 2\n", - "for i =2, range (2,0,-1): j = 2,1\n", - "i = 2, print: 2,1\n", - "\"\"\"" - ] - }, - { - "cell_type": "code", - "execution_count": 37, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:35.307230Z", - "start_time": "2021-06-26T15:20:35.292586Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1 \n", - "2 1 \n", - "3 2 1 \n", - "4 3 2 1 \n", - "5 4 3 2 1 \n" - ] - } - ], - "source": [ - "# Example 5: Method 2\n", - "\n", - "for i in range(0,5):\n", - " for j in range(i+1,0,-1):\n", - " print(j, end=\" \")\n", - " print()" - ] - }, - { - "cell_type": "code", - "execution_count": 38, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:35.588477Z", - "start_time": "2021-06-26T15:20:35.568950Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "* * * * * \n", - "* * * * \n", - "* * * \n", - "* * \n", - "* \n" - ] - } - ], - "source": [ - "# Example 6: Example 1 reverse pyramid \n", - "\n", - "\n", - "for i in range (1,6): # rows from 1 to 5\n", - " for j in range (5,i-1,-1): # column range(5,0,-1) = 54321\n", - " print (\"*\", end=\" \"),\n", - " print (\" \")" - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:35.837500Z", - "start_time": "2021-06-26T15:20:35.819923Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "5 5 5 5 5 \n", - "4 4 4 4 \n", - "3 3 3 \n", - "2 2 \n", - "1 \n" - ] - } - ], - "source": [ - "# Example 7: Example 2 reverse pyramid Method 1\n", - "\n", - "rows = 5\n", - "# range(1,10,2) # from 1,3,5,7,9\n", - "for i in range(rows,0,-1): # from 3,2,1\n", - " num = i\n", - " for j in range(0,i):\n", - " print(num, end=\" \")\n", - " print(\" \")" - ] - }, - { - "cell_type": "code", - "execution_count": 40, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:36.134372Z", - "start_time": "2021-06-26T15:20:36.111913Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "5 5 5 5 5 \n", - "4 4 4 4 \n", - "3 3 3 \n", - "2 2 \n", - "1 \n" - ] - }, - { - "data": { - "text/plain": [ - "'\\ni = 5 4 3 2 1 \\n\\n# loop 1\\nfor i = 5, range (0,5): j=5 4 3 2 1\\ni = 5, print: 5 5 5 5 5\\n\\n# loop 2\\nfor i = 4, range (0,4): j=4 3 2 1\\ni = 4, print: 4 4 4 4 \\n'" - ] - }, - "execution_count": 40, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# Example 7: Example 2 reverse pyramid Method 2\n", - "\n", - "for i in range(5,0,-1): # range from 5 4 3 2 1\n", - " for j in range(0,i): # range(0,5)=0 1 2 3 4\n", - " print(i, end=\" \")\n", - " print(\" \")\n", - " \n", - "\"\"\"\n", - "i = 5 4 3 2 1 \n", - "\n", - "# loop 1\n", - "for i = 5, range (0,5): j=5 4 3 2 1\n", - "i = 5, print: 5 5 5 5 5\n", - "\n", - "# loop 2\n", - "for i = 4, range (0,4): j=4 3 2 1\n", - "i = 4, print: 4 4 4 4 \n", - "\"\"\"" - ] - }, - { - "cell_type": "code", - "execution_count": 41, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:36.414154Z", - "start_time": "2021-06-26T15:20:36.402441Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1 2 3 4 5 \n", - "1 2 3 4 \n", - "1 2 3 \n", - "1 2 \n", - "1 \n" - ] - } - ], - "source": [ - "# Example 8: Method 1\n", - "\n", - "for i in range(5,0,-1): # rows range = 5 4 3 2 1 \n", - " for j in range(1,i+1): # column range \n", - " print(j, end =\" \")\n", - " print()" - ] - }, - { - "cell_type": "code", - "execution_count": 42, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:36.742278Z", - "start_time": "2021-06-26T15:20:36.729582Z" - }, - "scrolled": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1 2 3 4 5 \n", - "1 2 3 4 \n", - "1 2 3 \n", - "1 2 \n", - "1 \n" - ] - }, - { - "data": { - "text/plain": [ - "'\\ni = 1 2 3 4 5 \\n\\n# loop 1\\nfor i = 1, range (5): j=0 1 2 3 4\\ni = 1, print: 1 2 3 4 5\\n\\n# loop 2\\nfor i = 2, range (4): j=0 1 2 3\\ni = 2, print: 1 2 3 4\\n\\n# loop 3\\nfor i = 3, range (3): j=0 1 2\\ni = 3, print: 1 2 3\\n\\n# loop 4\\nfor i = 4, range (2): j=0 1\\ni = 4, print: 1 2\\n\\n# loop 5\\nfor i = 5, range (1): j=0 \\ni = 5, print: 1 \\n'" - ] - }, - "execution_count": 42, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# Example 8: Method 2\n", - "\n", - "for i in range(1,6):\n", - " for j in range(6-i):\n", - " print(j+1, end=\" \")\n", - " print(\" \")\n", - " \n", - "\"\"\"\n", - "i = 1 2 3 4 5 \n", - "\n", - "# loop 1\n", - "for i = 1, range (5): j=0 1 2 3 4\n", - "i = 1, print: 1 2 3 4 5\n", - "\n", - "# loop 2\n", - "for i = 2, range (4): j=0 1 2 3\n", - "i = 2, print: 1 2 3 4\n", - "\n", - "# loop 3\n", - "for i = 3, range (3): j=0 1 2\n", - "i = 3, print: 1 2 3\n", - "\n", - "# loop 4\n", - "for i = 4, range (2): j=0 1\n", - "i = 4, print: 1 2\n", - "\n", - "# loop 5\n", - "for i = 5, range (1): j=0 \n", - "i = 5, print: 1 \n", - "\"\"\"" - ] - }, - { - "cell_type": "code", - "execution_count": 43, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:37.336018Z", - "start_time": "2021-06-26T15:20:37.323326Z" - } - }, - "outputs": [], - "source": [ - "# Example 9: Print following rectangle of stars of 6 rows and 3 columns\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### `while` loop inside `for` loop\n", - "\n", - "The **[while loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/006_Python_while_Loop.ipynb)** is an entry-controlled loop, and a **`for`** loop is a count-controlled loop. We can also use a **`while`** loop under the for loop statement. For example," - ] - }, - { - "cell_type": "code", - "execution_count": 44, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:37.463948Z", - "start_time": "2021-06-26T15:20:37.424890Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Multiplication table of: 1\n", - "1 2 3 4 5 6 7 8 9 10 \n", - "\n", - "Multiplication table of: 2\n", - "2 4 6 8 10 12 14 16 18 20 \n", - "\n", - "Multiplication table of: 3\n", - "3 6 9 12 15 18 21 24 27 30 \n", - "\n", - "Multiplication table of: 4\n", - "4 8 12 16 20 24 28 32 36 40 \n", - "\n", - "Multiplication table of: 5\n", - "5 10 15 20 25 30 35 40 45 50 \n", - "\n" - ] - } - ], - "source": [ - "# Example 1: Print Multiplication table of a first 5 numbers using `for` loop and `while` loop\n", - "\n", - "# outer loop\n", - "for i in range(1, 6):\n", - " print('Multiplication table of:', i)\n", - " count = 1\n", - " # inner loop to print multiplication table of current number\n", - " while count < 11:\n", - " print(i * count, end=' ')\n", - " count = count + 1\n", - " print('\\n')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:** \n", - "\n", - "* In this program, we iterate the first five numbers one by one using the outer loop and range function\n", - "* Next, in each iteration of the outer loop, we will use the inner while loop to print the multiplication table of the current number" - ] - }, - { - "cell_type": "code", - "execution_count": 45, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:38.023512Z", - "start_time": "2021-06-26T15:20:38.008869Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Amy Amy Amy Amy Amy \n", - "Bella Bella Bella Bella Bella \n", - "Cathy Cathy Cathy Cathy Cathy \n" - ] - } - ], - "source": [ - "# Example 2:\n", - "\n", - "names = ['Amy', 'Bella', 'Cathy']\n", - "\n", - "for name in names: # outer loop \n", - " count = 0 # inner while loop\n", - " while count < 5:\n", - " print(name, end=' ')\n", - " # increment counter\n", - " count = count + 1\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## `for ` loop in one line\n", - "\n", - "We can also formulate the **`for`** loop statement in one line to reduce the number of lines of code. For example:" - ] - }, - { - "cell_type": "code", - "execution_count": 46, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:38.695380Z", - "start_time": "2021-06-26T15:20:38.679759Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[33, 63, 93, 36, 66, 96, 39, 69, 99]\n" - ] - } - ], - "source": [ - "# Example 1: regular `for` loop code\n", - "\n", - "first = [3, 6, 9]\n", - "second = [30, 60, 90]\n", - "final = []\n", - "for i in first:\n", - " for j in second:\n", - " final.append(i+j)\n", - "print(final)" - ] - }, - { - "cell_type": "code", - "execution_count": 47, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:39.006902Z", - "start_time": "2021-06-26T15:20:38.987373Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[33, 63, 93, 36, 66, 96, 39, 69, 99]\n" - ] - } - ], - "source": [ - "# Example 1: single line `for` loop code\n", - "\n", - "first = [3, 6, 9]\n", - "second = [30, 60, 90]\n", - "final = [i+j for i in first for j in second]\n", - "print(final)" - ] - }, - { - "cell_type": "code", - "execution_count": 48, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:39.272526Z", - "start_time": "2021-06-26T15:20:39.264713Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[2, 6, 8, 10]\n" - ] - } - ], - "source": [ - "# Example 2: Print the even numbers by adding 1 to the odd numbers in the list\n", - "\n", - "odd = [1, 5, 7, 9]\n", - "even = [i + 1 for i in odd if i % 2 == 1]\n", - "print(even)" - ] - }, - { - "cell_type": "code", - "execution_count": 49, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:39.585020Z", - "start_time": "2021-06-26T15:20:39.564518Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[[30, 60], [30, 90], [60, 30], [60, 90], [90, 60], [90, 30]]\n" - ] - } - ], - "source": [ - "# Example 3:\n", - "\n", - "final = [[x, y] for x in [30, 60, 90] for y in [60, 30, 90] if x != y]\n", - "print(final)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Accessing the index in for loop\n", - "\n", - "The **[enumerate()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/018_Python_enumerate%28%29.ipynb)** function is useful when we wanted to access both value and its index number or any sequence such as list or string. For example, a list is an ordered data structure that stores each item with its index number. Using the item’s index number, we can access or modify its value.\n", - "\n", - "Using enumerate function with a loop, we can access the list’s items with their index number. The **`enumerate()`** adds a counter to iteration and returns it in the form of an enumerable object.\n", - "\n", - "There three ways to access the index in **`for`** loop let’s see each one by one" - ] - }, - { - "cell_type": "code", - "execution_count": 50, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:40.193412Z", - "start_time": "2021-06-26T15:20:40.171932Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Numbers[ 0 ] = 4\n", - "Numbers[ 1 ] = 2\n", - "Numbers[ 2 ] = 5\n", - "Numbers[ 3 ] = 7\n", - "Numbers[ 4 ] = 8\n" - ] - } - ], - "source": [ - "# Example 1: Print elements of the list with its index number using the `enumerate()` function\n", - "\n", - "#In this program, the for loop iterates through the list and displays the \n", - "#elements along with its index number.\n", - "\n", - "numbers = [4, 2, 5, 7, 8]\n", - "for i, v in enumerate(numbers):\n", - " print('Numbers[', i, '] =', v)\n" - ] - }, - { - "cell_type": "code", - "execution_count": 51, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:40.505908Z", - "start_time": "2021-06-26T15:20:40.492242Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Index: 0 Value: 1\n", - "Index: 1 Value: 2\n", - "Index: 2 Value: 4\n", - "Index: 3 Value: 6\n", - "Index: 4 Value: 8\n" - ] - } - ], - "source": [ - "# Example 2: Printing the elements of the list with its index number using the `range()` function\n", - "\n", - "numbers = [1, 2, 4, 6, 8]\n", - "size = len(numbers)\n", - "for i in range(size):\n", - " print('Index:', i, \" \", 'Value:', numbers[i])" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Iterate String using `for` loop\n", - "\n", - "By looping through the **[string](https://github.com/milaan9/02_Python_Datatypes/blob/main/002_Python_String.ipynb)** using **`for`** loop, we can do lots of string operations. Let’s see how to perform various string operations using a **`for`** loop." - ] - }, - { - "cell_type": "code", - "execution_count": 52, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:41.301800Z", - "start_time": "2021-06-26T15:20:41.287156Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "H\n", - "e\n", - "l\n", - "l\n", - "o\n", - " \n", - "W\n", - "o\n", - "r\n", - "l\n", - "d\n" - ] - } - ], - "source": [ - "# Example 1: Printing the elements of a string using for loop\n", - "\n", - "for i in 'Hello World':\n", - " print(i)" - ] - }, - { - "cell_type": "code", - "execution_count": 53, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:41.645548Z", - "start_time": "2021-06-26T15:20:41.638711Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "A l a n " - ] - } - ], - "source": [ - "# Example 2: Access all characters of a string\n", - "\n", - "name = \"Alan\"\n", - "for i in name:\n", - " print(i, end=' ')" - ] - }, - { - "cell_type": "code", - "execution_count": 54, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:41.988315Z", - "start_time": "2021-06-26T15:20:41.968788Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "n a l A " - ] - } - ], - "source": [ - "# Example 3: Iterate string in reverse order\n", - "\n", - "name = \"Alan\"\n", - "for i in name[::-1]:\n", - " print(i, end=' ')" - ] - }, - { - "cell_type": "code", - "execution_count": 55, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:42.347689Z", - "start_time": "2021-06-26T15:20:42.339879Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "a n W a " - ] - } - ], - "source": [ - "# Example 4: Iterate over a particular set of characters in string\n", - "\n", - "name = \"Alan Watson\"\n", - "for char in name[2:7:1]:\n", - " print(char, end=' ')" - ] - }, - { - "cell_type": "code", - "execution_count": 56, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:42.690456Z", - "start_time": "2021-06-26T15:20:42.673861Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Remember,\n", - "Red,\n", - "hope\n", - "is\n", - "a\n", - "good\n", - "thing,\n", - "maybe\n", - "the\n", - "best\n", - "of\n", - "things,\n", - "and\n", - "no\n", - "good\n", - "thing\n", - "ever\n", - "dies\n" - ] - } - ], - "source": [ - "# Example 5: Iterate over words in a sentence using the `split()` function.\n", - "\n", - "dialogue = \"Remember, Red, hope is a good thing, maybe the best of things, and no good thing ever dies\"\n", - "# split on whitespace\n", - "for word in dialogue.split():\n", - " print(word)" - ] - }, - { - "cell_type": "code", - "execution_count": 57, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:43.049828Z", - "start_time": "2021-06-26T15:20:43.035185Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "a\n", - "b\n", - "c\n", - "total = 14\n" - ] - } - ], - "source": [ - "# Example 6:\n", - "\n", - "for ch in 'abc':\n", - " print(ch)\n", - "total = 0\n", - "for i in range(5): # from 0 to 4\n", - " total += i # total = 0+1+2+3+4 = 10\n", - "for i,j in [(1,2),(3,1)]: # [(1),(3)]\n", - " total += i**j # total = 1+3 = 4\n", - "print(\"total =\",total)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Iterate List using `for` loop\n", - "\n", - "**[Python list](https://github.com/milaan9/02_Python_Datatypes/blob/main/003_Python_List.ipynb)** is an ordered collection of items of different data types. It means Lists are ordered by index numbers starting from 0 to the total items-1. List items are enclosed in square **`[]`** brackets.\n", - "\n", - "Below are the few examples of Python list.\n", - "\n", - "```python\n", - ">>> numers = [1,2,4,6,7]\n", - ">>> players = [\"Messi\", \"Ronaldo\", \"Neymar\"]\n", - "```\n", - "Using a loop, we can perform various operations on the list. There are ways to iterate through elements in it. Here are some examples to help you understand better." - ] - }, - { - "cell_type": "code", - "execution_count": 58, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:43.752945Z", - "start_time": "2021-06-26T15:20:43.735371Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "2\n", - "3\n", - "6\n", - "9\n" - ] - } - ], - "source": [ - "# Example 1: Iterate over a list Method 1\n", - "\n", - "numbers = [1, 2, 3, 6, 9]\n", - "for num in numbers:\n", - " print(num)" - ] - }, - { - "cell_type": "code", - "execution_count": 59, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:44.126966Z", - "start_time": "2021-06-26T15:20:44.112321Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "2\n", - "3\n", - "6\n", - "9\n" - ] - }, - { - "data": { - "text/plain": [ - "[None, None, None, None, None]" - ] - }, - "execution_count": 59, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# Example 1: Iterate over a list Method 2 (list comprehension)\n", - "\n", - "numbers = [1, 2, 3, 6, 9]\n", - "[print(i) for i in numbers]" - ] - }, - { - "cell_type": "code", - "execution_count": 60, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:44.548837Z", - "start_time": "2021-06-26T15:20:44.533215Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "2\n", - "3\n", - "6\n", - "9\n" - ] - } - ], - "source": [ - "# Example 2: Iterate over a list using a for loop and range.\n", - "\n", - "numbers = [1, 2, 3, 6, 9]\n", - "size = len(numbers)\n", - "for i in range(size):\n", - " print(numbers[i])" - ] - }, - { - "cell_type": "code", - "execution_count": 61, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:45.016606Z", - "start_time": "2021-06-26T15:20:45.003915Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[2, 4, 6, 8, 10]\n", - "[2, 4, 6, 8, 10]\n", - "[2, 4, 6, 8, 10]\n", - "[2, 4, 6, 8, 10]\n", - "[2, 4, 6, 8, 10]\n" - ] - } - ], - "source": [ - "# Example 3: printing the elements of a list using for loop\n", - "\n", - "even_numbers = [2, 4, 6, 8, 10] # list with 5 elements\n", - "for i in even_numbers:\n", - " print(even_numbers)" - ] - }, - { - "cell_type": "code", - "execution_count": 62, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:45.437014Z", - "start_time": "2021-06-26T15:20:45.426272Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "60\n", - "HelloWorld\n", - "90.96\n" - ] - } - ], - "source": [ - "# Example 4: printing the elements of a list using for loop\n", - "\n", - "list = [60, \"HelloWorld\", 90.96]\n", - "for i in list:\n", - " print(i)" - ] - }, - { - "cell_type": "code", - "execution_count": 63, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:45.874509Z", - "start_time": "2021-06-26T15:20:45.856933Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "The sum is 50\n" - ] - } - ], - "source": [ - "# Example 5: Program to find the sum of all numbers stored in a list\n", - "\n", - "# List of numbers\n", - "numbers = [6, 5, 3, 8, 4, 2, 5, 6, 11] # list with 9 elements\n", - "\n", - "# variable to store the sum\n", - "sum = 0\n", - "\n", - "# iterate over the list\n", - "for val in numbers:\n", - " sum = sum+val\n", - "\n", - "print(\"The sum is\", sum)" - ] - }, - { - "cell_type": "code", - "execution_count": 64, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:46.326652Z", - "start_time": "2021-06-26T15:20:46.307123Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Square of: 1 is: 1\n", - "Square of: 2 is: 4\n", - "Square of: 3 is: 9\n", - "Square of: 4 is: 16\n", - "Square of: 5 is: 25\n" - ] - } - ], - "source": [ - "# Example 6: Calculate the square of each number using for loop.\n", - "\n", - "numbers = [1, 2, 3, 4, 5]\n", - "# iterate over each element in list num\n", - "for i in numbers:\n", - " # ** exponent operator\n", - " square = i ** 2\n", - " print(\"Square of:\", i, \"is:\", square)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:** **`i`** iterates over the 0,1,2,3,4. Every time it takes each value and executes the algorithm inside the loop. It is also possible to iterate over a nested list illustrated below." - ] - }, - { - "cell_type": "code", - "execution_count": 65, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:47.295393Z", - "start_time": "2021-06-26T15:20:47.279772Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "30.0\n" - ] - } - ], - "source": [ - "# Example 7: Calculate the average of list of numbers\n", - "\n", - "numbers = [10, 20, 30, 40, 50]\n", - "\n", - "# definite iteration\n", - "# run loop 5 times because list contains 5 items\n", - "sum = 0\n", - "for i in numbers:\n", - " sum = sum + i\n", - "list_size = len(numbers)\n", - "average = sum / list_size\n", - "print(average)" - ] - }, - { - "cell_type": "code", - "execution_count": 66, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:47.825659Z", - "start_time": "2021-06-26T15:20:47.804179Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "3\n", - "Green\n", - "Pink\n", - "Blue\n" - ] - } - ], - "source": [ - "# Example 8: Printing a list using range function\n", - "\n", - "color = ['Green', 'Pink', 'Blue'] # list with total 3 elements\n", - "print(len(color)) # print length of color\n", - "for i in range(len(color)):\n", - " print(color[i])" - ] - }, - { - "cell_type": "code", - "execution_count": 67, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:48.263157Z", - "start_time": "2021-06-26T15:20:48.254369Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[1, 2, 3]\n", - "[4, 5, 6]\n", - "[7, 8, 9]\n" - ] - } - ], - "source": [ - "# Example 9: Printing a list using range function\n", - "\n", - "list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # list with 3 elements\n", - "for list1 in list_of_lists:\n", - " print(list1)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Iterate Dictionary using `for` loop\n", - "\n", - "**[Python dictionary](https://github.com/milaan9/02_Python_Datatypes/blob/main/005_Python_Dictionary.ipynb)** is used to store the items in the format of **key-value** pair. It doesn’t allow duplicate items. It is enclosed with **`{}`**. Here are some of the examples of dictionaries.\n", - "\n", - "```python\n", - ">>> dict1 = {1: \"Apple\", 2: \"Ball\", 3: \"Cat\"}\n", - ">>> dict2 = {\"Antibiotics\": \"Penicillin\", \"Inventor\": \"Fleming\", \"Year\": 1928}\n", - "```\n", - "\n", - "There are ways to iterate through **key-value** pairs. Here are some examples to help you understand better." - ] - }, - { - "cell_type": "code", - "execution_count": 68, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:49.199670Z", - "start_time": "2021-06-26T15:20:49.191861Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Antibiotics\n", - "Inventor\n", - "Year\n" - ] - } - ], - "source": [ - "# Example 1: Access only the keys of the dictionary.\n", - "\n", - "dict1 = {\"Antibiotics\": \"Penicillin\", \"Inventor\": \"Fleming\", \"Year\": 1928}\n", - "for key in dict1:\n", - " print(key)" - ] - }, - { - "cell_type": "code", - "execution_count": 69, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:50.026809Z", - "start_time": "2021-06-26T15:20:50.007282Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Vaccine -> Polio\n", - "Inventor -> Salk\n", - "Year -> 1953\n" - ] - } - ], - "source": [ - "# Example 2: Iterate keys and values of the dictionary\n", - "\n", - "dict1 = {\"Vaccine\": \"Polio\", \"Inventor\": \"Salk\", \"Year\": 1953}\n", - "for key in dict1:\n", - " print(key, \"->\", dict1[key])" - ] - }, - { - "cell_type": "code", - "execution_count": 70, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-26T15:20:50.650826Z", - "start_time": "2021-06-26T15:20:50.640087Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Smallpox \n", - "Jenner\n", - "1796\n" - ] - } - ], - "source": [ - "# Example 3: Iterate only the values the dictionary\n", - "\n", - "dict1 = {\"Vaccine\": \"Smallpox \", \"Inventor\": \"Jenner\", \"Year\": 1796}\n", - "for value in dict1.values():\n", - " print(value)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "hide_input": false, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.8.8" - }, - "toc": { - "base_numbering": 1, - "nav_menu": {}, - "number_sections": true, - "sideBar": true, - "skip_h1_title": false, - "title_cell": "Table of Contents", - "title_sidebar": "Contents", - "toc_cell": false, - "toc_position": {}, - "toc_section_display": true, - "toc_window_display": false - }, - "varInspector": { - "cols": { - "lenName": 16, - "lenType": 16, - "lenVar": 40 - }, - "kernels_config": { - "python": { - "delete_cmd_postfix": "", - "delete_cmd_prefix": "del ", - "library": "var_list.py", - "varRefreshCmd": "print(var_dic_list())" - }, - "r": { - "delete_cmd_postfix": ") ", - "delete_cmd_prefix": "rm(", - "library": "var_list.r", - "varRefreshCmd": "cat(var_dic_list()) " - } - }, - "types_to_exclude": [ - "module", - "function", - "builtin_function_or_method", - "instance", - "_Feature" - ], - "window_display": false - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} From e81c71824d9e31dc5262ed7aff45d1a113045f7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Mon, 11 Oct 2021 20:26:02 +0530 Subject: [PATCH 18/23] Delete 006_Python_while_Loop.ipynb --- 006_Python_while_Loop.ipynb | 1482 ----------------------------------- 1 file changed, 1482 deletions(-) delete mode 100644 006_Python_while_Loop.ipynb diff --git a/006_Python_while_Loop.ipynb b/006_Python_while_Loop.ipynb deleted file mode 100644 index 02dc4a9..0000000 --- a/006_Python_while_Loop.ipynb +++ /dev/null @@ -1,1482 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "All the IPython Notebooks in this lecture series by Dr. Milan Parmar are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)**\n", - "" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Loops in Python\n", - "\n", - "Loops in Python programming function similar to loops in C, C++, Java or other languages. Python loops are used to repeatedly execute a block of statements until a given condition returns to be **`False`**. In Python, we have **two types of looping statements**, namely:\n", - "
\n", - "\n", - "
" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Python `while` Loop\n", - "\n", - "Loops are used in programming to repeat a specific block of code. In this article, you will learn to create a **`while`** loop in Python. We use a **`while`** loop when we want to repeat a code block." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## What is `while` loop in Python?\n", - "\n", - "The **`while`** loop in Python is used to iterate over a block of code as long as the expression/condition is **`True`**. When the condition becomes **`False`**, execution comes out of the loop immediately, and the first statement after the **`while`** loop is executed.\n", - "\n", - "We generally use this loop when we don't know the number of times to iterate beforehand.\n", - "\n", - "Python interprets any non-zero value as **`True`**. **`None`** and **`0`** are interpreted as **`False`**." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Why and When to use `while` loop in Python\n", - "\n", - "Now, the question might arise: when do we use a **`while`** loop, and why do we use it.\n", - "\n", - "* **Automate and repeat tasks:** As we know, **`while`** loops execute blocks of code over and over again until the condition is met it allows us to automate and repeat tasks in an efficient manner.\n", - "* **Indefinite Iteration:**The **`while`** loop will run as often as necessary to complete a particular task. When the user doesn’t know the number of iterations before execution, **`while`** loop is used instead of a **[for loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/005_Python_for_Loop.ipynb)** loop\n", - "* **Reduce complexity:** **`while`** loop is easy to write. using the loop, we don’t need to write the statements again and again. Instead, we can write statements we wanted to execute again and again inside the body of the loop thus, reducing the complexity of the code\n", - "* **Infinite loop:** If the code inside the **`while`** loop doesn’t modify the variables being tested in the loop condition, the loop will run forever." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Syntax: \n", - "\n", - "```python\n", - "while condition:\n", - " body of while loop\n", - "```\n", - "1. In the **`while`** loop, expression/condition is checked first.\n", - "2. The body of the loop is entered only if the expression/condition evaluates to **`True`**.\n", - "3. After one iteration, the expression/condition is checked again. This process continues until the test_expression evaluates to **`False`**.\n", - "\n", - "
\n", - "\n", - "
\n", - "\n", - ">**Note:** An infinite loop occurs when a program keeps executing within one loop, never leaving it. To exit out of infinite loops on the command line, press **CTRL + C**." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:52:23.934629Z", - "start_time": "2021-06-14T08:52:23.927796Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "2\n", - "3\n", - "4\n" - ] - } - ], - "source": [ - "# Example 1: Print numbers less than 5\n", - "\n", - "count = 1\n", - "# run loop till count is less than 5\n", - "while count < 5:\n", - " print(count)\n", - " count = count + 1" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:52:24.668023Z", - "start_time": "2021-06-14T08:52:24.647518Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Sum of first 10 number is: 55\n" - ] - } - ], - "source": [ - "# Example 2:\n", - "\n", - "num = 10\n", - "sum = 0\n", - "i = 1\n", - "while i <= num:\n", - " sum = sum + i\n", - " i = i + 1\n", - "print(\"Sum of first 10 number is:\", sum)" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:52:25.267142Z", - "start_time": "2021-06-14T08:52:25.255427Z" - }, - "scrolled": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Value of a is 10\n", - "Value of a is 8\n", - "Value of a is 6\n", - "Value of a is 4\n", - "Value of a is 2\n", - "Loop is Completed\n" - ] - } - ], - "source": [ - "# Example 3:\n", - "\n", - "a=10 # 'a' is my variable\n", - "\n", - "while a>0: # Enter the body of while loop because condition is TRUE\n", - " print ((\"Value of a is\"),a)\n", - " a=a-2\n", - "print (\"Loop is Completed\")" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:52:27.189010Z", - "start_time": "2021-06-14T08:52:27.167527Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "9.999999999999998\n" - ] - } - ], - "source": [ - "# Example 4:\n", - "\n", - "n=153\n", - "sum=0\n", - "\n", - "while n>0:\n", - " r=n%10 # r is the remainder of the division\n", - " sum+=r # sum+=r is equal to sum = sum+r\n", - " n=n/10\n", - "print (sum)" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:52:27.836467Z", - "start_time": "2021-06-14T08:52:27.815961Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Total iteration required 3\n" - ] - } - ], - "source": [ - "# Example 5: How many times a given number can be divided by 3 before it is less than or equal to 10.\n", - "\n", - "count = 0\n", - "number = 180\n", - "while number > 10:\n", - " # divide number by 3\n", - " number = number / 3\n", - " # increase count\n", - " count = count + 1\n", - "print('Total iteration required', count)" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:52:29.455600Z", - "start_time": "2021-06-14T08:52:29.447790Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "The sum is 55\n" - ] - } - ], - "source": [ - "# Example 6: Program to add natural numbers up to sum = 1+2+3+...+n\n", - "\n", - "# To take input from the user, \n", - "# n = int(input(\"Enter n: \"))\n", - "\n", - "n = 10\n", - "\n", - "# initialize sum and counter\n", - "sum = 0\n", - "i = 1\n", - "\n", - "while i <= n:\n", - " sum = sum + i\n", - " i = i+1 # update counter, i.e., the value of i will change from 1 to 2 in next iteration...\n", - "\n", - "# print the sum\n", - "print(\"The sum is\", sum)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "In the above program, the test expression will be **`True`** as long as our counter variable **`i`** is less than or equal to **`n`** (10 in our program).\n", - "\n", - "We need to increase the value of the counter variable in the body of the loop. This is very important (and mostly forgotten). Failing to do so will result in an infinite loop (never-ending loop).\n", - "\n", - "Finally, the result is displayed." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## `while` loop with `if-else`\n", - "\n", - "A **`while`** loop can have an optional **[if-else](https://github.com/milaan9/03_Python_Flow_Control/blob/main/002_Python_if_else_statement.ipynb)** block. We use **`if-else`** statement in the loop when conditional iteration is needed. i.e., If the condition is **`True`**, then the statements inside the if block will execute othwerwise, the else block will execute." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:52:37.765141Z", - "start_time": "2021-06-14T08:52:31.408720Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Please Enter Number 9\n", - "9 is a odd number\n", - "8 is a even number\n", - "7 is a odd number\n", - "6 is a even number\n", - "5 is a odd number\n", - "4 is a even number\n", - "3 is a odd number\n", - "2 is a even number\n", - "1 is a odd number\n" - ] - } - ], - "source": [ - "# Example 1: Print even and odd numbers between 1 to the entered number.\n", - "\n", - "n = int(input('Please Enter Number '))\n", - "while n > 0:\n", - " # check even and odd\n", - " if n % 2 == 0:\n", - " print(n, 'is a even number')\n", - " else:\n", - " print(n, 'is a odd number')\n", - " # decrease number by 1 in each iteration\n", - " n = n - 1" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:52:37.901851Z", - "start_time": "2021-06-14T08:52:37.875485Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "2\n", - "9\n", - "4\n", - "25\n", - "6\n", - "49\n", - "8\n", - "81\n" - ] - } - ], - "source": [ - "# Example 2: printing the square of odd numbers less than n. \n", - "\n", - "n =10\n", - "i = 1\n", - "while i < n:\n", - " #if (i % 2 == 0): (for even numbers)\n", - " if (i % 2 != 0):\n", - " print(i ** 2)\n", - " i = i + 1\n", - " else:\n", - " print(i)\n", - " i = i + 1" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:52:45.455039Z", - "start_time": "2021-06-14T08:52:45.442346Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "The sum is 30\n" - ] - } - ], - "source": [ - "# Example 3: Add all even numbers from 1 to 10 using while loop\n", - "# 2+4+6+8+10\n", - "\n", - "# n = int(input(\"Please enter the maximum value: \"))\n", - "n = 10\n", - "\n", - "sum = 0\n", - "i = 1\n", - "\n", - "while i <= n:\n", - " if(i%2==0):\n", - " sum = sum + i\n", - "# sum += i\n", - " i = i+1\n", - " \n", - "# print the sum\n", - "print(\"The sum is\", sum)" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:52:48.045357Z", - "start_time": "2021-06-14T08:52:48.024854Z" - }, - "code_folding": [], - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "17\n", - "19\n", - "23\n", - "29\n", - "31\n", - "37\n", - "41\n", - "43\n", - "47\n", - "53\n", - "The total sum is 340\n" - ] - } - ], - "source": [ - "# Example 4: Write a code to add all the prime numbers between 17 to 53 using while loop\n", - "# 17, 19, 23, 29, 31, 37, 41, 43, 47, 53\n", - "\n", - "'''Method 1'''\n", - "\n", - "sum=0\n", - "for i in range(17,54):\n", - " k=2\n", - " if i>=2:\n", - " while i % k!=0:\n", - " k+=1\n", - " if i==k:\n", - " sum += i\n", - " print(i)\n", - "print(\"The total sum is\",sum)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## `while` loop with `else`\n", - "\n", - "A **`while`** loop can have an optional **`else`** block as well. The **`else`** part is executed if the condition in the **`while`** loop evaluates to **`False`**.\n", - "\n", - "The **`else`** will be skipped/ignored when:\n", - "\n", - "* **`while`** loop terminates abruptly\n", - "* The **[break statement](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)** is used to break the **`while`** loop" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:52:49.752872Z", - "start_time": "2021-06-14T08:52:49.745062Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "2\n", - "3\n", - "4\n", - "5\n", - "6\n", - "Done. 'while loop' executed normally\n" - ] - } - ], - "source": [ - "# Example 1: Use while loop to print numbers from 1 to 6\n", - "\n", - "i = 1\n", - "while i <= 6:\n", - " print(i)\n", - " i = i + 1\n", - "else:\n", - " print(\"Done. 'while loop' executed normally\")" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:52:50.591736Z", - "start_time": "2021-06-14T08:52:50.583927Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "2\n", - "3\n" - ] - } - ], - "source": [ - "# Example 2: Else block with break statement in a while loop.\n", - "\n", - "i = 1\n", - "while i <= 6:\n", - " print(i)\n", - " if i == 3:\n", - " break\n", - " i = i + 1\n", - "else:\n", - " print(\"Done. `while loop` executed normally\")" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:52:51.204038Z", - "start_time": "2021-06-14T08:52:51.188413Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Inside while loop\n", - "Inside while loop\n", - "Inside while loop\n", - "Inside else\n" - ] - } - ], - "source": [ - "# Example 3:\n", - "'''Example to illustrate the use of else statement with the while loop'''\n", - "\n", - "counter = 0 # counter is my variable\n", - "\n", - "while counter < 3:\n", - " print(\"Inside while loop\")\n", - " counter = counter + 1 # increment the counter\n", - "else:\n", - " print(\"Inside else\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "Here, we use a **`counter`** variable to print the string **`Inside loop`** three times.\n", - "\n", - "On the fourth iteration, the condition in **`while`** becomes **`False`**. Hence, the **`else`** part is executed." - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:53:01.391979Z", - "start_time": "2021-06-14T08:52:52.585381Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Enter any number between 100 and 600 369\n", - "Given Number is correct 369\n" - ] - } - ], - "source": [ - "# Example 4: we want a user to enter any number between 100 and 600\n", - "\n", - "number = int(input('Enter any number between 100 and 600 '))\n", - "# number greater than 100 and less than 600\n", - "while number < 100 or number > 600:\n", - " print('Incorrect number, Please enter correct number:')\n", - " number = int(input('Enter a Number between 100 and 600 '))\n", - "else:\n", - " print(\"Given Number is correct\", number)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Using Control Statement in `while` loops in Python\n", - "\n", - "**[Control statements](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)** in Python like **`break`**, **`continue`**, etc can be used to control the execution flow of **`while`** loop in Python. Let us now understand how this can be done.\n", - "\n", - "It is used when you want to exit a loop or skip a part of the loop based on the given condition. It also knows as **transfer statements**." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### a) `break` in `while` loop\n", - "\n", - "Using the **`break`** statement, we can exit from the **`while`** loop even if the condition is **`True`**. \n", - "\n", - "If the **`break`** statement is used inside a nested loop (loop inside another loop), it will terminate the innermost loop. For example," - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:53:08.314316Z", - "start_time": "2021-06-14T08:53:08.298691Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "60\n", - "HelloWorld\n", - "90.45\n" - ] - } - ], - "source": [ - "# Example 1:\n", - "\n", - "list = [60, \"HelloWorld\", 90.45, 50, 67.23, \"Python\"] # total 6 elements\n", - "i = 0\n", - "while(i < 6):\n", - " print(list[i])\n", - " i = i + 1\n", - " if(i == 3):\n", - " break" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation**: \n", - "\n", - "Here, the **`while`** loop runs until the value of the variable **`i`** is less than 6. But because of the **`break`** statement, the loop gets terminated when the value of the variable **`i`** is 3." - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:53:09.871435Z", - "start_time": "2021-06-14T08:53:09.849953Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "A l a n " - ] - } - ], - "source": [ - "# Example 2: Display each character from a string and if `a` character is number then stop the loop.\n", - "\n", - "name = 'Alan99White'\n", - "size = len(name)\n", - "i = 0\n", - "# iterate loop till the last character\n", - "while i < size:\n", - " # break loop if current character is number\n", - " if name[i].isdecimal():\n", - " break;\n", - " # print current character\n", - " print(name[i], end=' ')\n", - " i = i + 1" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### b) `continue` in while loop\n", - "\n", - "The **`continue`** statement is used to stop/skip the block of code in the loop for the current iteration only and continue with the next iteration. \n", - "\n", - "For example, let's say you want to print all the odd numbers less than a particular value. Here is how you can do it using **`continue`** keyword in Python." - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:53:11.585296Z", - "start_time": "2021-06-14T08:53:11.574556Z" - }, - "code_folding": [] - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "3\n", - "5\n", - "7\n", - "9\n" - ] - } - ], - "source": [ - "# Example 1: printing odd numbers less than `n`\n", - "\n", - "n=10\n", - "i = 1\n", - "while (i < n):\n", - " if (i % 2 == 0):\n", - " i = i + 1\n", - " continue # continue means skip the current loop\n", - " else:\n", - " print (i)\n", - " i = i + 1" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Explanation:**\n", - "\n", - "Here, the continue statement gets executed when the value of the variable is an even number. This simply means, whenever it is an even number, we simply skip all other statements and execute the next iteration." - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:53:13.071129Z", - "start_time": "2021-06-14T08:53:13.056484Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "A l a n W h i t e " - ] - } - ], - "source": [ - "# Example 2: Write a while loop to display only alphabets from a string.\n", - "\n", - "name = 'Alan99White'\n", - "\n", - "size = len(name)\n", - "i = -1\n", - "# iterate loop till the last character\n", - "while i < size - 1:\n", - " i = i + 1\n", - " # skip while loop body if current character is not alphabet\n", - " if not name[i].isalpha():\n", - " continue\n", - " # print current character\n", - " print(name[i], end=' ')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### c) `pass` in `while` loop\n", - "\n", - "The **`pass`** statement is a null statement, i.e., nothing happens when the statement is executed. Primarily it is used in empty functions or classes. When the interpreter finds a pass statement in the program, it returns no operation." - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:53:14.653641Z", - "start_time": "2021-06-14T08:53:14.638020Z" - } - }, - "outputs": [], - "source": [ - "# Example 1:\n", - "\n", - "n = 4\n", - "while n > 0:\n", - " n = n - 1\n", - " pass" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Reverse `while` loop\n", - "\n", - "A reverse loop means an iterating loop in the backward direction. A simple example includes:\n", - "\n", - "* Display numbers from 10 to 1.\n", - "* Reverse a string or list" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:53:16.266917Z", - "start_time": "2021-06-14T08:53:16.257152Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "10 9 8 7 6 5 4 3 2 1 0 " - ] - } - ], - "source": [ - "# Example 1: Reverse a while loop to display numbers from 10 to 1\n", - "\n", - "# reverse while loop\n", - "i = 10\n", - "while i >= 0:\n", - " print(i, end=' ')\n", - " i = i - 1" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Nested `while` loops\n", - "\n", - "**Nested while loop** is a **`while`** loop inside another **`while`** a loop. \n", - "\n", - "In the nested **`while`** loop, the number of iterations will be equal to the number of iterations in the outer loop multiplied by the iterations in the inner loop. In each iteration of the outer loop inner loop execute all its iteration.\n", - "\n", - "**Syntax:**\n", - "\n", - "```python\n", - "while expression:\n", - " while expression:\n", - " statement(s)\n", - " statement(s)\n", - "```" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### `while` loop inside `while` loop" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Example: Nested `while` loop" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:53:19.515435Z", - "start_time": "2021-06-14T08:53:19.497371Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "12345678910\n", - "12345678910\n", - "12345678910\n" - ] - } - ], - "source": [ - "# Example: print the first 10 numbers on each line 5 times\n", - "\n", - "i = 1\n", - "while i <= 3:\n", - " j = 1\n", - " while j <= 10:\n", - " print(j, end='')\n", - " j = j + 1\n", - " i = i + 1\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Example: Nested `while` loop to print the pattern\n", - "\n", - "```python\n", - "*\n", - "* *\n", - "* * *\n", - "* * * *\n", - "* * * * *\n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:53:21.297164Z", - "start_time": "2021-06-14T08:53:21.281542Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "* \n", - "* * \n", - "* * * \n", - "* * * * \n", - "* * * * * \n" - ] - } - ], - "source": [ - "# Example 1: Method 1\n", - "\n", - "i = 1\n", - "# outer while loop\n", - "# 5 rows in pattern\n", - "while i < 6:\n", - " j = 0\n", - " # nested while loop\n", - " while j < i:\n", - " print('*', end=' ')\n", - " j = j + 1\n", - " # end of nested while loop\n", - " # new line after each row\n", - " print('')\n", - " i = i + 1" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### `for` loop inside `while` loop\n", - "\n", - "We can also use **[for loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/005_Python_for_Loop.ipynb)** inside a **`while`** loop as a nested loop. For example, " - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:53:23.125769Z", - "start_time": "2021-06-14T08:53:23.105263Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "* \n", - "* * \n", - "* * * \n", - "* * * * \n", - "* * * * * \n" - ] - } - ], - "source": [ - "# Example 1: Method 2\n", - "\n", - "i = 1\n", - "# outer while loop\n", - "while i < 6:\n", - " # nested for loop\n", - " for j in range(1, i + 1):\n", - " print(\"*\", end=\" \")\n", - " print('')\n", - " i = i + 1" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:53:23.996860Z", - "start_time": "2021-06-14T08:53:23.985143Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "17\n", - "19\n", - "23\n", - "29\n", - "31\n", - "37\n", - "41\n", - "43\n", - "47\n", - "53\n", - "The total sum is 340\n" - ] - } - ], - "source": [ - "# Example 2: Write a code to add all the prime numbers between 17 to 53 using while loop\n", - "# 17, 19, 23, 29, 31, 37, 41, 43, 47, 53\n", - "\n", - "'''Method 1'''\n", - "\n", - "n=17\n", - "sum=0\n", - "while n<=53:\n", - " for i in range(2,n):\n", - " if(n % i)== 0: \n", - " break\n", - " else:\n", - " i=i+1\n", - " else:\n", - " sum=sum+n\n", - " print(n)\n", - " n=n+1\n", - "print(\"The total sum is\",sum)" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:53:24.991975Z", - "start_time": "2021-06-14T08:53:24.979278Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Show Perfect number fom 1 to 100\n", - "Perfect number: 6\n", - "Perfect number: 28\n" - ] - } - ], - "source": [ - "# Example 3:\n", - "\n", - "print('Show Perfect number fom 1 to 100')\n", - "n = 2\n", - "\n", - "while n <= 100: # outer while loop\n", - " x_sum = 0 \n", - " for i in range(1, n): # inner for loop\n", - " if n % i == 0:\n", - " x_sum += i\n", - " if x_sum == n:\n", - " print('Perfect number:', n)\n", - " n += 1" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Iterate String using `while` loop\n", - "\n", - "By looping through the **[string](https://github.com/milaan9/02_Python_Datatypes/blob/main/002_Python_String.ipynb)** using **`while`** loop, we can do lots of string operations. For example," - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:53:26.480251Z", - "start_time": "2021-06-14T08:53:26.472433Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "A\n", - "l\n", - "a\n", - "n\n" - ] - } - ], - "source": [ - "# Example 1: while loop to iterate string letter by letter\n", - "\n", - "name = \"Alan\"\n", - "i = 0\n", - "res = len(name) - 1\n", - "while i <= res:\n", - " print(name[i])\n", - " i = i + 1" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Iterate List using `while` loop\n", - "\n", - "**[Python list](https://github.com/milaan9/02_Python_Datatypes/blob/main/003_Python_List.ipynb)** is an ordered collection of items of different data types. It means Lists are ordered by index numbers starting from 0 to the total items-1. List items are enclosed in square **`[]`** brackets.\n", - "\n", - "Below are the few examples of Python list.\n", - "\n", - "```python\n", - ">>> numers = [1,2,4,6,7]\n", - ">>> players = [\"Messi\", \"Ronaldo\", \"Neymar\"]\n", - "```\n", - "Using a loop, we can perform various operations on the list. There are ways to iterate through elements in it. Here are some examples to help you understand better." - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:53:27.906995Z", - "start_time": "2021-06-14T08:53:27.889421Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "2\n", - "3\n", - "6\n", - "9\n" - ] - } - ], - "source": [ - "# Example 1: Use while loop to iterate over a list.\n", - "\n", - "numbers = [1, 2, 3, 6, 9]\n", - "size = len(numbers)\n", - "i = 0\n", - "while i < size:\n", - " print(numbers[i])\n", - " i = i + 1" - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:53:28.690197Z", - "start_time": "2021-06-14T08:53:28.681409Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "60\n", - "HelloWorld\n" - ] - } - ], - "source": [ - "# Example 2: printing the first two elements of a list\n", - "\n", - "list = [60, \"HelloWorld\", 90.96] # list with three elements\n", - "i = 0\n", - "while(i < 2):\n", - " print (list[i]) #printing the element in the index i\n", - " i = i + 1 " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - ">**Note**: When working with the **`while`** loop, it is important to declare the indexing variable **`i`** beforehand and to increment the indexing variable accordingly. Else it will result in an infinite loop." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Iterate Numbers using `while` loop\n", - "\n", - "Now, consider a program where you want to print out the squares of all the **[numbers](https://github.com/milaan9/02_Python_Datatypes/blob/main/001_Python_Numbers.ipynb)** less a particular number. Let's see how this works with a while statement." - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:53:31.143799Z", - "start_time": "2021-06-14T08:53:31.121339Z" - }, - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "4\n", - "9\n", - "16\n", - "25\n", - "36\n", - "49\n", - "64\n", - "81\n", - "100\n" - ] - } - ], - "source": [ - "# Example 1: printing the square of numbers less than `n`\n", - "\n", - "i = 1\n", - "while (i <= 10):\n", - " print (i ** 2) #printing the element in the index i\n", - " i = i + 1" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:53:32.006098Z", - "start_time": "2021-06-14T08:53:31.985594Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "8\n", - "27\n", - "64\n", - "125\n", - "216\n", - "343\n", - "512\n", - "729\n" - ] - } - ], - "source": [ - "# Example 2: Find the cube of number from 1 to 9.\n", - "\n", - "i = 1\n", - "while(i<10):\n", - " print(i*i*i)\n", - "# print(i**3)\n", - " i=i+1" - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "metadata": { - "ExecuteTime": { - "end_time": "2021-06-14T08:53:32.913808Z", - "start_time": "2021-06-14T08:53:32.905023Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "4\n", - "Loop over\n" - ] - } - ], - "source": [ - "# Example 3:\n", - "\n", - "i = 1\n", - "while i < 3:\n", - " print(i ** 2)\n", - " i = i+1\n", - "print('Loop over')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## While loop in Python FAQs\n", - "\n", - "\n", - "1. A while loop in python is used for what type of iteration?\n", - "> A while loop is ideal for iteration when the number of iterations is not known. Also, it is ideal to use a while loop when you have a condition that needs to be satisfied.\n", - "\n", - "\n", - "2. Why does infinite while loop occur in Python?\n", - "> A loop becomes an infinite loop if the while condition never becomes FALSE. Such a loop that never terminates is called an infinite loop.\n", - "\n", - "\n", - "3. Is there a do...while loop in Python?\n", - ">No. There is no do while loop in Python.\n", - "\n", - "\n", - "4. How do you break a while loop in Python?\n", - ">Usually, the control shifts out of the while loop when the while condition is no False. Or you can use various control statements like break, continue, etc to break out of the while loop or break of the particular iteration of the while loop.\n", - "\n", - "\n", - "5. How to write an empty while function in Python?\n", - ">You can write an empty while function in Python using the pass statements. Here is how you can write it.\n", - "\n", - "```python\n", - "#empty while statement in python\n", - ">>> i = 0\n", - ">>> while (i < 10) :\n", - ">>> pass\n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "hide_input": false, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.8.8" - }, - "toc": { - "base_numbering": 1, - "nav_menu": {}, - "number_sections": true, - "sideBar": true, - "skip_h1_title": false, - "title_cell": "Table of Contents", - "title_sidebar": "Contents", - "toc_cell": false, - "toc_position": {}, - "toc_section_display": true, - "toc_window_display": false - }, - "varInspector": { - "cols": { - "lenName": 16, - "lenType": 16, - "lenVar": 40 - }, - "kernels_config": { - "python": { - "delete_cmd_postfix": "", - "delete_cmd_prefix": "del ", - "library": "var_list.py", - "varRefreshCmd": "print(var_dic_list())" - }, - "r": { - "delete_cmd_postfix": ") ", - "delete_cmd_prefix": "rm(", - "library": "var_list.r", - "varRefreshCmd": "cat(var_dic_list()) " - } - }, - "types_to_exclude": [ - "module", - "function", - "builtin_function_or_method", - "instance", - "_Feature" - ], - "window_display": false - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} From 1889b865b6c9bddd3a43323400a6db1ca490ff45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Mon, 11 Oct 2021 20:26:34 +0530 Subject: [PATCH 19/23] updates with more examples and exercises --- 000_Python_Flow_Control_statement .ipynb | 168 + 001_Python_if_statement.ipynb | 423 ++ 002_Python_if_else_statement.ipynb | 591 +++ 003_Python_if_elif_else_statement .ipynb | 486 +++ 004_Python_Nested_if_statement.ipynb | 304 ++ 005_Python_for_Loop.ipynb | 3385 +++++++++++++++++ 006_Python_while_Loop.ipynb | 1646 ++++++++ ...ython_break_continue_pass_statements.ipynb | 1308 +++++++ 8 files changed, 8311 insertions(+) create mode 100644 000_Python_Flow_Control_statement .ipynb create mode 100644 001_Python_if_statement.ipynb create mode 100644 002_Python_if_else_statement.ipynb create mode 100644 003_Python_if_elif_else_statement .ipynb create mode 100644 004_Python_Nested_if_statement.ipynb create mode 100644 005_Python_for_Loop.ipynb create mode 100644 006_Python_while_Loop.ipynb create mode 100644 007_Python_break_continue_pass_statements.ipynb diff --git a/000_Python_Flow_Control_statement .ipynb b/000_Python_Flow_Control_statement .ipynb new file mode 100644 index 0000000..099d254 --- /dev/null +++ b/000_Python_Flow_Control_statement .ipynb @@ -0,0 +1,168 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "All the IPython Notebooks in **Python Flow Control Statements** lecture series by Dr. Milaan Parmar are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)**\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Python Flow-Control (Decision-Making) Statements\n", + "\n", + "In Python programming, decision-making statements are those that **help in deciding the flow of the program**. \n", + "\n", + "For example, at times, you might want to execute a block of code only if a particular condition is satisfied. Well, in this case, decision-making statement will be of great help. Let us consider an example to understand this better.\n", + "\n", + "Decision making is required when we want to execute a code only if a certain condition is satisfied.\n", + "\n", + "The key thing to note about Python's control flow statements and program structure is that it uses **`_indentation_`** to mark blocks. Hence the amount of white space (space or tab characters) at the start of a line is very important. This generally helps to make code more readable but can catch out new users of python." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* Suppose you are given a number and are asked to check if it is an even number or not. How would you do it?\n", + "\n", + "> The first thought that would pop up your mind is this - **\"If the number is divisible by 2, then it is an even number, else it is an odd number\"**. That's absolutely the right logic. But when this has to be coded, you will need the help of decision-making statements. To understand this, let's now look at how they function." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Control Flow Statements\n", + "\n", + "The flow control statements are divided into **three** categories:\n", + "\n", + "1. **Conditional statements**\n", + "2. **Iterative statements**\n", + "3. **Transfer/Control statements**\n", + "\n", + "
\n", + "\n", + "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Conditional statements\n", + "\n", + "In Python, condition statements act depending on whether a given condition is true or false. You can execute different blocks of codes depending on the outcome of a condition. Condition statements always evaluate to either **`True`** or **`False`**.\n", + "\n", + "There are **four** types of conditional statements:\n", + "\n", + "1. **[if](https://github.com/milaan9/03_Python_Flow_Control/blob/main/001_Python_if_statement.ipynb)**\n", + "2. **[if-else](https://github.com/milaan9/03_Python_Flow_Control/blob/main/002_Python_if_else_statement.ipynb)**\n", + "3. **[if-elif-else](https://github.com/milaan9/03_Python_Flow_Control/blob/main/003_Python_if_elif_else_statement%20.ipynb)**\n", + "4. **[nested-if](https://github.com/milaan9/03_Python_Flow_Control/blob/main/004_Python_Nested_if_statement.ipynb)**" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Iterative statements\n", + "\n", + "In Python, iterative statements allow us to execute a block of code repeatedly as long as the condition is **`True`**. We also call it a loop statements.\n", + "\n", + "Python provides us the following **two** loop statement to perform some actions repeatedly\n", + "\n", + "1. **[for loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/005_Python_for_Loop.ipynb)**\n", + "2. **[while loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/006_Python_while_Loop.ipynb)**" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Transfer statements\n", + "\n", + "In Python, transfer statements are used to alter the program’s way of execution in a certain manner. For this purpose, we use **three** types of transfer statements.\n", + "\n", + "1. **[break statement](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)**\n", + "2. **[continue statement](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)**\n", + "3. **[pass statements](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "hide_input": false, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.8" + }, + "toc": { + "base_numbering": 1, + "nav_menu": {}, + "number_sections": true, + "sideBar": true, + "skip_h1_title": false, + "title_cell": "Table of Contents", + "title_sidebar": "Contents", + "toc_cell": false, + "toc_position": {}, + "toc_section_display": true, + "toc_window_display": false + }, + "varInspector": { + "cols": { + "lenName": 16, + "lenType": 16, + "lenVar": 40 + }, + "kernels_config": { + "python": { + "delete_cmd_postfix": "", + "delete_cmd_prefix": "del ", + "library": "var_list.py", + "varRefreshCmd": "print(var_dic_list())" + }, + "r": { + "delete_cmd_postfix": ") ", + "delete_cmd_prefix": "rm(", + "library": "var_list.r", + "varRefreshCmd": "cat(var_dic_list()) " + } + }, + "types_to_exclude": [ + "module", + "function", + "builtin_function_or_method", + "instance", + "_Feature" + ], + "window_display": false + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/001_Python_if_statement.ipynb b/001_Python_if_statement.ipynb new file mode 100644 index 0000000..a25310c --- /dev/null +++ b/001_Python_if_statement.ipynb @@ -0,0 +1,423 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "All the IPython Notebooks in **Python Flow Control Statements** lecture series by Dr. Milaan Parmar are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)**\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Python `if` statement\n", + "\n", + "In control statements, The **`if`** statement is the simplest form. It takes a condition and evaluates to either **`True`** or **`False`**.\n", + "\n", + "If the condition is **`True`**, then the **`True`** block of code will be executed, and if the condition is **`False`**, then the block of code is skipped, and The controller moves to the next line." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Syntax:\n", + "\n", + "```python\n", + "if(condition):\n", + " statement 1\n", + " statement 2\n", + " statement n\n", + "```\n", + "\n", + "* An **`if`** statement should be preceded by the keyword **`if`** and ended with a colon **`:`**. The condition of an if statement can be written with or without round brackets **`()`**.\n", + "\n", + "* In Python, the body of the **`if`** statement is indicated by the indentation. The body starts with an indentation and the first unindented line marks the end.\n", + "\n", + "* Python interprets non-zero values as **`True`**. **`None`** and **`0`** are interpreted as **`False`**.\n", + "\n", + "
\n", + "\n", + "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Example: of `if` statement:**\n", + "\n", + "```python\n", + ">>> grade = 70\n", + ">>> if grade >= 65:\n", + ">>> print(\"Passing grade\")\n", + "\n", + "Passing grade\n", + "```\n", + "\n", + "With this code, we have the variable grade and are giving it the integer value of 70. We are then using the **`if`** statement to evaluate whether or not the variable grade is **greater than or equal `>=`** to 65. If it does meet this **condition**, we are telling the program to print out the string Passing grade. \n", + "\n", + "Again, if we change the grade to 50 or < 65 number, we will receive no output." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-10T20:03:33.690723Z", + "start_time": "2021-06-10T20:03:33.674172Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Passing grade\n" + ] + } + ], + "source": [ + "# Example 1:\n", + "grade = 70\n", + "if grade >= 65:\n", + " print(\"Passing grade\")" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-10T20:03:34.440566Z", + "start_time": "2021-06-10T20:03:34.422066Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "3 is a positive number.\n", + "This is always printed.\n", + "This is also always printed.\n" + ] + } + ], + "source": [ + "# Example 2: If the number is positive, we print an appropriate message\n", + "\n", + "num = 3\n", + "if (num > 0): # if condition is TRUE: enter the body of if\n", + " print(num, \"is a positive number.\")\n", + "print(\"This is always printed.\")\n", + "\n", + "num = -1\n", + "if num > 0: # if condition is FALSE: do not enter the body of if\n", + " print(num, \"is a negative number.\")\n", + "print(\"This is also always printed.\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation**:\n", + "\n", + "In the above example, **`num > 0`** is the test expression.\n", + "\n", + "The body of **`if`** is executed only if this evaluates to **`True`**.\n", + "\n", + "When the variable **`num`** is equal to 3, test expression is true and statements inside the body of **`if`** are executed.\n", + "\n", + "If the variable **`num`** is equal to -1, test expression is false and statements inside the body of **`if`** are skipped.\n", + "\n", + "The **[print()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/051_Python_print%28%29.ipynb)** statement falls outside of the **`if`** block (unindented). Hence, it is executed regardless of the test expression." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-10T20:03:35.580430Z", + "start_time": "2021-06-10T20:03:35.571663Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "81\n", + "Next lines of code\n" + ] + } + ], + "source": [ + "# Example 3: Calculate the square of a number if it greater than 6\n", + "\n", + "number = 9\n", + "if number > 6:\n", + " # Calculate square\n", + " print(number * number)\n", + "print('Next lines of code')" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-10T20:03:36.158393Z", + "start_time": "2021-06-10T20:03:36.145731Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "num1 is less than num2\n" + ] + } + ], + "source": [ + "# Example 4: Check if num1 is less than num2\n", + "\n", + "num1, num2 = 6, 9\n", + "if(num1 < num2):\n", + " print(\"num1 is less than num2\")" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-10T20:03:36.548892Z", + "start_time": "2021-06-10T20:03:36.529417Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello\n" + ] + } + ], + "source": [ + "x = 12\n", + "if x > 10:\n", + " print(\"Hello\")" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-10T20:03:37.032393Z", + "start_time": "2021-06-10T20:03:37.017791Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hooray!\n" + ] + } + ], + "source": [ + "if 5 != 3 * 6:\n", + " print (\"Hooray!\")" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-10T20:03:38.014494Z", + "start_time": "2021-06-10T20:03:37.995993Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Horray!\n" + ] + } + ], + "source": [ + "if 5 == 15/3:\n", + " print (\"Horray!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Shortcut for `if` statement (Short-hand `if` or one-line `if`)\n", + "\n", + "If you have only one statement to execute, then you can put it on the same line as the `if` statement. Let's try doing this for the above example." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-10T20:03:38.795011Z", + "start_time": "2021-06-10T20:03:38.778459Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "num1 is less than num2\n" + ] + } + ], + "source": [ + "num1, num2 = 5, 6\n", + "if(num1 < num2): print(\"num1 is less than num2\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### The Difference....\n", + "\n", + "Now, try to execute the below-given code and observe the difference." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-10T20:03:44.293701Z", + "start_time": "2021-06-10T20:03:44.275199Z" + } + }, + "outputs": [], + "source": [ + "#program to check if num1 is less than num 2\n", + "num1, num2 = 6, 5\n", + "if (num1 < num2):\n", + " print(\"num1 is less than num2\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "**Did your Python IDE print anything?** No, it will not.\n", + "\n", + "In the above-given code, the value 6 is greater than 5, this means the condition is False. We have instructed the interpreter to print only when the condition is True and hence it in this case, nothing gets printed. However, **you can also instruct the interpreter what to do when the condition is False and this can be done using else statement**." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-10T20:03:48.495255Z", + "start_time": "2021-06-10T20:03:48.478701Z" + } + }, + "outputs": [], + "source": [ + "if 5 == 18/3:\n", + " print (\"Hooray!\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "hide_input": false, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.8" + }, + "toc": { + "base_numbering": 1, + "nav_menu": {}, + "number_sections": true, + "sideBar": true, + "skip_h1_title": false, + "title_cell": "Table of Contents", + "title_sidebar": "Contents", + "toc_cell": false, + "toc_position": {}, + "toc_section_display": true, + "toc_window_display": false + }, + "varInspector": { + "cols": { + "lenName": 16, + "lenType": 16, + "lenVar": 40 + }, + "kernels_config": { + "python": { + "delete_cmd_postfix": "", + "delete_cmd_prefix": "del ", + "library": "var_list.py", + "varRefreshCmd": "print(var_dic_list())" + }, + "r": { + "delete_cmd_postfix": ") ", + "delete_cmd_prefix": "rm(", + "library": "var_list.r", + "varRefreshCmd": "cat(var_dic_list()) " + } + }, + "types_to_exclude": [ + "module", + "function", + "builtin_function_or_method", + "instance", + "_Feature" + ], + "window_display": false + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/002_Python_if_else_statement.ipynb b/002_Python_if_else_statement.ipynb new file mode 100644 index 0000000..7d64e78 --- /dev/null +++ b/002_Python_if_else_statement.ipynb @@ -0,0 +1,591 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "All the IPython Notebooks in **Python Flow Control Statements** lecture series by Dr. Milaan Parmar are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)**\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Python `if-else` statement\n", + "\n", + "It is likely that we will want the program to do something even when an **[if statement](https://github.com/milaan9/03_Python_Flow_Control/blob/main/001_Python_if_statement.ipynb)** **evaluates to false**. In our grade example of previous tutorial, we will want output whether the grade is passing or failing." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T07:16:58.412652Z", + "start_time": "2021-10-04T07:16:58.381404Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Case 2\n" + ] + } + ], + "source": [ + "x = 1\n", + "\n", + "if x > 3:\n", + " print (\"Case 1\")\n", + "if x <= 3:\n", + " print (\"Case 2\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The **`if-else`** statement checks the condition and executes the **`if`** block of code when the condition is **`True`**, and **`if`** the condition is **`False`**, it will execute the **`else`** block of code." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Syntax :\n", + "\n", + "```python\n", + "if condition:\n", + " statement 1\n", + "else:\n", + " statement 2\n", + "```\n", + "\n", + "1. The **`if..else`** statement evaluates **`condition`** and will execute the body of **`if`** only when the test condition is **`True`**.\n", + "\n", + "2. If the condition is **`False`**, the body of **`else`** is executed. Indentation is used to separate the blocks.\n", + "\n", + "
\n", + "\n", + "
\n", + "\n", + "To do this, we will add an else statement to the grade condition above that is constructed like this:\n", + "\n", + "```python\n", + ">>> grade = 60 \n", + ">>> if grade >= 65:\n", + ">>> print(\"Passing grade\")\n", + ">>> else:\n", + ">>> print(\"Failing grade\")\n", + "\n", + "Failing grade\n", + "```\n", + "\n", + "Since the grade variable above has the value of 60, the if statement evaluates as false, so the program will not print out Passing grade. The else statement that follows tells the program to do **something anyway**.\n", + "\n", + "If we then rewrite the program to give the grade a value of 65 or higher, we will instead receive the output Passing grade." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T07:16:58.535698Z", + "start_time": "2021-10-04T07:16:58.415580Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Failing grade\n" + ] + } + ], + "source": [ + "# Example 1:\n", + "\n", + "grade = 60\n", + " \n", + "if grade >= 65:\n", + " print(\"Passing grade\")\n", + "else:\n", + " print(\"Failing grade\")" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T07:16:58.644099Z", + "start_time": "2021-10-04T07:16:58.540581Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Positive or Zero\n" + ] + } + ], + "source": [ + "# Example 2: Program checks if the number is positive or negative and displays an appropriate message\n", + "\n", + "num = 3\n", + "\n", + "# Try these two variations as well. \n", + "# num = -5\n", + "# num = 0\n", + "\n", + "if num >= 0:\n", + " print(\"Positive or Zero\")\n", + "else:\n", + " print(\"Negative number\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation**\n", + "\n", + "In the above example, when **`num`** is equal to 3, the test expression is true and the body of **`if`** is executed and the **`body`** of else is skipped.\n", + "\n", + "If **`num`** is equal to -5, the test expression is false and the body of **`else`** is executed and the body of **`if`** is skipped.\n", + "\n", + "If **`num`** is equal to 0, the test expression is true and body of **`if`** is executed and **`body`** of else is skipped." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T07:16:58.659725Z", + "start_time": "2021-10-04T07:16:58.648003Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "num2 is less than num1\n" + ] + } + ], + "source": [ + "# Example 3: program to check if a num1 is less than num2\n", + "\n", + "num1, num2 = 6, 5\n", + "if (num1 < num2):\n", + " print(\"num1 is less than num2\")\n", + "else:\n", + " print(\"num2 is less than num1\")" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T07:16:58.798390Z", + "start_time": "2021-10-04T07:16:58.662651Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Correct password\n", + "Incorrect Password\n" + ] + } + ], + "source": [ + "# Example 4:\n", + "\n", + "def password_check(password):\n", + " if password == \"Python@99>\":\n", + " print(\"Correct password\")\n", + " else:\n", + " print(\"Incorrect Password\")\n", + "\n", + "password_check(\"Python@99>\")\n", + "# Output Correct password\n", + "\n", + "password_check(\"Python99\")\n", + "# Output Incorrect Password" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Shortcut of `if else` (Short Hand if ... else or One line `if else`)\n", + "\n", + "If you have **only one statement each for if and else, then they can be put in the same line**. This can be done as shown below" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T07:16:58.920462Z", + "start_time": "2021-10-04T07:16:58.806208Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Feed the bear now!\n" + ] + } + ], + "source": [ + "hungry = True\n", + "x = 'Feed the bear now!' if hungry else 'Do not feed the bear.'\n", + "print(x)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T07:16:59.059135Z", + "start_time": "2021-10-04T07:16:58.931207Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A is positive\n" + ] + } + ], + "source": [ + "a = 3\n", + "print('A is positive') if a > 0 else print('A is negative') # first condition met, 'A is positive' will be printed" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T07:16:59.183158Z", + "start_time": "2021-10-04T07:16:59.070854Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "num2 is less than num1\n" + ] + } + ], + "source": [ + "num1, num2 = 6, 5\n", + "print(\"num1 is less than num2\") if (num1 < num2) else print(\"num2 is less than num1\")" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T07:16:59.325248Z", + "start_time": "2021-10-04T07:16:59.189017Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "positive\n" + ] + } + ], + "source": [ + "number = 96\n", + "if number > 0: print(\"positive\") \n", + "else: print(\"negative\")" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T07:16:59.429251Z", + "start_time": "2021-10-04T07:16:59.328177Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "world\n" + ] + } + ], + "source": [ + "x = 12\n", + "if 10 < x < 11:\n", + " print(\"hello\")\n", + "else:\n", + " print(\"world\")" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T07:16:59.538139Z", + "start_time": "2021-10-04T07:16:59.437065Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Case 2\n" + ] + } + ], + "source": [ + "'''\n", + "x = 1\n", + "\n", + "if x > 3:\n", + " print (\"Case 1\")\n", + "if x <= 3:\n", + " print (\"Case 2\")\n", + "'''\n", + "\n", + "x = 1\n", + "\n", + "if x > 3:\n", + " print (\"Case 1\")\n", + "else:\n", + " print (\"Case 2\")" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T07:16:59.660693Z", + "start_time": "2021-10-04T07:16:59.542045Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Incorrect\n" + ] + } + ], + "source": [ + "x = 2\n", + "\n", + "if x > 4:\n", + " print (\"Correct\")\n", + "else:\n", + " print(\"Incorrect\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### The difference....\n", + "\n", + "Now, let us try to execute the same above discussed code with different input values." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T07:16:59.814505Z", + "start_time": "2021-10-04T07:16:59.664116Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "num2 is less than num1\n" + ] + }, + { + "data": { + "text/plain": [ + "'\\nOutput: num2 is lesser than num1\\n'" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#program to check if num1 is less than num2\n", + "\n", + "num1, num2 = 5, 5\n", + "if (num1 < num2):\n", + " print(\"num1 is less than num2\")\n", + "else:\n", + " print(\"num2 is less than num1\")\n", + "\n", + "'''\n", + "Output: num2 is lesser than num1\n", + "'''" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "* **Why was the output wrong?**\n", + "\n", + "Since both the input values are equal, the condition **`num1List\n", + "\n", + "1. Get user input using **`input(“Enter your age: ”)`**. If user is 18 or older, give feedback: **`You are old enough to drive`**. If below 18 give feedback to **`wait for the missing amount of years`**. \n", + "\n", + "Output:\n", + "\n", + "```py\n", + " Enter your age: 30\n", + " You are old enough to learn to drive.\n", + " Output:\n", + " Enter your age: 15\n", + " You need 3 more years to learn to drive.\n", + "```\n", + "\n", + "2. Compare the values of my_age and your_age using **`if-else`**. Who is older (me or you)? Use **`input(“Enter your age: ”)`** to get the age as input. You can use a nested condition to print **`'year'`** for 1 year difference in age, **`'years'`** for bigger differences, and a custom text if **`my_age = your_age`**. \n", + "\n", + "Output:\n", + "\n", + "```py\n", + " Enter your age: 30\n", + " You are 5 years older than me.\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "hide_input": false, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.8" + }, + "toc": { + "base_numbering": 1, + "nav_menu": {}, + "number_sections": true, + "sideBar": true, + "skip_h1_title": false, + "title_cell": "Table of Contents", + "title_sidebar": "Contents", + "toc_cell": false, + "toc_position": {}, + "toc_section_display": true, + "toc_window_display": false + }, + "varInspector": { + "cols": { + "lenName": 16, + "lenType": 16, + "lenVar": 40 + }, + "kernels_config": { + "python": { + "delete_cmd_postfix": "", + "delete_cmd_prefix": "del ", + "library": "var_list.py", + "varRefreshCmd": "print(var_dic_list())" + }, + "r": { + "delete_cmd_postfix": ") ", + "delete_cmd_prefix": "rm(", + "library": "var_list.r", + "varRefreshCmd": "cat(var_dic_list()) " + } + }, + "types_to_exclude": [ + "module", + "function", + "builtin_function_or_method", + "instance", + "_Feature" + ], + "window_display": false + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/003_Python_if_elif_else_statement .ipynb b/003_Python_if_elif_else_statement .ipynb new file mode 100644 index 0000000..28f651b --- /dev/null +++ b/003_Python_if_elif_else_statement .ipynb @@ -0,0 +1,486 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "All the IPython Notebooks in **Python Flow Control Statements** lecture series by Dr. Milaan Parmar are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)**\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Python `if-elif-else` statement\n", + "\n", + "So far, we have presented a Boolean option for conditional statements, with each **[if statement](https://github.com/milaan9/03_Python_Flow_Control/blob/main/001_Python_if_statement.ipynb)** evaluating to either **`True`** or **`False`**. In Python, the **`if-elif-else`** condition statement has an **`elif`** keyword used to chain multiple conditions one after another." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Syntax:\n", + "\n", + "```python\n", + "if condition-1: \n", + " statement 1 \n", + "elif condition-2:\n", + " stetement 2 \n", + "elif condition-3:\n", + " stetement 3 \n", + " ... \n", + "else: \n", + " statement \n", + "```\n", + "\n", + "1. The **`elif`** is short for else if. It allows us to check for multiple expressions.\n", + "\n", + "2. If the condition for **`if`** is **`False`**, it checks the condition of the next **`elif`** block and so on.\n", + "\n", + "3. If all the conditions are **`False`**, the body of **`else`** is executed.\n", + "\n", + "4. Only one block among the several **`if-elif-else`** blocks is executed according to the condition.\n", + "\n", + "5. The **`if`** block can have only one **`else`** block. But it can have multiple **`elif`** blocks.\n", + "\n", + "
\n", + "\n", + "
" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T08:50:54.861499Z", + "start_time": "2021-10-04T08:50:54.848803Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Zero\n" + ] + } + ], + "source": [ + "# Example 1:\n", + "\n", + "'''In this program, we check if the number is positive or negative or zero and \n", + "display an appropriate message'''\n", + "\n", + "num = 0\n", + "\n", + "# Try these two variations as well:\n", + "# num = 0\n", + "# num = -4.5\n", + "\n", + "if num > 0:\n", + " print(\"Positive number\")\n", + "elif num == 0:\n", + " print(\"Zero\")\n", + "else:\n", + " print(\"Negative number\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "When variable **`num`** is positive, **`Positive number`** is printed.\n", + "\n", + "If **`num`** is equal to 0, **`Zero`** is printed.\n", + "\n", + "If **`num`** is negative, **`Negative number`** is printed. " + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T08:50:55.015301Z", + "start_time": "2021-10-04T08:50:54.876146Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "num1 is equal to num2\n" + ] + } + ], + "source": [ + "# Example 2:\n", + "\n", + "num1, num2 = 5, 5\n", + "if(num1 > num2):\n", + " print(\"num1 is greater than num2\")\n", + "elif(num1 == num2):\n", + " print(\"num1 is equal to num2\")\n", + "else:\n", + " print(\"num1 is less than num2\")" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T08:50:55.153487Z", + "start_time": "2021-10-04T08:50:55.019212Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "x y:\n", + " print(\"x>y\")\n", + "elif x < y:\n", + " print(\"x= 90:\n", + " print(\"A grade\")\n", + "elif grade >=80:\n", + " print(\"B grade\")\n", + "elif grade >=70:\n", + " print(\"C grade\")\n", + "elif grade >= 65:\n", + " print(\"D grade\")\n", + "else:\n", + " print(\"Failing grade\")" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T08:50:55.446456Z", + "start_time": "2021-10-04T08:50:55.281905Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Admin\n", + "Editor\n", + "Guest\n", + "Wrong entry\n" + ] + } + ], + "source": [ + "# Example 5:\n", + "\n", + "def user_check(choice):\n", + " if choice == 1:\n", + " print(\"Admin\")\n", + " elif choice == 2:\n", + " print(\"Editor\")\n", + " elif choice == 3:\n", + " print(\"Guest\")\n", + " else:\n", + " print(\"Wrong entry\")\n", + "\n", + "user_check(1) # Admin\n", + "user_check(2) # Editor\n", + "user_check(3) # Guest\n", + "user_check(4) # Wrong entry" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## if-elif-else statements with logical operators\n", + "\n", + "We can avoid writing nested condition by using logical operator **`and`**." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### if-elif-else statements `and` Logical Operator\n", + "\n", + "**Syntax:**\n", + "\n", + "```py\n", + "if condition and condition:\n", + " code\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T08:50:55.556809Z", + "start_time": "2021-10-04T08:50:55.453294Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A is zero\n" + ] + } + ], + "source": [ + "a = 0\n", + "if a > 0 and a % 2 == 0:\n", + " print('A is an even and positive integer')\n", + "elif a > 0 and a % 2 != 0:\n", + " print('A is a positive integer')\n", + "elif a == 0:\n", + " print('A is zero')\n", + "else:\n", + " print('A is negative')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### if-elif-else statements `or` Logical Operator\n", + "\n", + "**Syntax:**\n", + "\n", + "```py\n", + "if condition or condition:\n", + " code\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T08:50:55.708176Z", + "start_time": "2021-10-04T08:50:55.559738Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Access denied!\n" + ] + } + ], + "source": [ + "user = 'Arthur'\n", + "access_level = 3\n", + "if user == 'admin' or access_level >= 4:\n", + " print('Access granted!')\n", + "else:\n", + " print('Access denied!')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 💻 Exercises ➞ List\n", + "\n", + "### Exercises ➞ Level 1\n", + "\n", + "1. Get two numbers from the user using input prompt. If **`num_1`** is greater than **`num_2`** return **`num_1`** is greater than **`num_2`**, if **`num_1`** is less **`num_2`** return **`num_1`** is smaller than **`num_2`**, else **`num_1`** is equal to **`num_2`**. Output:\n", + "\n", + "```sh\n", + "Enter number one: 9\n", + "Enter number two: 6\n", + "9 is greater than 6\n", + "```\n", + "\n", + "### Exercises ➞ Level 2\n", + "\n", + "1. Write a code which gives grade to students according to theirs scores:\n", + " \n", + "```py\n", + " 80-100, A\n", + " 70-89, B\n", + " 60-69, C\n", + " 50-59, D\n", + " 0-49, F\n", + "```\n", + "\n", + "2. Check if the season is Autumn, Winter, Spring or Summer. \n", + " - If the user input is:\n", + " - September, October or November, the season is Autumn.\n", + " - December, January or February, the season is Winter.\n", + " - March, April or May, the season is Spring\n", + " - June, July or August, the season is Summer\n", + "\n", + "\n", + "3. The following list contains some fruits:\n", + " - If a fruit doesn't exist in the list add the fruit to the list and print the modified list. If the fruit exists print **`('That fruit already exist in the list')`** \n", + " \n", + "```py\n", + " fruits = ['banana', 'orange', 'mango', 'pear']\n", + "``` \n", + "\n", + "\n", + "### Exercises ➞ Level 3\n", + "\n", + " 1. Here we have a person dictionary. Feel free to modify it!\n", + " \n", + "```py\n", + " person={\n", + " 'first_name': 'Milaan',\n", + " 'last_name': 'Parmar',\n", + " 'age': 96,\n", + " 'country': 'Finland',\n", + " 'is_marred': True,\n", + " 'skills': ['Python', 'Matlab', 'R', 'C', 'C++'],\n", + " 'address': {\n", + " 'street': 'Space street',\n", + " 'zipcode': '02210'\n", + " }\n", + " }\n", + "```\n", + "\n", + " * Check if the person dictionary has skills key, if so print out the middle skill in the skills list.\n", + " * Check if the person dictionary has skills key, if so check if the person has 'Python' skill and print out the result.\n", + " * If a person skills has only Python and Matlab, print('He knows machine learning'), if the person skills has Python, and R print('He knows statistics'), if the person skills has C, and C++, Print('He knows software development'), else print('unknown title') - for more accurate results more conditions can be nested!\n", + " * If the person is married and if he lives in Finland, print the information in the following format:\n", + "\n", + "```py\n", + " Milaan Parmar lives in Finland. He is married.\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "hide_input": false, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.8" + }, + "toc": { + "base_numbering": 1, + "nav_menu": {}, + "number_sections": true, + "sideBar": true, + "skip_h1_title": false, + "title_cell": "Table of Contents", + "title_sidebar": "Contents", + "toc_cell": false, + "toc_position": { + "height": "calc(100% - 180px)", + "left": "10px", + "top": "150px", + "width": "204.797px" + }, + "toc_section_display": true, + "toc_window_display": false + }, + "varInspector": { + "cols": { + "lenName": 16, + "lenType": 16, + "lenVar": 40 + }, + "kernels_config": { + "python": { + "delete_cmd_postfix": "", + "delete_cmd_prefix": "del ", + "library": "var_list.py", + "varRefreshCmd": "print(var_dic_list())" + }, + "r": { + "delete_cmd_postfix": ") ", + "delete_cmd_prefix": "rm(", + "library": "var_list.r", + "varRefreshCmd": "cat(var_dic_list()) " + } + }, + "types_to_exclude": [ + "module", + "function", + "builtin_function_or_method", + "instance", + "_Feature" + ], + "window_display": false + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/004_Python_Nested_if_statement.ipynb b/004_Python_Nested_if_statement.ipynb new file mode 100644 index 0000000..17c7d42 --- /dev/null +++ b/004_Python_Nested_if_statement.ipynb @@ -0,0 +1,304 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "All the IPython Notebooks in **Python Flow Control Statements** lecture series by Dr. Milaan Parmar are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)**\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Python Nested `if` statement\n", + "\n", + "We can have a nested-**[if-else](https://github.com/milaan9/03_Python_Flow_Control/blob/main/002_Python_if_else_statement.ipynb)** or nested-**[if-elif-else](https://github.com/milaan9/03_Python_Flow_Control/blob/main/003_Python_if_elif_else_statement%20.ipynb)** statement inside another **`if-else`** statement. This is called **nesting** in computer programming. The nested if statements is useful when we want to make a series of decisions.\n", + "\n", + "Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. They can get confusing, so they must be avoided unless necessary.\n", + "\n", + "We can use nested if statements for situations where we want to check for a **secondary condition** if the first condition executes as **`True`**." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Syntax:\n", + "\n", + "#### Example 1:\n", + "```python\n", + "if conditon_outer:\n", + " if condition_inner:\n", + " statement of nested if\n", + " else:\n", + " statement of nested if else:\n", + " statement ot outer if\n", + "else:\n", + " Outer else \n", + "statement outside if block\n", + "```\n", + "\n", + "#### Example 2:\n", + "```python\n", + "if expression1:\n", + " statement(s)\n", + " if expression2:\n", + " statement(s)\n", + " elif expression3:\n", + " statement(s)\n", + " elif expression4:\n", + " statement(s)\n", + " else:\n", + " statement(s)\n", + "else:\n", + " statement(s)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-10T21:32:46.158585Z", + "start_time": "2021-06-10T21:32:46.150794Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "All Conditions are false\n" + ] + } + ], + "source": [ + "# Example 1:\n", + "\n", + "a=10\n", + "if a>=20: # Condition FALSE\n", + " print (\"Condition is True\")\n", + "else: # Code will go to ELSE body\n", + " if a>=15: # Condition FALSE\n", + " print (\"Checking second value\")\n", + " else: # Code will go to ELSE body\n", + " print (\"All Conditions are false\")" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-10T21:32:46.684934Z", + "start_time": "2021-06-10T21:32:46.672274Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "x y:\n", + " print( \"x>y\")\n", + "elif x < y:\n", + " print( \"x 0): \n", + " print(\"num1 is a positive number\")\n", + " else: \n", + " print(\"num1 is a negative number\")\n", + "else: # For zero condition is TRUE\n", + " print(\"num1 is neither positive nor negative\")" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-10T21:33:30.124628Z", + "start_time": "2021-06-10T21:33:16.450727Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Enter a number: 9\n", + "Positive number\n" + ] + } + ], + "source": [ + "# Example 4:\n", + "\n", + "'''In this program, we input a number check if the number is \n", + "positive or negative or zero and display an appropriate message. \n", + "This time we use nested if statement'''\n", + "\n", + "num = float(input(\"Enter a number: \"))\n", + "if num >= 0:\n", + " if num == 0:\n", + " print(\"Zero\")\n", + " else:\n", + " print(\"Positive number\")\n", + "else:\n", + " print(\"Negative number\")" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-10T21:33:37.996992Z", + "start_time": "2021-06-10T21:33:37.975571Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "96 is greater than 66\n", + "96 and 96 are equal\n" + ] + } + ], + "source": [ + "# Example 5:\n", + "\n", + "def number_arithmetic(num1, num2):\n", + " if num1 >= num2:\n", + " if num1 == num2:\n", + " print(f'{num1} and {num2} are equal')\n", + " else:\n", + " print(f'{num1} is greater than {num2}')\n", + " else:\n", + " print(f'{num1} is smaller than {num2}')\n", + "\n", + "number_arithmetic(96, 66)\n", + "# Output 96 is greater than 66\n", + "number_arithmetic(96, 96)\n", + "# Output 56 and 56 are equal" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "hide_input": false, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.8" + }, + "toc": { + "base_numbering": 1, + "nav_menu": {}, + "number_sections": true, + "sideBar": true, + "skip_h1_title": false, + "title_cell": "Table of Contents", + "title_sidebar": "Contents", + "toc_cell": false, + "toc_position": {}, + "toc_section_display": true, + "toc_window_display": false + }, + "varInspector": { + "cols": { + "lenName": 16, + "lenType": 16, + "lenVar": 40 + }, + "kernels_config": { + "python": { + "delete_cmd_postfix": "", + "delete_cmd_prefix": "del ", + "library": "var_list.py", + "varRefreshCmd": "print(var_dic_list())" + }, + "r": { + "delete_cmd_postfix": ") ", + "delete_cmd_prefix": "rm(", + "library": "var_list.r", + "varRefreshCmd": "cat(var_dic_list()) " + } + }, + "types_to_exclude": [ + "module", + "function", + "builtin_function_or_method", + "instance", + "_Feature" + ], + "window_display": false + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/005_Python_for_Loop.ipynb b/005_Python_for_Loop.ipynb new file mode 100644 index 0000000..0f0bb14 --- /dev/null +++ b/005_Python_for_Loop.ipynb @@ -0,0 +1,3385 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "All the IPython Notebooks in **Python Flow Control Statements** lecture series by Dr. Milaan Parmar are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)**\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Loops in Python\n", + "\n", + "Loops in Python programming function similar to loops in C, C++, Java or other languages. Python loops are used to repeatedly execute a block of statements until a given condition returns to be **`False`**. In Python, we have **two types of looping statements**, namely:\n", + "
\n", + "\n", + "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Python `for` Loop\n", + "\n", + "In this class, you'll learn to iterate over a sequence of elements using the different variations of **`for`** loop. We use a **`for`** loop when we want to repeat a code block for a **fixed number of times**." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## What is `for` loop in Python? \n", + "\n", + "The for loop in Python is used to iterate over a sequence (**[string](https://github.com/milaan9/02_Python_Datatypes/blob/main/002_Python_String.ipynb)**, **[list](https://github.com/milaan9/02_Python_Datatypes/blob/main/003_Python_List.ipynb)**, **[dictionary](https://github.com/milaan9/02_Python_Datatypes/blob/main/005_Python_Dictionary.ipynb)**, **[set](https://github.com/milaan9/02_Python_Datatypes/blob/main/006_Python_Sets.ipynb)**, or **[tuple](https://github.com/milaan9/02_Python_Datatypes/blob/main/004_Python_Tuple.ipynb)**). Iterating over a sequence is called traversal." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Why use `for` loop?\n", + "\n", + "Let’s see the use **`for`** loop in Python.\n", + "\n", + "* **Definite Iteration:** When we know how many times we wanted to run a loop, then we use count-controlled loops such as **`for`** loops. It is also known as definite iteration. For example, Calculate the percentage of 50 students. here we know we need to iterate a loop 50 times (1 iteration for each student).\n", + "* **Reduces the code’s complexity:** Loop repeats a specific block of code a fixed number of times. It reduces the repetition of lines of code, thus reducing the complexity of the code. Using **`for`** loops and while loops we can automate and repeat tasks in an efficient manner.\n", + "* **Loop through sequences:** used for iterating over lists, strings, tuples, dictionaries, etc., and perform various operations on it, based on the conditions specified by the user." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Syntax :\n", + "\n", + "```python \n", + "for element in sequence:\n", + " body of for loop \n", + "```\n", + "\n", + "1. First, **`element`** is the variable that takes the value of the item inside the sequence on each iteration.\n", + "\n", + "2. Second, all the **`statements`** in the body of the for loop are executed with the same value. The body of for loop is separated from the rest of the code using indentation.\n", + "\n", + "3. Finally, loop continues until we reach the last item in the **`sequence`**. The body of for loop is separated from the rest of the code using indentation.\n", + "\n", + "
\n", + "\n", + "
" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:49.251313Z", + "start_time": "2021-10-04T12:09:49.240575Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "one\n", + "two\n", + "three\n", + "four\n", + "five\n" + ] + } + ], + "source": [ + "# Example 1: For loop \n", + "\n", + "words = ['one', 'two', 'three', 'four', 'five']\n", + "\n", + "for i in words:\n", + " print(i)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:49.282564Z", + "start_time": "2021-10-04T12:09:49.259620Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "30.0\n" + ] + } + ], + "source": [ + "# Example 2: Calculate the average of list of numbers\n", + "\n", + "numbers = [10, 20, 30, 40, 50]\n", + "\n", + "# definite iteration\n", + "# run loop 5 times because list contains 5 items\n", + "sum = 0\n", + "for i in numbers:\n", + " sum = sum + i\n", + "list_size = len(numbers)\n", + "average = sum / list_size\n", + "print(average)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## `for` loop with `range()` function\n", + "\n", + "The **[range()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/053_Python_range%28%29.ipynb)** function returns a sequence of numbers starting from 0 (by default) if the initial limit is not specified and it increments by 1 (by default) until a final limit is reached.\n", + "\n", + "The **`range()`** function is used with a loop to specify the range (how many times) the code block will be executed. Let us see with an example.\n", + "\n", + "We can generate a sequence of numbers using **`range()`** function. **`range(5)`** will generate numbers from 0 to 4 (5 numbers). \n", + "\n", + "
\n", + "\n", + "
\n", + "\n", + "The **`range()`** function is \"lazy\" in a sense because it doesn't generate every number that it \"contains\" when we create it. However, it is not an iterator since it supports **[len()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/040_Python_len%28%29.ipynb)** and **`__getitem__`** operations.\n", + "\n", + "This **`range()`** function does not store all the values in memory; it would be inefficient. So it remembers the start, stop, step size and generates the next number on the go.\n", + "\n", + "We can also define the start, stop and step size as **`range(start, stop,step_size)`**. **`step_size`** defaults to 1 if not provided." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:49.435886Z", + "start_time": "2021-10-04T12:09:49.292334Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[]\n", + "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n", + "[1, 2, 3, 4, 5, 6, 7, 8, 9]\n" + ] + } + ], + "source": [ + "# Example 1: How range works in Python?\n", + "\n", + "# empty range\n", + "print(list(range(0)))\n", + "\n", + "# using range(stop)\n", + "print(list(range(10)))\n", + "\n", + "# using range(start, stop)\n", + "print(list(range(1, 10)))" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:49.633639Z", + "start_time": "2021-10-04T12:09:49.439794Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "8\n", + "9\n" + ] + } + ], + "source": [ + "# Example 2:\n", + "\n", + "for num in range(10):\n", + " print(num)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:49.908542Z", + "start_time": "2021-10-04T12:09:49.640473Z" + }, + "scrolled": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "8\n", + "9\n", + "10\n" + ] + } + ], + "source": [ + "# Example 3:\n", + "\n", + "for i in range(1, 11):\n", + " print(i)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:50.137547Z", + "start_time": "2021-10-04T12:09:49.913425Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2\n", + "4\n", + "6\n", + "8\n", + "10\n" + ] + } + ], + "source": [ + "# Example 4:\n", + "\n", + "for i in range (2, 12, 2): # beginning 2 with distance of 2 and stop before 12\n", + " print (i)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:50.259614Z", + "start_time": "2021-10-04T12:09:50.141453Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2\n", + "4\n", + "6\n", + "8\n", + "10\n" + ] + } + ], + "source": [ + "# Example 5:\n", + "\n", + "num=2\n", + "\n", + "for a in range (1,6): # range (1,6) means numbers from 1 to 5, i.e., (1,2,3,4,5)\n", + " print (num * a)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:50.396821Z", + "start_time": "2021-10-04T12:09:50.262548Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "3\n", + "6\n", + "10\n", + "15\n", + "21\n", + "28\n", + "36\n", + "45\n", + "55\n" + ] + }, + { + "data": { + "text/plain": [ + "'\\n0+1 = 1\\n1+2 = 3\\n3+3 = 6\\n6+4 = 10\\n10+5 =15\\n21\\n28\\n36\\n45\\n45+10 = 55\\n'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Example 6: Find Sum of 10 Numbers\n", + "\n", + "sum=0\n", + "for n in range(1,11): # range (1,11) means numbers from 1 to 5, i.e., (1,2,3,4,5,6,7,8,9,10)\n", + " sum+=n \n", + " print (sum)\n", + " \n", + "'''\n", + "0+1 = 1\n", + "1+2 = 3\n", + "3+3 = 6\n", + "6+4 = 10\n", + "10+5 =15\n", + "21\n", + "28\n", + "36\n", + "45\n", + "45+10 = 55\n", + "'''" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:50.534518Z", + "start_time": "2021-10-04T12:09:50.399756Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Case 1:\n", + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "Case 2:\n", + "5\n", + "6\n", + "7\n", + "8\n", + "9\n", + "Case 3:\n", + "5\n", + "7\n", + "9\n" + ] + } + ], + "source": [ + "# Example 7: printing a series of numbers using for and range\n", + "\n", + "print(\"Case 1:\")\n", + "for i in range(5): # Print numbers from 0 to 4\n", + " print (i)\n", + "\n", + "print(\"Case 2:\") \n", + "for i in range(5, 10): # Print numbers from 5 to 9\n", + " print (i)\n", + "\n", + "print(\"Case 3:\")\n", + "for i in range(5, 10, 2): # Print numbers from 5 with distace 2 and stop before 10\n", + " print (i)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## `for` loop with `if-else`\n", + "\n", + "A **`for`** loop can have an optional **[if-else](https://github.com/milaan9/03_Python_Flow_Control/blob/main/002_Python_if_else_statement.ipynb)** block. The **`if-else`** checks the condition and if the condition is **`True`** it executes the block of code present inside the **`if`** block and if the condition is **`False`**, it will execute the block of code present inside the **`else`** block." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:50.657566Z", + "start_time": "2021-10-04T12:09:50.539403Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Odd Number: 1\n", + "Even Number: 2\n", + "Odd Number: 3\n", + "Even Number: 4\n", + "Odd Number: 5\n", + "Even Number: 6\n", + "Odd Number: 7\n", + "Even Number: 8\n", + "Odd Number: 9\n", + "Even Number: 10\n" + ] + } + ], + "source": [ + "# Example 1: Print all even and odd numbers\n", + "\n", + "for i in range(1, 11):\n", + " if i % 2 == 0:\n", + " print('Even Number:', i)\n", + " else:\n", + " print('Odd Number:', i)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## `for` loop with `else`\n", + "\n", + "A **`for`** loop can have an optional **`else`** block as well. The **`else`** part is executed if the items in the sequence used in for loop exhausts.\n", + "\n", + "**`else`** block will be skipped/ignored when:\n", + "\n", + "* **`for`** loop terminate abruptly\n", + "* the **[break statement](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)** is used to break the **`for`** loop." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:50.793310Z", + "start_time": "2021-10-04T12:09:50.666842Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "5\n", + "No items left.\n" + ] + } + ], + "source": [ + "# Example 1:\n", + "\n", + "digits = [0, 1, 5]\n", + "\n", + "for i in digits:\n", + " print(i)\n", + "else:\n", + " print(\"No items left.\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "Here, the for loop prints items of the list until the loop exhausts. When the for loop exhausts, it executes the block of code in the **`else`** and prints **`No items left`**." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:50.991550Z", + "start_time": "2021-10-04T12:09:50.796727Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "8\n", + "9\n", + "10\n", + "The loop stops at 10\n" + ] + } + ], + "source": [ + "# Example 2:\n", + "\n", + "for number in range(11):\n", + " print(number) # prints 0 to 10, not including 11\n", + "else:\n", + " print('The loop stops at', number)" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:51.159520Z", + "start_time": "2021-10-04T12:09:50.996435Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "Done\n" + ] + } + ], + "source": [ + "# Example 3: Else block in for loop\n", + "\n", + "for i in range(1, 6):\n", + " print(i)\n", + "else:\n", + " print(\"Done\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This **`for-else`** statement can be used with the **`break`** keyword to run the **`else`** block only when the **`break`** keyword was not executed. Let's take an example:" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:51.312349Z", + "start_time": "2021-10-04T12:09:51.162449Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "No entry with that name found.\n" + ] + } + ], + "source": [ + "# Example 4:\n", + "\n", + "student_name = 'Arthur'\n", + "\n", + "marks = {'Alan': 99, 'Bill': 55, 'Cory': 77}\n", + "\n", + "for student in marks:\n", + " if student == student_name:\n", + " print(marks[student])\n", + " break\n", + "else:\n", + " print('No entry with that name found.')" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:51.403663Z", + "start_time": "2021-10-04T12:09:51.315770Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n" + ] + } + ], + "source": [ + "# Example 5:\n", + "\n", + "count = 0\n", + "for i in range(1, 6):\n", + " count = count + 1\n", + " if count > 2:\n", + " break\n", + " else:\n", + " print(i)\n", + "else:\n", + " print(\"Done\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using Control Statement in `for` loops in Python\n", + "\n", + "**[Control statements](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)** in Python like **`break`**, **`continue`**, etc can be used to control the execution flow of **`for`** loop in Python. Let us now understand how this can be done.\n", + "\n", + "It is used when you want to exit a loop or skip a part of the loop based on the given condition. It also knows as **transfer statements**." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### a) `break` in `for` loop\n", + "\n", + "Using the **`break`** statement, we can exit from the **`for`** loop before it has looped through all the elements in the sequence as shown below. As soon as it breaks out of the **`for`** loop, the control shifts to the immediate next line of code. For example," + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:51.556493Z", + "start_time": "2021-10-04T12:09:51.407569Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "2\n", + "3\n" + ] + } + ], + "source": [ + "# Example 1:\n", + "\n", + "numbers = (0,1,2,3,4,5)\n", + "for number in numbers:\n", + " print(number)\n", + " if number == 3:\n", + " break" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "In the above example, the loop stops when it reaches 3." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:51.709323Z", + "start_time": "2021-10-04T12:09:51.561377Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Pink\n" + ] + } + ], + "source": [ + "# Example 2:\n", + "\n", + "color = ['Green', 'Pink', 'Blue']\n", + "for i in color:\n", + " if(i == 'Pink'):\n", + " break\n", + "print (i)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "Here, in the second iteration, the **`if`** condition becomes **`True`**. Hence the loop beaks out of the for loop and the immediate next line of code i.e **`print (i)`** is executed and as a result, pink is outputted." + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:51.861668Z", + "start_time": "2021-10-04T12:09:51.712254Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "4\n", + "7\n", + "8\n", + "15\n" + ] + } + ], + "source": [ + "# Example 3:\n", + "\n", + "numbers = [1, 4, 7, 8, 15, 20, 35, 45, 55]\n", + "for i in numbers:\n", + " if i > 15:\n", + " # break the loop\n", + " break\n", + " else:\n", + " print(i)" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:52.014500Z", + "start_time": "2021-10-04T12:09:51.870458Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 0\n", + "2 0\n", + "2 1\n", + "3 0\n", + "3 1\n", + "3 2\n", + "4 0\n", + "4 1\n", + "4 2\n", + "4 3\n" + ] + } + ], + "source": [ + "# Example 4:\n", + "\n", + "for i in range(5):\n", + " for j in range(5):\n", + " if j == i:\n", + " break\n", + " print(i, j)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "We have two loops. The outer **`for`** loop iterates the first four numbers using the **[range()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/053_Python_range%28%29.ipynb)** function, and the inner **`for`** loop also iterates the first four numbers. If the outer number and a current number of the inner loop are the same, then break the inner (nested) loop." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### b) `continue` in `for` loop\n", + "\n", + "The **`continue`** statement is used to stop/skip the block of code in the loop for the current iteration only and continue with the next iteration. For example," + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:52.152683Z", + "start_time": "2021-10-04T12:09:52.017432Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Blue\n" + ] + } + ], + "source": [ + "# Example 1:\n", + "\n", + "color = ['Green', 'Pink', 'Blue']\n", + "for i in color:\n", + " if(i == 'Pink'):\n", + " continue\n", + "print (i)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "Here, in the second iteration, the condition becomes **`True`**. Hence the interpreter skips the **`print (i)`** statement and immediately executes the next iteration." + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:52.274755Z", + "start_time": "2021-10-04T12:09:52.155615Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "Next number should be 1\n", + "1\n", + "Next number should be 2\n", + "2\n", + "Next number should be 3\n", + "3\n", + "4\n", + "Next number should be 5\n", + "5\n", + "loop's end\n", + "outside the loop\n" + ] + } + ], + "source": [ + "# Example 2:\n", + "\n", + "numbers = (0,1,2,3,4,5)\n", + "for number in numbers:\n", + " print(number)\n", + " if number == 3:\n", + " continue\n", + " print('Next number should be ', number + 1) if number != 5 else print(\"loop's end\") # for short hand conditions need both if and else statements\n", + "print('outside the loop')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "In the example above, if the number equals 3, the step **after** the condition (but inside the loop) is skipped and the execution of the loop continues if there are any iterations left." + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:52.366553Z", + "start_time": "2021-10-04T12:09:52.277686Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "3 * 6 = 18\n", + "3 * 9 = 27\n", + "6 * 3 = 18\n", + "6 * 9 = 54\n", + "9 * 3 = 27\n", + "9 * 6 = 54\n" + ] + } + ], + "source": [ + "# Example 3:\n", + "\n", + "first = [3, 6, 9]\n", + "second = [3, 6, 9]\n", + "for i in first:\n", + " for j in second:\n", + " if i == j:\n", + " continue\n", + " print(i, '*', j, '= ', i * j)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "We have two loops. The outer for loop iterates the first list, and the inner loop also iterates the second list of numbers. If the outer number and the inner loop’s current number are the same, then move to the next iteration of an inner loop.\n", + "\n", + "As you can see in the output, no same numbers multiplying to each other." + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:52.488622Z", + "start_time": "2021-10-04T12:09:52.369485Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Total number of m is: 2\n" + ] + } + ], + "source": [ + "# Example 4:\n", + "\n", + "name = \"mariya mennen\"\n", + "count = 0\n", + "for char in name:\n", + " if char != 'm':\n", + " continue\n", + " else:\n", + " count = count + 1\n", + "\n", + "print('Total number of m is:', count)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### c) `pass` in `for` loop\n", + "\n", + "The **`pass`** statement is a null statement, i.e., nothing happens when the statement is executed. Primarily it is used in empty functions or classes. When the interpreter finds a pass statement in the program, it returns no operation." + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:52.625830Z", + "start_time": "2021-10-04T12:09:52.493506Z" + } + }, + "outputs": [], + "source": [ + "# Example 1:\n", + "\n", + "for number in range(6):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:52.747899Z", + "start_time": "2021-10-04T12:09:52.633640Z" + } + }, + "outputs": [], + "source": [ + "# Example 2:\n", + "\n", + "num = [1, 4, 5, 3, 7, 8]\n", + "for i in num:\n", + " # calculate multiplication in future if required\n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Reverse for loop\n", + "\n", + "Till now, we have learned about forward looping in **`for`** loop with various examples. Now we will learn about the backward iteration of a loop.\n", + "\n", + "Sometimes we require to do reverse looping, which is quite useful. For example, to reverse a list.\n", + "\n", + "There are three ways to iterating the **`for`** loop backward:\n", + "\n", + "* Reverse **`for`** loop using **[range()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/053_Python_range%28%29.ipynb)** function\n", + "* Reverse **`for`** loop using the **[reversed()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/055_Python_reversed%28%29.ipynb)** function" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Backward Iteration using the `reversed()` function\n", + "\n", + "We can use the built-in function **[reversed()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/055_Python_reversed%28%29.ipynb)** with **`for`** loop to change the order of elements, and this is the simplest way to perform a reverse looping." + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:52.871924Z", + "start_time": "2021-10-04T12:09:52.752784Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "40\n", + "30\n", + "20\n", + "10\n" + ] + } + ], + "source": [ + "# Example 1: Reversed numbers using `reversed()` function\n", + "\n", + "list1 = [10, 20, 30, 40]\n", + "for num in reversed(list1):\n", + " print(num)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Reverse for loop using `range()`\n", + "\n", + "We can use the built-in **[range()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/053_Python_range%28%29.ipynb)** function with the **`for`** loop to reverse the elements order. The **`range()`** generates the integer numbers between the given start integer to the stop integer." + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:53.008641Z", + "start_time": "2021-10-04T12:09:52.875832Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Reverse numbers using for loop\n", + "5\n", + "4\n", + "3\n", + "2\n", + "1\n", + "0\n" + ] + } + ], + "source": [ + "# Example 1:\n", + "\n", + "print(\"Reverse numbers using for loop\")\n", + "num = 5\n", + "# start = 5\n", + "# stop = -1\n", + "# step = -1\n", + "for num in (range(num, -1, -1)):\n", + " print(num)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There are many helper functions that make **`for`** loops even more powerful and easy to use. For example **[enumerate()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/018_Python_enumerate%28%29.ipynb)**, **[zip()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/066_Python_zip%28%29.ipynb)**, **[sorted()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/060_Python_sorted%28%29.ipynb)**, **[reversed()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/055_Python_reversed%28%29.ipynb)**" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:53.129735Z", + "start_time": "2021-10-04T12:09:53.015969Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "reversed: \tc;b;a;\n", + "enuemerated:\t0 = a; 1 = b; 2 = c; \n", + "zip'ed: \n", + "a : x\n", + "b : y\n", + "c : z\n" + ] + } + ], + "source": [ + "# Example 2:\n", + "\n", + "print(\"reversed: \\t\",end=\"\")\n", + "for ch in reversed(\"abc\"):\n", + " print(ch,end=\";\")\n", + "\n", + "print(\"\\nenuemerated:\\t\",end=\"\")\n", + "for i,ch in enumerate(\"abc\"):\n", + " print(i,\"=\",ch,end=\"; \")\n", + " \n", + "print(\"\\nzip'ed: \")\n", + "for a,x in zip(\"abc\",\"xyz\"):\n", + " print(a,\":\",x)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Nested `for` loops\n", + "\n", + "**Nested `for` loop** is a **`for`** loop inside another **`for`** a loop. \n", + "\n", + "A nested loop has one loop inside of another. In Python, you can use any loop inside any other loop. For instance, a **`for`** loop inside a **[while loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/006_Python_while_Loop.ipynb)**, a **`while`** inside **`for`** in and so on. It is mainly used with two-dimensional arrays.\n", + "\n", + "In nested loops, the inner loop finishes all of its iteration for each iteration of the outer loop. i.e., For each iteration of the outer loop inner loop restart and completes all its iterations, then the next iteration of the outer loop begins.\n", + "\n", + "**Syntax:**\n", + "\n", + "```python\n", + "# outer for loop\n", + "for element in sequence \n", + " # inner for loop\n", + " for element in sequence:\n", + " body of inner for loop\n", + " body of outer for loop\n", + "other statements\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### `for` loop inside `for` loop" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Example: Nested `for` loop \n", + "\n", + "In this example, we are using a **`for`** loop inside a **`for`** loop. In this example, we are printing a multiplication table of the first ten numbers.\n", + "\n", + "
\n", + "\n", + "
\n", + "\n", + "1. The outer **`for`** loop uses the **[range()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/053_Python_range%28%29.ipynb)** function to iterate over the first ten numbers\n", + "2. The inner **`for`** loop will execute ten times for each outer number\n", + "3. In the body of the inner loop, we will print the multiplication of the outer number and current number\n", + "4. The inner loop is nothing but a body of an outer loop." + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:53.208838Z", + "start_time": "2021-10-04T12:09:53.132667Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 2 3 4 5 6 7 8 9 10 \n", + "2 4 6 8 10 12 14 16 18 20 \n", + "3 6 9 12 15 18 21 24 27 30 \n", + "4 8 12 16 20 24 28 32 36 40 \n", + "5 10 15 20 25 30 35 40 45 50 \n", + "6 12 18 24 30 36 42 48 54 60 \n", + "7 14 21 28 35 42 49 56 63 70 \n", + "8 16 24 32 40 48 56 64 72 80 \n", + "9 18 27 36 45 54 63 72 81 90 \n", + "10 20 30 40 50 60 70 80 90 100 \n" + ] + } + ], + "source": [ + "# Example 1: printing a multiplication table of the first ten numbers\n", + "\n", + "# outer loop\n", + "for i in range(1, 11):\n", + " # nested loop \n", + " for j in range(1, 11): # to iterate from 1 to 10 \n", + " print(i * j, end=' ') # print multiplication\n", + " print()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "* In this program, the outer **`for`** loop is iterate numbers from 1 to 10. The **`range()`** return 10 numbers. So total number of iteration of the outer loop is 10.\n", + "* In the first iteration of the nested loop, the number is 1. In the next, it 2. and so on till 10.\n", + "* Next, the inner loop will also execute ten times because we rea printing multiplication table up to ten. For each iteration of the outer loop, the inner loop will execute ten times.\n", + "* In each iteration of an inner loop, we calculated the multiplication of two numbers." + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:53.312842Z", + "start_time": "2021-10-04T12:09:53.211769Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Python\n", + "Matlab\n", + "R\n", + "C\n", + "C++\n" + ] + } + ], + "source": [ + "# Example 1:\n", + "\n", + "person = {\n", + " 'first_name':'Milaan',\n", + " 'last_name':'Parmar',\n", + " 'age':96,\n", + " 'country':'Finland',\n", + " 'is_marred':True,\n", + " 'skills':['Python', 'Matlab', 'R', 'C', 'C++'],\n", + " 'address':{\n", + " 'street':'Space street',\n", + " 'zipcode':'02210'\n", + " }\n", + "}\n", + "for key in person:\n", + " if key == 'skills':\n", + " for skill in person['skills']:\n", + " print(skill)" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:53.465185Z", + "start_time": "2021-10-04T12:09:53.315774Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "17\n", + "19\n", + "23\n", + "29\n", + "31\n", + "37\n", + "41\n", + "43\n", + "47\n", + "53\n", + "340\n" + ] + } + ], + "source": [ + "# Example 2: Write a code to add all the prime numbers between 17 to 53 using while loop\n", + "# 17, 19, 23, 29, 31, 37, 41, 43, 47, 53\n", + "\n", + "sum=0\n", + "for i in range(17,54): \n", + " for j in range(2,i): \n", + " if i%j ==0: \n", + " break \n", + " else: \n", + " sum=sum+i\n", + " print(i)\n", + "print(sum)" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:53.556006Z", + "start_time": "2021-10-04T12:09:53.468116Z" + }, + "code_folding": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Red flower\n", + "Red watch\n", + "Pink flower\n", + "Pink watch\n" + ] + } + ], + "source": [ + "# Example 3: iterating through nested for loops\n", + "\n", + "color = ['Red', 'Pink']\n", + "element = ['flower', 'watch']\n", + "for i in color:\n", + " for j in element:\n", + " print(i, j)" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:53.571631Z", + "start_time": "2021-10-04T12:09:53.558938Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "45\n" + ] + } + ], + "source": [ + "# Example 4: A use case of a nested for loop in `list_of_lists` case would be\n", + "\n", + "list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n", + "total=0\n", + "for list1 in list_of_lists:\n", + " for i in list1:\n", + " total = total+i\n", + "print(total)" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:53.678564Z", + "start_time": "2021-10-04T12:09:53.576026Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "iteration 0: 1\n", + "iteration 1: 2\n", + "iteration 2: 3\n", + "iteration 3: 4\n", + "iteration 4: 5\n", + "iteration 5: 6\n" + ] + } + ], + "source": [ + "# Example 5:\n", + "\n", + "numbers = [[1, 2, 3], [4, 5, 6]]\n", + "\n", + "cnt = 0\n", + "for i in numbers:\n", + " for j in i:\n", + " print('iteration', cnt, end=': ')\n", + " print(j)\n", + " cnt = cnt + 1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Example: Nested `for` loop to print pattern\n", + "\n", + "```python\n", + "*\n", + "* *\n", + "* * *\n", + "* * * *\n", + "* * * * *\n", + "```\n", + "\n", + "```python\n", + ">>>rows = 5\n", + " # outer loop\n", + ">>>for i in range(1, rows + 1):\n", + " # inner loop\n", + ">>> for j in range(1, i + 1):\n", + ">>> print(\"*\", end=\" \")\n", + ">>> print('')\n", + "```\n", + "\n", + "
\n", + "\n", + "
\n", + "\n", + "**Explanation:**\n", + "\n", + "* In this program, the outer loop is the number of rows print. \n", + "* The number of rows is five, so the outer loop will execute five times\n", + "* Next, the inner loop is the total number of columns in each row.\n", + "* For each iteration of the outer loop, the columns count gets incremented by 1\n", + "* In the first iteration of the outer loop, the column count is 1, in the next it 2. and so on.\n", + "* The inner loop iteration is equal to the count of columns.\n", + "* In each iteration of an inner loop, we print star" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:09:53.800634Z", + "start_time": "2021-10-04T12:09:53.681496Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "* \n", + "* * \n", + "* * * \n", + "* * * * \n", + "* * * * * \n" + ] + } + ], + "source": [ + "# Example 1: Method 1\n", + "\n", + "rows = 5\n", + "for i in range(1, rows + 1): # outer loop \n", + " for j in range(1, i + 1): # inner loop\n", + " print(\"*\", end=\" \")\n", + " print('')" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:19.154180Z", + "start_time": "2021-10-04T12:09:53.805520Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "How many rows? 5\n", + "* \n", + "* * \n", + "* * * \n", + "* * * * \n", + "* * * * * \n" + ] + } + ], + "source": [ + "# Example 1: Method 2 - Print Floyd Triangle with user input\n", + "\t\t\n", + "\n", + "ran = input(\"How many rows? \")\n", + "\n", + "rang = int(ran)\n", + "k = 1\n", + "for i in range(1, rang+1):\n", + " for j in range(1, i+1):\n", + " print(\"*\", end=\" \")\n", + " k = k + 1\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:19.169316Z", + "start_time": "2021-10-04T12:10:19.157142Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 \n", + "2 2 \n", + "3 3 3 \n", + "4 4 4 4 \n", + "5 5 5 5 5 \n" + ] + } + ], + "source": [ + "# Example 2: Method 1\n", + "\n", + "for i in range(1,6): # numbers from 0,1,2,3,4,5\n", + " for j in range(1, i+1): \n", + " print(i, end=\" \") # print number \n", + " print(\" \") # line after each row to display pattern correctly" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:19.338754Z", + "start_time": "2021-10-04T12:10:19.171271Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " \n", + "1 \n", + "2 2 \n", + "3 3 3 \n", + "4 4 4 4 \n", + "5 5 5 5 5 \n" + ] + } + ], + "source": [ + "# Example 2: Method 2\n", + "\n", + "rows = 6 \n", + "for num in range(rows): # from 0,1,2,3,4,5\n", + " for i in range(num):\n", + " print(num,end=\" \") # print the number\n", + " print(\" \") # line after each row to print" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:19.539923Z", + "start_time": "2021-10-04T12:10:19.342658Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 \n", + "2 2 \n", + "3 3 3 \n", + "4 4 4 4 \n", + "5 5 5 5 5 \n" + ] + } + ], + "source": [ + "# Example 3: Method 3\n", + "\n", + "n=5 # giving number of rows i want\n", + "x = 0\n", + "for i in range(0 , n): # from 0 to 4\n", + " x += 1 # equivalent to x=x+1\n", + " for j in range(0, i + 1): # 0,1,2,3,4,5\n", + " print(x , end=\" \") \n", + " print(\" \") " + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:19.693243Z", + "start_time": "2021-10-04T12:10:19.549688Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 \n", + "1 2 \n", + "1 2 3 \n", + "1 2 3 4 \n", + "1 2 3 4 5 \n" + ] + } + ], + "source": [ + "# Example 4: Method 1\n", + "\n", + "rows = 5\n", + "for row in range(1, rows+1): # from 1\n", + " for column in range(1, row+1): # from 1,2,3,4,5\n", + " print(column, end=\" \")\n", + " print(\" \")" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:19.953986Z", + "start_time": "2021-10-04T12:10:19.699105Z" + }, + "scrolled": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 \n", + "1 2 \n", + "1 2 3 \n", + "1 2 3 4 \n", + "1 2 3 4 5 \n" + ] + } + ], + "source": [ + "# Example 4: Method 2\n", + "\n", + "for i in range (1, 6): # rows from 1 to 5\n", + " for j in range(i): # column range(i)\n", + " print (j + 1, end = ' ')\n", + " print ()" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:20.121956Z", + "start_time": "2021-10-04T12:10:19.956919Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 \n", + "2 1 \n", + "3 2 1 \n", + "4 3 2 1 \n", + "5 4 3 2 1 \n" + ] + }, + { + "data": { + "text/plain": [ + "'\\ni = 1 2 3 4 5 \\n\\n# loop 1\\nfor i = 1, range (1,0,-1): j=1\\ni = 1, print: 1 \\n\\n# loop 2\\nfor i =2, range (2,0,-1): j = 2,1\\ni = 2, print: 2,1\\n'" + ] + }, + "execution_count": 42, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Example 5: Method 1\n", + "\n", + "for i in range (1,6):\n", + " for j in range (i,0,-1):\n", + " print(j, end=\" \")\n", + " print(\" \")\n", + " \n", + "\"\"\"\n", + "i = 1 2 3 4 5 \n", + "\n", + "# loop 1\n", + "for i = 1, range (1,0,-1): j=1\n", + "i = 1, print: 1 \n", + "\n", + "# loop 2\n", + "for i =2, range (2,0,-1): j = 2,1\n", + "i = 2, print: 2,1\n", + "\"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:20.245002Z", + "start_time": "2021-10-04T12:10:20.124886Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 \n", + "2 1 \n", + "3 2 1 \n", + "4 3 2 1 \n", + "5 4 3 2 1 \n" + ] + } + ], + "source": [ + "# Example 5: Method 2\n", + "\n", + "for i in range(0,5):\n", + " for j in range(i+1,0,-1):\n", + " print(j, end=\" \")\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:20.398322Z", + "start_time": "2021-10-04T12:10:20.249887Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "* * * * * \n", + "* * * * \n", + "* * * \n", + "* * \n", + "* \n" + ] + } + ], + "source": [ + "# Example 6: Example 1 reverse pyramid \n", + "\n", + "\n", + "for i in range (1,6): # rows from 1 to 5\n", + " for j in range (5,i-1,-1): # column range(5,0,-1) = 54321\n", + " print (\"*\", end=\" \"),\n", + " print (\" \")" + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:20.521369Z", + "start_time": "2021-10-04T12:10:20.401256Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "5 5 5 5 5 \n", + "4 4 4 4 \n", + "3 3 3 \n", + "2 2 \n", + "1 \n" + ] + } + ], + "source": [ + "# Example 7: Example 2 reverse pyramid Method 1\n", + "\n", + "rows = 5\n", + "# range(1,10,2) # from 1,3,5,7,9\n", + "for i in range(rows,0,-1): # from 3,2,1\n", + " num = i\n", + " for j in range(0,i):\n", + " print(num, end=\" \")\n", + " print(\" \")" + ] + }, + { + "cell_type": "code", + "execution_count": 46, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:20.736215Z", + "start_time": "2021-10-04T12:10:20.526255Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "5 5 5 5 5 \n", + "4 4 4 4 \n", + "3 3 3 \n", + "2 2 \n", + "1 \n" + ] + }, + { + "data": { + "text/plain": [ + "'\\ni = 5 4 3 2 1 \\n\\n# loop 1\\nfor i = 5, range (0,5): j=5 4 3 2 1\\ni = 5, print: 5 5 5 5 5\\n\\n# loop 2\\nfor i = 4, range (0,4): j=4 3 2 1\\ni = 4, print: 4 4 4 4 \\n'" + ] + }, + "execution_count": 46, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Example 7: Example 2 reverse pyramid Method 2\n", + "\n", + "for i in range(5,0,-1): # range from 5 4 3 2 1\n", + " for j in range(0,i): # range(0,5)=0 1 2 3 4\n", + " print(i, end=\" \")\n", + " print(\" \")\n", + " \n", + "\"\"\"\n", + "i = 5 4 3 2 1 \n", + "\n", + "# loop 1\n", + "for i = 5, range (0,5): j=5 4 3 2 1\n", + "i = 5, print: 5 5 5 5 5\n", + "\n", + "# loop 2\n", + "for i = 4, range (0,4): j=4 3 2 1\n", + "i = 4, print: 4 4 4 4 \n", + "\"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:20.873909Z", + "start_time": "2021-10-04T12:10:20.739145Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 2 3 4 5 \n", + "1 2 3 4 \n", + "1 2 3 \n", + "1 2 \n", + "1 \n" + ] + } + ], + "source": [ + "# Example 8: Method 1\n", + "\n", + "for i in range(5,0,-1): # rows range = 5 4 3 2 1 \n", + " for j in range(1,i+1): # column range \n", + " print(j, end =\" \")\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:21.094614Z", + "start_time": "2021-10-04T12:10:20.877817Z" + }, + "scrolled": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 2 3 4 5 \n", + "1 2 3 4 \n", + "1 2 3 \n", + "1 2 \n", + "1 \n" + ] + }, + { + "data": { + "text/plain": [ + "'\\ni = 1 2 3 4 5 \\n\\n# loop 1\\nfor i = 1, range (5): j=0 1 2 3 4\\ni = 1, print: 1 2 3 4 5\\n\\n# loop 2\\nfor i = 2, range (4): j=0 1 2 3\\ni = 2, print: 1 2 3 4\\n\\n# loop 3\\nfor i = 3, range (3): j=0 1 2\\ni = 3, print: 1 2 3\\n\\n# loop 4\\nfor i = 4, range (2): j=0 1\\ni = 4, print: 1 2\\n\\n# loop 5\\nfor i = 5, range (1): j=0 \\ni = 5, print: 1 \\n'" + ] + }, + "execution_count": 48, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Example 8: Method 2\n", + "\n", + "for i in range(1,6):\n", + " for j in range(6-i):\n", + " print(j+1, end=\" \")\n", + " print(\" \")\n", + " \n", + "\"\"\"\n", + "i = 1 2 3 4 5 \n", + "\n", + "# loop 1\n", + "for i = 1, range (5): j=0 1 2 3 4\n", + "i = 1, print: 1 2 3 4 5\n", + "\n", + "# loop 2\n", + "for i = 2, range (4): j=0 1 2 3\n", + "i = 2, print: 1 2 3 4\n", + "\n", + "# loop 3\n", + "for i = 3, range (3): j=0 1 2\n", + "i = 3, print: 1 2 3\n", + "\n", + "# loop 4\n", + "for i = 4, range (2): j=0 1\n", + "i = 4, print: 1 2\n", + "\n", + "# loop 5\n", + "for i = 5, range (1): j=0 \n", + "i = 5, print: 1 \n", + "\"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": 49, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:21.227425Z", + "start_time": "2021-10-04T12:10:21.103408Z" + } + }, + "outputs": [], + "source": [ + "# Example 9: Print following rectangle of stars of 6 rows and 3 columns\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### `while` loop inside `for` loop\n", + "\n", + "The **[while loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/006_Python_while_Loop.ipynb)** is an entry-controlled loop, and a **`for`** loop is a count-controlled loop. We can also use a **`while`** loop under the for loop statement. For example," + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:21.427621Z", + "start_time": "2021-10-04T12:10:21.232310Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Multiplication table of: 1\n", + "1 2 3 4 5 6 7 8 9 10 \n", + "\n", + "Multiplication table of: 2\n", + "2 4 6 8 10 12 14 16 18 20 \n", + "\n", + "Multiplication table of: 3\n", + "3 6 9 12 15 18 21 24 27 30 \n", + "\n", + "Multiplication table of: 4\n", + "4 8 12 16 20 24 28 32 36 40 \n", + "\n", + "Multiplication table of: 5\n", + "5 10 15 20 25 30 35 40 45 50 \n", + "\n" + ] + } + ], + "source": [ + "# Example 1: Print Multiplication table of a first 5 numbers using `for` loop and `while` loop\n", + "\n", + "# outer loop\n", + "for i in range(1, 6):\n", + " print('Multiplication table of:', i)\n", + " count = 1\n", + " # inner loop to print multiplication table of current number\n", + " while count < 11:\n", + " print(i * count, end=' ')\n", + " count = count + 1\n", + " print('\\n')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:** \n", + "\n", + "* In this program, we iterate the first five numbers one by one using the outer loop and range function\n", + "* Next, in each iteration of the outer loop, we will use the inner while loop to print the multiplication table of the current number" + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:21.551647Z", + "start_time": "2021-10-04T12:10:21.431529Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Amy Amy Amy Amy Amy \n", + "Bella Bella Bella Bella Bella \n", + "Cathy Cathy Cathy Cathy Cathy \n" + ] + } + ], + "source": [ + "# Example 2:\n", + "\n", + "names = ['Amy', 'Bella', 'Cathy']\n", + "\n", + "for name in names: # outer loop \n", + " count = 0 # inner while loop\n", + " while count < 5:\n", + " print(name, end=' ')\n", + " # increment counter\n", + " count = count + 1\n", + " print()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## `for ` loop in one line\n", + "\n", + "We can also formulate the **`for`** loop statement in one line to reduce the number of lines of code. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 52, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:21.719615Z", + "start_time": "2021-10-04T12:10:21.556531Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[33, 63, 93, 36, 66, 96, 39, 69, 99]\n" + ] + } + ], + "source": [ + "# Example 1: regular `for` loop code\n", + "\n", + "first = [3, 6, 9]\n", + "second = [30, 60, 90]\n", + "final = []\n", + "for i in first:\n", + " for j in second:\n", + " final.append(i+j)\n", + "print(final)" + ] + }, + { + "cell_type": "code", + "execution_count": 53, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:21.858284Z", + "start_time": "2021-10-04T12:10:21.723522Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[33, 63, 93, 36, 66, 96, 39, 69, 99]\n" + ] + } + ], + "source": [ + "# Example 1: single line `for` loop code\n", + "\n", + "first = [3, 6, 9]\n", + "second = [30, 60, 90]\n", + "final = [i+j for i in first for j in second]\n", + "print(final)" + ] + }, + { + "cell_type": "code", + "execution_count": 54, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:21.997934Z", + "start_time": "2021-10-04T12:10:21.861219Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[2, 6, 8, 10]\n" + ] + } + ], + "source": [ + "# Example 2: Print the even numbers by adding 1 to the odd numbers in the list\n", + "\n", + "odd = [1, 5, 7, 9]\n", + "even = [i + 1 for i in odd if i % 2 == 1]\n", + "print(even)" + ] + }, + { + "cell_type": "code", + "execution_count": 55, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:22.151254Z", + "start_time": "2021-10-04T12:10:22.000865Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[30, 60], [30, 90], [60, 30], [60, 90], [90, 60], [90, 30]]\n" + ] + } + ], + "source": [ + "# Example 3:\n", + "\n", + "final = [[x, y] for x in [30, 60, 90] for y in [60, 30, 90] if x != y]\n", + "print(final)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Accessing the index in for loop\n", + "\n", + "The **[enumerate()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/018_Python_enumerate%28%29.ipynb)** function is useful when we wanted to access both value and its index number or any sequence such as list or string. For example, a list is an ordered data structure that stores each item with its index number. Using the item’s index number, we can access or modify its value.\n", + "\n", + "Using enumerate function with a loop, we can access the list’s items with their index number. The **`enumerate()`** adds a counter to iteration and returns it in the form of an enumerable object.\n", + "\n", + "There three ways to access the index in **`for`** loop let’s see each one by one" + ] + }, + { + "cell_type": "code", + "execution_count": 56, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:22.335828Z", + "start_time": "2021-10-04T12:10:22.154187Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Numbers[ 0 ] = 4\n", + "Numbers[ 1 ] = 2\n", + "Numbers[ 2 ] = 5\n", + "Numbers[ 3 ] = 7\n", + "Numbers[ 4 ] = 8\n" + ] + } + ], + "source": [ + "# Example 1: Print elements of the list with its index number using the `enumerate()` function\n", + "\n", + "#In this program, the for loop iterates through the list and displays the \n", + "#elements along with its index number.\n", + "\n", + "numbers = [4, 2, 5, 7, 8]\n", + "for i, v in enumerate(numbers):\n", + " print('Numbers[', i, '] =', v)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 57, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:22.474496Z", + "start_time": "2021-10-04T12:10:22.338757Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Index: 0 Value: 1\n", + "Index: 1 Value: 2\n", + "Index: 2 Value: 4\n", + "Index: 3 Value: 6\n", + "Index: 4 Value: 8\n" + ] + } + ], + "source": [ + "# Example 2: Printing the elements of the list with its index number using the `range()` function\n", + "\n", + "numbers = [1, 2, 4, 6, 8]\n", + "size = len(numbers)\n", + "for i in range(size):\n", + " print('Index:', i, \" \", 'Value:', numbers[i])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Iterate String using `for` loop\n", + "\n", + "By looping through the **[string](https://github.com/milaan9/02_Python_Datatypes/blob/main/002_Python_String.ipynb)** using **`for`** loop, we can do lots of string operations. Let’s see how to perform various string operations using a **`for`** loop." + ] + }, + { + "cell_type": "code", + "execution_count": 58, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:22.613169Z", + "start_time": "2021-10-04T12:10:22.477429Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "P\n", + "y\n", + "t\n", + "h\n", + "o\n", + "n\n", + "P\n", + "y\n", + "t\n", + "h\n", + "o\n", + "n\n" + ] + } + ], + "source": [ + "# Example 1: For loop with string\n", + "\n", + "# Method 1:\n", + "language = 'Python'\n", + "for letter in language:\n", + " print(letter)\n", + "\n", + "# Method 2: using range() function\n", + "\n", + "for i in range(len(language)):\n", + " print(language[i])" + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:22.721568Z", + "start_time": "2021-10-04T12:10:22.617079Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "H\n", + "e\n", + "l\n", + "l\n", + "o\n", + " \n", + "W\n", + "o\n", + "r\n", + "l\n", + "d\n" + ] + } + ], + "source": [ + "# Example 2: Printing the elements of a string using for loop\n", + "\n", + "for i in 'Hello World':\n", + " print(i)" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:22.843641Z", + "start_time": "2021-10-04T12:10:22.724500Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A l a n " + ] + } + ], + "source": [ + "# Example 3: Access all characters of a string\n", + "\n", + "name = \"Alan\"\n", + "for i in name:\n", + " print(i, end=' ')" + ] + }, + { + "cell_type": "code", + "execution_count": 61, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:22.967662Z", + "start_time": "2021-10-04T12:10:22.848523Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "n a l A " + ] + } + ], + "source": [ + "# Example 4: Iterate string in reverse order\n", + "\n", + "name = \"Alan\"\n", + "for i in name[::-1]:\n", + " print(i, end=' ')" + ] + }, + { + "cell_type": "code", + "execution_count": 62, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:23.120985Z", + "start_time": "2021-10-04T12:10:22.971571Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "a n W a " + ] + } + ], + "source": [ + "# Example 5: Iterate over a particular set of characters in string\n", + "\n", + "name = \"Alan Watson\"\n", + "for char in name[2:7:1]:\n", + " print(char, end=' ')" + ] + }, + { + "cell_type": "code", + "execution_count": 63, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:23.244033Z", + "start_time": "2021-10-04T12:10:23.123915Z" + }, + "scrolled": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Remember,\n", + "Red,\n", + "hope\n", + "is\n", + "a\n", + "good\n", + "thing,\n", + "maybe\n", + "the\n", + "best\n", + "of\n", + "things,\n", + "and\n", + "no\n", + "good\n", + "thing\n", + "ever\n", + "dies\n" + ] + } + ], + "source": [ + "# Example 6: Iterate over words in a sentence using the `split()` function.\n", + "\n", + "dialogue = \"Remember, Red, hope is a good thing, maybe the best of things, and no good thing ever dies\"\n", + "# split on whitespace\n", + "for word in dialogue.split():\n", + " print(word)" + ] + }, + { + "cell_type": "code", + "execution_count": 64, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:23.352429Z", + "start_time": "2021-10-04T12:10:23.246960Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "a\n", + "b\n", + "c\n", + "total = 14\n" + ] + } + ], + "source": [ + "# Example 7:\n", + "\n", + "for ch in 'abc':\n", + " print(ch)\n", + "total = 0\n", + "for i in range(5): # from 0 to 4\n", + " total += i # total = 0+1+2+3+4 = 10\n", + "for i,j in [(1,2),(3,1)]: # [(1),(3)]\n", + " total += i**j # total = 1+3 = 4\n", + "print(\"total =\",total)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Iterate List using `for` loop\n", + "\n", + "**[Python list](https://github.com/milaan9/02_Python_Datatypes/blob/main/003_Python_List.ipynb)** is an ordered collection of items of different data types. It means Lists are ordered by index numbers starting from 0 to the total items-1. List items are enclosed in square **`[]`** brackets.\n", + "\n", + "Below are the few examples of Python list.\n", + "\n", + "```python\n", + ">>> numers = [1,2,4,6,7]\n", + ">>> players = [\"Messi\", \"Ronaldo\", \"Neymar\"]\n", + "```\n", + "Using a loop, we can perform various operations on the list. There are ways to iterate through elements in it. Here are some examples to help you understand better." + ] + }, + { + "cell_type": "code", + "execution_count": 65, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:23.476453Z", + "start_time": "2021-10-04T12:10:23.356337Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n", + "6\n", + "9\n" + ] + } + ], + "source": [ + "# Example 1: Iterate over a list Method 1\n", + "\n", + "numbers = [1, 2, 3, 6, 9]\n", + "for num in numbers:\n", + " print(num)" + ] + }, + { + "cell_type": "code", + "execution_count": 66, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:23.617078Z", + "start_time": "2021-10-04T12:10:23.480360Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n", + "6\n", + "9\n" + ] + }, + { + "data": { + "text/plain": [ + "[None, None, None, None, None]" + ] + }, + "execution_count": 66, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Example 2: Iterate over a list Method 2 (list comprehension)\n", + "\n", + "numbers = [1, 2, 3, 6, 9]\n", + "[print(i) for i in numbers]" + ] + }, + { + "cell_type": "code", + "execution_count": 67, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:23.738173Z", + "start_time": "2021-10-04T12:10:23.620986Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n", + "6\n", + "9\n" + ] + } + ], + "source": [ + "# Example 3: Iterate over a list using a for loop and range.\n", + "\n", + "numbers = [1, 2, 3, 6, 9]\n", + "size = len(numbers)\n", + "for i in range(size):\n", + " print(numbers[i])" + ] + }, + { + "cell_type": "code", + "execution_count": 68, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:23.846571Z", + "start_time": "2021-10-04T12:10:23.741102Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[2, 4, 6, 8, 10]\n", + "[2, 4, 6, 8, 10]\n", + "[2, 4, 6, 8, 10]\n", + "[2, 4, 6, 8, 10]\n", + "[2, 4, 6, 8, 10]\n" + ] + } + ], + "source": [ + "# Example 4: printing the elements of a list using for loop\n", + "\n", + "even_numbers = [2, 4, 6, 8, 10] # list with 5 elements\n", + "for i in even_numbers:\n", + " print(even_numbers)" + ] + }, + { + "cell_type": "code", + "execution_count": 69, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:24.000869Z", + "start_time": "2021-10-04T12:10:23.850479Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "60\n", + "HelloWorld\n", + "90.96\n" + ] + } + ], + "source": [ + "# Example 5: printing the elements of a list using for loop\n", + "\n", + "list = [60, \"HelloWorld\", 90.96]\n", + "for i in list:\n", + " print(i)" + ] + }, + { + "cell_type": "code", + "execution_count": 70, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:24.141492Z", + "start_time": "2021-10-04T12:10:24.023330Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The sum is 50\n" + ] + } + ], + "source": [ + "# Example 6: Program to find the sum of all numbers stored in a list\n", + "\n", + "# List of numbers\n", + "numbers = [6, 5, 3, 8, 4, 2, 5, 6, 11] # list with 9 elements\n", + "\n", + "# variable to store the sum\n", + "sum = 0\n", + "\n", + "# iterate over the list\n", + "for val in numbers:\n", + " sum = sum+val\n", + "\n", + "print(\"The sum is\", sum)" + ] + }, + { + "cell_type": "code", + "execution_count": 71, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:24.306532Z", + "start_time": "2021-10-04T12:10:24.159071Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Square of: 1 is: 1\n", + "Square of: 2 is: 4\n", + "Square of: 3 is: 9\n", + "Square of: 4 is: 16\n", + "Square of: 5 is: 25\n" + ] + } + ], + "source": [ + "# Example 7: Calculate the square of each number using for loop.\n", + "\n", + "numbers = [1, 2, 3, 4, 5]\n", + "# iterate over each element in list num\n", + "for i in numbers:\n", + " # ** exponent operator\n", + " square = i ** 2\n", + " print(\"Square of:\", i, \"is:\", square)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:** **`i`** iterates over the 0,1,2,3,4. Every time it takes each value and executes the algorithm inside the loop. It is also possible to iterate over a nested list illustrated below." + ] + }, + { + "cell_type": "code", + "execution_count": 72, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:24.413953Z", + "start_time": "2021-10-04T12:10:24.309463Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "30.0\n" + ] + } + ], + "source": [ + "# Example 8: Calculate the average of list of numbers\n", + "\n", + "numbers = [10, 20, 30, 40, 50]\n", + "\n", + "# definite iteration\n", + "# run loop 5 times because list contains 5 items\n", + "sum = 0\n", + "for i in numbers:\n", + " sum = sum + i\n", + "list_size = len(numbers)\n", + "average = sum / list_size\n", + "print(average)" + ] + }, + { + "cell_type": "code", + "execution_count": 73, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:24.553606Z", + "start_time": "2021-10-04T12:10:24.418839Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "3\n", + "Green\n", + "Pink\n", + "Blue\n" + ] + } + ], + "source": [ + "# Example 9: Printing a list using range function\n", + "\n", + "color = ['Green', 'Pink', 'Blue'] # list with total 3 elements\n", + "print(len(color)) # print length of color\n", + "for i in range(len(color)):\n", + " print(color[i])" + ] + }, + { + "cell_type": "code", + "execution_count": 74, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:24.569228Z", + "start_time": "2021-10-04T12:10:24.559462Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3]\n", + "[4, 5, 6]\n", + "[7, 8, 9]\n" + ] + } + ], + "source": [ + "# Example 10: Printing a list using range function\n", + "\n", + "list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # list with 3 elements\n", + "for list1 in list_of_lists:\n", + " print(list1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Iterate Tuple using `for` loop\n", + "\n", + "**[Python list](https://github.com/milaan9/02_Python_Datatypes/blob/main/004_Python_Tuple.ipynb)** Only the difference is that list is enclosed between square bracket **`[]`**, tuple between parentheses **`()`** and we cannot change the elements of a tuple once it is assigned, i.e., **immutable** whereas we can change the elements of a list i.e., **mutable**.\n", + "\n", + "Below are the few examples of Python list.\n", + "\n", + "```python\n", + ">>> numers = (1,2,4,6,7)\n", + ">>> players = (\"Messi\", \"Ronaldo\", \"Neymar\")\n", + "```\n", + "Using a loop, we can perform various operations on the tuple. There are ways to iterate through elements in it. Here are some examples to help you understand better." + ] + }, + { + "cell_type": "code", + "execution_count": 75, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:24.723523Z", + "start_time": "2021-10-04T12:10:24.572159Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "5\n" + ] + } + ], + "source": [ + "# Example 1: For loop with tuple\n", + "\n", + "numbers = (0, 1, 2, 3, 4, 5)\n", + "for number in numbers:\n", + " print(number)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Iterate Dictionary using `for` loop\n", + "\n", + "**[Python dictionary](https://github.com/milaan9/02_Python_Datatypes/blob/main/005_Python_Dictionary.ipynb)** is used to store the items in the format of **key-value** pair. It doesn’t allow duplicate items. It is enclosed with **`{}`**. Here are some of the examples of dictionaries.\n", + "\n", + "```python\n", + ">>> dict1 = {1: \"Apple\", 2: \"Ball\", 3: \"Cat\"}\n", + ">>> dict2 = {\"Antibiotics\": \"Penicillin\", \"Inventor\": \"Fleming\", \"Year\": 1928}\n", + "```\n", + "\n", + "There are ways to iterate through **key-value** pairs. Here are some examples to help you understand better." + ] + }, + { + "cell_type": "code", + "execution_count": 76, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:24.876845Z", + "start_time": "2021-10-04T12:10:24.727434Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Antibiotics\n", + "Inventor\n", + "Year\n" + ] + } + ], + "source": [ + "# Example 1: Access only the keys of the dictionary.\n", + "\n", + "dict1 = {\"Antibiotics\": \"Penicillin\", \"Inventor\": \"Fleming\", \"Year\": 1928}\n", + "for key in dict1:\n", + " print(key)" + ] + }, + { + "cell_type": "code", + "execution_count": 77, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:25.062391Z", + "start_time": "2021-10-04T12:10:24.879776Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Vaccine -> Polio\n", + "Inventor -> Salk\n", + "Year -> 1953\n" + ] + } + ], + "source": [ + "# Example 2: Iterate keys and values of the dictionary\n", + "\n", + "dict1 = {\"Vaccine\": \"Polio\", \"Inventor\": \"Salk\", \"Year\": 1953}\n", + "for key in dict1:\n", + " print(key, \"->\", dict1[key])" + ] + }, + { + "cell_type": "code", + "execution_count": 78, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:25.216690Z", + "start_time": "2021-10-04T12:10:25.065324Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Smallpox \n", + "Jenner\n", + "1796\n" + ] + } + ], + "source": [ + "# Example 3: Iterate only the values the dictionary\n", + "\n", + "dict1 = {\"Vaccine\": \"Smallpox \", \"Inventor\": \"Jenner\", \"Year\": 1796}\n", + "for value in dict1.values():\n", + " print(value)" + ] + }, + { + "cell_type": "code", + "execution_count": 79, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:25.339735Z", + "start_time": "2021-10-04T12:10:25.221574Z" + }, + "scrolled": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "first_name\n", + "last_name\n", + "age\n", + "country\n", + "is_marred\n", + "skills\n", + "address\n", + "first_name Milaan\n", + "last_name Parmar\n", + "age 96\n", + "country Finland\n", + "is_marred True\n", + "skills ['Python', 'Matlab', 'R', 'C', 'C++']\n", + "address {'street': 'Space street', 'zipcode': '02210'}\n" + ] + } + ], + "source": [ + "# Example 4: For loop with dictionary\n", + "#Looping through a dictionary gives you the key of the dictionary.\n", + "\n", + "person = {\n", + " 'first_name':'Milaan',\n", + " 'last_name':'Parmar',\n", + " 'age':96,\n", + " 'country':'Finland',\n", + " 'is_marred':True,\n", + " 'skills':['Python', 'Matlab', 'R', 'C', 'C++'],\n", + " 'address':{\n", + " 'street':'Space street',\n", + " 'zipcode':'02210'\n", + " }\n", + "}\n", + "for key in person:\n", + " print(key)\n", + "\n", + "for key, value in person.items():\n", + " print(key, value) # this way we get both keys and values printed out" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Iterate Set using `for` loop\n", + "\n", + "**[Python sets](https://github.com/milaan9/02_Python_Datatypes/blob/main/006_Python_Sets.ipynb)** is an unordered collection of items. Every set element is unique (no duplicates) and must be immutable (cannot be changed).\n", + "\n", + "However, a set itself is **mutable**. We can add or remove items from it.\n", + "\n", + "```python\n", + ">>> my_set = {1, 2, 3}\n", + ">>> my_vaccine = {\"Penicillin\", \"Fleming\", \"1928\"}\n", + "```\n", + "\n", + "Sets can also be used to perform mathematical set operations like **union**, **intersection**, **symmetric difference**, etc." + ] + }, + { + "cell_type": "code", + "execution_count": 80, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:10:25.509661Z", + "start_time": "2021-10-04T12:10:25.343645Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "GUava\n", + "Banana\n", + "Grape\n", + "Kiwi\n", + "Orange\n", + "Apple\n", + "Mango\n" + ] + } + ], + "source": [ + "# Example 6: For loop with set\n", + "\n", + "mix_fruits = {'Banana', 'Apple', 'Mango', 'Orange', 'GUava', 'Kiwi', 'Grape'}\n", + "for fruits in mix_fruits:\n", + " print(fruits)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 💻 Exercises ➞ List\n", + "\n", + "### Exercises ➞ Level 1\n", + "\n", + "1. Iterate 0 to 10 using **`for`** loop, do the same using **`while`** loop.\n", + "2. Iterate 10 to 0 using **`for`** loop, do the same using **`while`** loop.\n", + "3. Write a loop that makes seven calls to **`print()`**, so we get on the output the following triangle:\n", + "\n", + "```py\n", + "# # # # # # # #\n", + "# # # # # # # #\n", + "# # # # # # # #\n", + "# # # # # # # #\n", + "# # # # # # # #\n", + "# # # # # # # #\n", + "# # # # # # # #\n", + "# # # # # # # #\n", + "```\n", + "\n", + "4. Use nested loops to create the following:\n", + "\n", + "```py\n", + " #\n", + " ###\n", + " #####\n", + " #######\n", + " #########\n", + " ###########\n", + "#############\n", + "```\n", + "\n", + "5. Print the following pattern using loops\n", + "\n", + "```py\n", + " 0 x 0 = 0\n", + " 1 x 1 = 1\n", + " 2 x 2 = 4\n", + " 3 x 3 = 9\n", + " 4 x 4 = 16\n", + " 5 x 5 = 25\n", + " 6 x 6 = 36\n", + " 7 x 7 = 49\n", + " 8 x 8 = 64\n", + " 9 x 9 = 81\n", + " 10 x 10 = 100\n", + "```\n", + "\n", + "6. Iterate through the list, ['Python', 'Numpy','Pandas','Scikit', 'Pytorch'] using a **`for`** loop and print out the items.\n", + "7. Use **`for`** loop to iterate from 0 to 100 and print only even numbers\n", + "8. Use **`for`** loop to iterate from 0 to 100 and print only odd numbers\n", + " \n", + "### Exercises ➞ Level 2\n", + " \n", + "1. Use **`for`** loop to iterate from 0 to 100 and print the sum of all numbers.\n", + "\n", + "```py\n", + " The sum of all numbers is 5050.\n", + "```\n", + "\n", + "1. Use **`for`** loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds.\n", + "\n", + "```py\n", + " The sum of all evens is 2550. And the sum of all odds is 2500.\n", + "```\n", + "\n", + "### Exercises ➞ Level 3\n", + "\n", + "1. Go to the data folder and use the **[countries.py](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries.py)** file. Loop through the countries and extract all the countries containing the word **`land`**.\n", + "1. This is a fruit list, ['banana', 'orange', 'mango', 'lemon'] reverse the order using loop.\n", + "2. Go to the data folder and use the **[countries_data.py](https://github.com/milaan9/03_Python_Flow_Control/blob/main/countries_details_data.py)** file. \n", + " 1. What are the total number of languages in the data\n", + " 2. Find the ten most spoken languages from the data\n", + " 3. Find the 10 most populated countries in the world" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "hide_input": false, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.8" + }, + "toc": { + "base_numbering": 1, + "nav_menu": {}, + "number_sections": true, + "sideBar": true, + "skip_h1_title": false, + "title_cell": "Table of Contents", + "title_sidebar": "Contents", + "toc_cell": false, + "toc_position": {}, + "toc_section_display": true, + "toc_window_display": false + }, + "varInspector": { + "cols": { + "lenName": 16, + "lenType": 16, + "lenVar": 40 + }, + "kernels_config": { + "python": { + "delete_cmd_postfix": "", + "delete_cmd_prefix": "del ", + "library": "var_list.py", + "varRefreshCmd": "print(var_dic_list())" + }, + "r": { + "delete_cmd_postfix": ") ", + "delete_cmd_prefix": "rm(", + "library": "var_list.r", + "varRefreshCmd": "cat(var_dic_list()) " + } + }, + "types_to_exclude": [ + "module", + "function", + "builtin_function_or_method", + "instance", + "_Feature" + ], + "window_display": false + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/006_Python_while_Loop.ipynb b/006_Python_while_Loop.ipynb new file mode 100644 index 0000000..36fad61 --- /dev/null +++ b/006_Python_while_Loop.ipynb @@ -0,0 +1,1646 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "All the IPython Notebooks in **Python Flow Control Statements** lecture series by Dr. Milaan Parmar are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)**\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Loops in Python\n", + "\n", + "Loops in Python programming function similar to loops in C, C++, Java or other languages. Python loops are used to repeatedly execute a block of statements until a given condition returns to be **`False`**. In Python, we have **two types of looping statements**, namely:\n", + "
\n", + "\n", + "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Python `while` Loop\n", + "\n", + "Loops are used in programming to repeat a specific block of code. In this article, you will learn to create a **`while`** loop in Python. We use a **`while`** loop when we want to repeat a code block." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## What is `while` loop in Python?\n", + "\n", + "The **`while`** loop in Python is used to iterate over a block of code as long as the expression/condition is **`True`**. When the condition becomes **`False`**, execution comes out of the loop immediately, and the first statement after the **`while`** loop is executed.\n", + "\n", + "We generally use this loop when we don't know the number of times to iterate beforehand.\n", + "\n", + "Python interprets any non-zero value as **`True`**. **`None`** and **`0`** are interpreted as **`False`**." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Why and When to use `while` loop in Python\n", + "\n", + "Now, the question might arise: when do we use a **`while`** loop, and why do we use it.\n", + "\n", + "* **Automate and repeat tasks:** As we know, **`while`** loops execute blocks of code over and over again until the condition is met it allows us to automate and repeat tasks in an efficient manner.\n", + "* **Indefinite Iteration:**The **`while`** loop will run as often as necessary to complete a particular task. When the user doesn’t know the number of iterations before execution, **`while`** loop is used instead of a **[for loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/005_Python_for_Loop.ipynb)** loop\n", + "* **Reduce complexity:** **`while`** loop is easy to write. using the loop, we don’t need to write the statements again and again. Instead, we can write statements we wanted to execute again and again inside the body of the loop thus, reducing the complexity of the code\n", + "* **Infinite loop:** If the code inside the **`while`** loop doesn’t modify the variables being tested in the loop condition, the loop will run forever." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Syntax: \n", + "\n", + "```python\n", + "while condition:\n", + " body of while loop\n", + "```\n", + "1. In the **`while`** loop, expression/condition is checked first.\n", + "2. The body of the loop is entered only if the expression/condition evaluates to **`True`**.\n", + "3. After one iteration, the expression/condition is checked again. This process continues until the test_expression evaluates to **`False`**.\n", + "\n", + "
\n", + "\n", + "
\n", + "\n", + ">**Note:** An infinite loop occurs when a program keeps executing within one loop, never leaving it. To exit out of infinite loops on the command line, press **CTRL + C**." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:18.052046Z", + "start_time": "2021-10-04T12:15:18.041303Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n", + "4\n" + ] + } + ], + "source": [ + "# Example 1: Print numbers less than 5\n", + "\n", + "count = 1\n", + "# run loop till count is less than 5\n", + "while count < 5:\n", + " print(count)\n", + " count = count + 1" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:18.175091Z", + "start_time": "2021-10-04T12:15:18.059861Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Sum of first 10 number is: 55\n" + ] + } + ], + "source": [ + "# Example 2:\n", + "\n", + "num = 10\n", + "sum = 0\n", + "i = 1\n", + "while i <= num:\n", + " sum = sum + i\n", + " i = i + 1\n", + "print(\"Sum of first 10 number is:\", sum)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:18.297648Z", + "start_time": "2021-10-04T12:15:18.178999Z" + }, + "scrolled": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Value of a is 10\n", + "Value of a is 8\n", + "Value of a is 6\n", + "Value of a is 4\n", + "Value of a is 2\n", + "Loop is Completed\n" + ] + } + ], + "source": [ + "# Example 3:\n", + "\n", + "a=10 # 'a' is my variable\n", + "\n", + "while a>0: # Enter the body of while loop because condition is TRUE\n", + " print ((\"Value of a is\"),a)\n", + " a=a-2\n", + "print (\"Loop is Completed\")" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:18.406047Z", + "start_time": "2021-10-04T12:15:18.307417Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "9.999999999999998\n" + ] + } + ], + "source": [ + "# Example 4:\n", + "\n", + "n=153\n", + "sum=0\n", + "\n", + "while n>0:\n", + " r=n%10 # r is the remainder of the division\n", + " sum+=r # sum+=r is equal to sum = sum+r\n", + " n=n/10\n", + "print (sum)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:18.559855Z", + "start_time": "2021-10-04T12:15:18.409468Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Total iteration required 3\n" + ] + } + ], + "source": [ + "# Example 5: How many times a given number can be divided by 3 before it is less than or equal to 10.\n", + "\n", + "count = 0\n", + "number = 180\n", + "while number > 10:\n", + " # divide number by 3\n", + " number = number / 3\n", + " # increase count\n", + " count = count + 1\n", + "print('Total iteration required', count)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:18.747846Z", + "start_time": "2021-10-04T12:15:18.565720Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The sum is 55\n" + ] + } + ], + "source": [ + "# Example 6: Program to add natural numbers up to sum = 1+2+3+...+n\n", + "\n", + "# To take input from the user, \n", + "# n = int(input(\"Enter n: \"))\n", + "\n", + "n = 10\n", + "\n", + "# initialize sum and counter\n", + "sum = 0\n", + "i = 1\n", + "\n", + "while i <= n:\n", + " sum = sum + i\n", + " i = i+1 # update counter, i.e., the value of i will change from 1 to 2 in next iteration...\n", + "\n", + "# print the sum\n", + "print(\"The sum is\", sum)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "In the above program, the test expression will be **`True`** as long as our counter variable **`i`** is less than or equal to **`n`** (10 in our program).\n", + "\n", + "We need to increase the value of the counter variable in the body of the loop. This is very important (and mostly forgotten). Failing to do so will result in an infinite loop (never-ending loop).\n", + "\n", + "Finally, the result is displayed." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:18.913373Z", + "start_time": "2021-10-04T12:15:18.751753Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 \n" + ] + } + ], + "source": [ + "# Example 7: simple fibonacci series\n", + "# the sum of two elements defines the next set\n", + "\n", + "a, b = 0, 1\n", + "while b < 1000:\n", + " print(b, end = ' ', flush = True)\n", + " a, b = b, a + b\n", + "\n", + "print() # line ending" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## `while` loop with `if-else`\n", + "\n", + "A **`while`** loop can have an optional **[if-else](https://github.com/milaan9/03_Python_Flow_Control/blob/main/002_Python_if_else_statement.ipynb)** block. We use **`if-else`** statement in the loop when conditional iteration is needed. i.e., If the condition is **`True`**, then the statements inside the if block will execute othwerwise, the else block will execute." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:26.656062Z", + "start_time": "2021-10-04T12:15:18.916304Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Please Enter Number 9\n", + "9 is a odd number\n", + "8 is a even number\n", + "7 is a odd number\n", + "6 is a even number\n", + "5 is a odd number\n", + "4 is a even number\n", + "3 is a odd number\n", + "2 is a even number\n", + "1 is a odd number\n" + ] + } + ], + "source": [ + "# Example 1: Print even and odd numbers between 1 to the entered number.\n", + "\n", + "n = int(input('Please Enter Number '))\n", + "while n > 0:\n", + " # check even and odd\n", + " if n % 2 == 0:\n", + " print(n, 'is a even number')\n", + " else:\n", + " print(n, 'is a odd number')\n", + " # decrease number by 1 in each iteration\n", + " n = n - 1" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:26.671686Z", + "start_time": "2021-10-04T12:15:26.660944Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "9\n", + "4\n", + "25\n", + "6\n", + "49\n", + "8\n", + "81\n" + ] + } + ], + "source": [ + "# Example 2: printing the square of odd numbers less than n. \n", + "\n", + "n =10\n", + "i = 1\n", + "while i < n:\n", + " #if (i % 2 == 0): (for even numbers)\n", + " if (i % 2 != 0):\n", + " print(i ** 2)\n", + " i = i + 1\n", + " else:\n", + " print(i)\n", + " i = i + 1" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:26.858208Z", + "start_time": "2021-10-04T12:15:26.674614Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The sum is 30\n" + ] + } + ], + "source": [ + "# Example 3: Add all even numbers from 1 to 10 using while loop\n", + "# 2+4+6+8+10\n", + "\n", + "# n = int(input(\"Please enter the maximum value: \"))\n", + "n = 10\n", + "\n", + "sum = 0\n", + "i = 1\n", + "\n", + "while i <= n:\n", + " if(i%2==0):\n", + " sum = sum + i\n", + "# sum += i\n", + " i = i+1\n", + " \n", + "# print the sum\n", + "print(\"The sum is\", sum)" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:26.980277Z", + "start_time": "2021-10-04T12:15:26.866021Z" + }, + "code_folding": [], + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "17\n", + "19\n", + "23\n", + "29\n", + "31\n", + "37\n", + "41\n", + "43\n", + "47\n", + "53\n", + "The total sum is 340\n" + ] + } + ], + "source": [ + "# Example 4: Write a code to add all the prime numbers between 17 to 53 using while loop\n", + "# 17, 19, 23, 29, 31, 37, 41, 43, 47, 53\n", + "\n", + "'''Method 1'''\n", + "\n", + "sum=0\n", + "for i in range(17,54):\n", + " k=2\n", + " if i>=2:\n", + " while i % k!=0:\n", + " k+=1\n", + " if i==k:\n", + " sum += i\n", + " print(i)\n", + "print(\"The total sum is\",sum)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## `while` loop with `else`\n", + "\n", + "A **`while`** loop can have an optional **`else`** block as well. The **`else`** part is executed if the condition in the **`while`** loop evaluates to **`False`**.\n", + "\n", + "The **`else`** will be skipped/ignored when:\n", + "\n", + "* **`while`** loop terminates abruptly\n", + "* The **[break statement](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)** is used to break the **`while`** loop" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:27.086726Z", + "start_time": "2021-10-04T12:15:26.983211Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "5\n" + ] + } + ], + "source": [ + "count = 0\n", + "while count < 5:\n", + " print(count)\n", + " count = count + 1\n", + "else:\n", + " print(count)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "The above loop condition will be false when count is 5 and the loop stops, and execution starts the else statement. As a result 5 will be printed." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:27.224424Z", + "start_time": "2021-10-04T12:15:27.091608Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "Done. 'while loop' executed normally\n" + ] + } + ], + "source": [ + "# Example 1: Use while loop to print numbers from 1 to 6\n", + "\n", + "i = 1\n", + "while i <= 6:\n", + " print(i)\n", + " i = i + 1\n", + "else:\n", + " print(\"Done. 'while loop' executed normally\")" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:27.378230Z", + "start_time": "2021-10-04T12:15:27.231258Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n" + ] + } + ], + "source": [ + "# Example 2: Else block with break statement in a while loop.\n", + "\n", + "i = 1\n", + "while i <= 6:\n", + " print(i)\n", + " if i == 3:\n", + " break\n", + " i = i + 1\n", + "else:\n", + " print(\"Done. `while loop` executed normally\")" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:27.503719Z", + "start_time": "2021-10-04T12:15:27.383113Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Inside while loop\n", + "Inside while loop\n", + "Inside while loop\n", + "Inside else\n" + ] + } + ], + "source": [ + "# Example 3:\n", + "'''Example to illustrate the use of else statement with the while loop'''\n", + "\n", + "counter = 0 # counter is my variable\n", + "\n", + "while counter < 3:\n", + " print(\"Inside while loop\")\n", + " counter = counter + 1 # increment the counter\n", + "else:\n", + " print(\"Inside else\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "Here, we use a **`counter`** variable to print the string **`Inside loop`** three times.\n", + "\n", + "On the fourth iteration, the condition in **`while`** becomes **`False`**. Hence, the **`else`** part is executed." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:34.325991Z", + "start_time": "2021-10-04T12:15:27.507624Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Enter any number between 100 and 600 555\n", + "Given Number is correct 555\n" + ] + } + ], + "source": [ + "# Example 4: we want a user to enter any number between 100 and 600\n", + "\n", + "number = int(input('Enter any number between 100 and 600 '))\n", + "# number greater than 100 and less than 600\n", + "while number < 100 or number > 600:\n", + " print('Incorrect number, Please enter correct number:')\n", + " number = int(input('Enter a Number between 100 and 600 '))\n", + "else:\n", + " print(\"Given Number is correct\", number)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using Control Statement in `while` loops in Python\n", + "\n", + "**[Control statements](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)** in Python like **`break`**, **`continue`**, etc can be used to control the execution flow of **`while`** loop in Python. Let us now understand how this can be done.\n", + "\n", + "It is used when you want to exit a loop or skip a part of the loop based on the given condition. It also knows as **transfer statements**." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### a) `break` in `while` loop\n", + "\n", + "Using the **`break`** statement, we can exit from the **`while`** loop even if the condition is **`True`**. \n", + "\n", + "If the **`break`** statement is used inside a nested loop (loop inside another loop), it will terminate the innermost loop. For example," + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:34.341618Z", + "start_time": "2021-10-04T12:15:34.327947Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "2\n" + ] + } + ], + "source": [ + "# Example 1:\n", + "\n", + "count = 0\n", + "while count < 5:\n", + " print(count)\n", + " count = count + 1\n", + " if count == 3:\n", + " break " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation**: \n", + "\n", + "Here, the **`while`** loop runs until the value of the variable **`i`** is less than 5. But because of the **`break`** statement, the loop gets terminated when the value of the variable **`i`** is 3 and it prints 0, 1, 2" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:34.485175Z", + "start_time": "2021-10-04T12:15:34.343572Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "60\n", + "HelloWorld\n", + "90.45\n" + ] + } + ], + "source": [ + "# Example 2:\n", + "\n", + "list = [60, \"HelloWorld\", 90.45, 50, 67.23, \"Python\"] # total 6 elements\n", + "i = 0\n", + "while(i < 6):\n", + " print(list[i])\n", + " i = i + 1\n", + " if(i == 3):\n", + " break" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation**: \n", + "\n", + "Here, the **`while`** loop runs until the value of the variable **`i`** is less than 6. But because of the **`break`** statement, the loop gets terminated when the value of the variable **`i`** is 3." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:34.639958Z", + "start_time": "2021-10-04T12:15:34.504703Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A l a n " + ] + } + ], + "source": [ + "# Example 3: Display each character from a string and if `a` character is number then stop the loop.\n", + "\n", + "name = 'Alan99White'\n", + "size = len(name)\n", + "i = 0\n", + "# iterate loop till the last character\n", + "while i < size:\n", + " # break loop if current character is number\n", + " if name[i].isdecimal():\n", + " break;\n", + " # print current character\n", + " print(name[i], end=' ')\n", + " i = i + 1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### b) `continue` in while loop\n", + "\n", + "The **`continue`** statement is used to stop/skip the block of code in the loop for the current iteration only and continue with the next iteration. \n", + "\n", + "For example, let's say you want to print all the odd numbers less than a particular value. Here is how you can do it using **`continue`** keyword in Python." + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:43.254714Z", + "start_time": "2021-10-04T12:15:34.653630Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "2\n" + ] + }, + { + "ename": "KeyboardInterrupt", + "evalue": "", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mKeyboardInterrupt\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[1;32mwhile\u001b[0m \u001b[0mcount\u001b[0m \u001b[1;33m<\u001b[0m \u001b[1;36m5\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mcount\u001b[0m \u001b[1;33m==\u001b[0m \u001b[1;36m3\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 6\u001b[1;33m \u001b[1;32mcontinue\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 7\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mcount\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mKeyboardInterrupt\u001b[0m: " + ] + } + ], + "source": [ + "# Example 1:\n", + "\n", + "count = 0\n", + "while count < 5:\n", + " if count == 3:\n", + " continue \n", + " else:\n", + " print(count)\n", + " count = count + 1 " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "The above **`while`** loop only prints 0, 1, 2 and 4 (skips 3)." + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:48.259605Z", + "start_time": "2021-10-04T12:15:48.244468Z" + }, + "code_folding": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "3\n", + "5\n", + "7\n", + "9\n" + ] + } + ], + "source": [ + "# Example 2: printing odd numbers less than `n`\n", + "\n", + "n=10\n", + "i = 1\n", + "while (i < n):\n", + " if (i % 2 == 0):\n", + " i = i + 1\n", + " continue # continue means skip the current loop\n", + " else:\n", + " print (i)\n", + " i = i + 1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "Here, the **`continue`** statement gets executed when the value of the variable is an even number. This simply means, whenever it is an even number, we simply skip all other statements and execute the next iteration." + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:49.635581Z", + "start_time": "2021-10-04T12:15:49.620932Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A l a n W h i t e " + ] + } + ], + "source": [ + "# Example 3: Write a while loop to display only alphabets from a string.\n", + "\n", + "name = 'Alan99White'\n", + "\n", + "size = len(name)\n", + "i = -1\n", + "# iterate loop till the last character\n", + "while i < size - 1:\n", + " i = i + 1\n", + " # skip while loop body if current character is not alphabet\n", + " if not name[i].isalpha():\n", + " continue\n", + " # print current character\n", + " print(name[i], end=' ')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### c) `pass` in `while` loop\n", + "\n", + "The **`pass`** statement is a null statement, i.e., nothing happens when the statement is executed. Primarily it is used in empty functions or classes. When the interpreter finds a pass statement in the program, it returns no operation." + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:50.622885Z", + "start_time": "2021-10-04T12:15:50.610197Z" + } + }, + "outputs": [], + "source": [ + "# Example 1:\n", + "\n", + "n = 4\n", + "while n > 0:\n", + " n = n - 1\n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Reverse `while` loop\n", + "\n", + "A reverse loop means an iterating loop in the backward direction. A simple example includes:\n", + "\n", + "* Display numbers from 10 to 1.\n", + "* Reverse a string or list" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:52.550625Z", + "start_time": "2021-10-04T12:15:52.539885Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10 9 8 7 6 5 4 3 2 1 0 " + ] + } + ], + "source": [ + "# Example 1: Reverse a while loop to display numbers from 10 to 1\n", + "\n", + "# reverse while loop\n", + "i = 10\n", + "while i >= 0:\n", + " print(i, end=' ')\n", + " i = i - 1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Nested `while` loops\n", + "\n", + "**Nested while loop** is a **`while`** loop inside another **`while`** a loop. \n", + "\n", + "In the nested **`while`** loop, the number of iterations will be equal to the number of iterations in the outer loop multiplied by the iterations in the inner loop. In each iteration of the outer loop inner loop execute all its iteration.\n", + "\n", + "**Syntax:**\n", + "\n", + "```python\n", + "while expression:\n", + " while expression:\n", + " statement(s)\n", + " statement(s)\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### `while` loop inside `while` loop" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Example: Nested `while` loop" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:53.847500Z", + "start_time": "2021-10-04T12:15:53.826996Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "12345678910\n", + "12345678910\n", + "12345678910\n" + ] + } + ], + "source": [ + "# Example: print the first 10 numbers on each line 5 times\n", + "\n", + "i = 1\n", + "while i <= 3:\n", + " j = 1\n", + " while j <= 10:\n", + " print(j, end='')\n", + " j = j + 1\n", + " i = i + 1\n", + " print()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Example: Nested `while` loop to print the pattern\n", + "\n", + "```python\n", + "*\n", + "* *\n", + "* * *\n", + "* * * *\n", + "* * * * *\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:54.568693Z", + "start_time": "2021-10-04T12:15:54.547213Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "* \n", + "* * \n", + "* * * \n", + "* * * * \n", + "* * * * * \n" + ] + } + ], + "source": [ + "# Example 1: Method 1\n", + "\n", + "i = 1\n", + "# outer while loop\n", + "# 5 rows in pattern\n", + "while i < 6:\n", + " j = 0\n", + " # nested while loop\n", + " while j < i:\n", + " print('*', end=' ')\n", + " j = j + 1\n", + " # end of nested while loop\n", + " # new line after each row\n", + " print('')\n", + " i = i + 1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### `for` loop inside `while` loop\n", + "\n", + "We can also use **[for loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/005_Python_for_Loop.ipynb)** inside a **`while`** loop as a nested loop. For example, " + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:55.309907Z", + "start_time": "2021-10-04T12:15:55.290378Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "* \n", + "* * \n", + "* * * \n", + "* * * * \n", + "* * * * * \n" + ] + } + ], + "source": [ + "# Example 1: Method 2\n", + "\n", + "i = 1\n", + "# outer while loop\n", + "while i < 6:\n", + " # nested for loop\n", + " for j in range(1, i + 1):\n", + " print(\"*\", end=\" \")\n", + " print('')\n", + " i = i + 1" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:55.725921Z", + "start_time": "2021-10-04T12:15:55.702486Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "17\n", + "19\n", + "23\n", + "29\n", + "31\n", + "37\n", + "41\n", + "43\n", + "47\n", + "53\n", + "The total sum is 340\n" + ] + } + ], + "source": [ + "# Example 2: Write a code to add all the prime numbers between 17 to 53 using while loop\n", + "# 17, 19, 23, 29, 31, 37, 41, 43, 47, 53\n", + "\n", + "'''Method 1'''\n", + "\n", + "n=17\n", + "sum=0\n", + "while n<=53:\n", + " for i in range(2,n):\n", + " if(n % i)== 0: \n", + " break\n", + " else:\n", + " i=i+1\n", + " else:\n", + " sum=sum+n\n", + " print(n)\n", + " n=n+1\n", + "print(\"The total sum is\",sum)" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:56.062835Z", + "start_time": "2021-10-04T12:15:56.043797Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Show Perfect number fom 1 to 100\n", + "Perfect number: 6\n", + "Perfect number: 28\n" + ] + } + ], + "source": [ + "# Example 3:\n", + "\n", + "print('Show Perfect number fom 1 to 100')\n", + "n = 2\n", + "\n", + "while n <= 100: # outer while loop\n", + " x_sum = 0 \n", + " for i in range(1, n): # inner for loop\n", + " if n % i == 0:\n", + " x_sum += i\n", + " if x_sum == n:\n", + " print('Perfect number:', n)\n", + " n += 1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Iterate String using `while` loop\n", + "\n", + "By looping through the **[string](https://github.com/milaan9/02_Python_Datatypes/blob/main/002_Python_String.ipynb)** using **`while`** loop, we can do lots of string operations. For example," + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:56.695654Z", + "start_time": "2021-10-04T12:15:56.675146Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A\n", + "l\n", + "a\n", + "n\n" + ] + } + ], + "source": [ + "# Example 1: while loop to iterate string letter by letter\n", + "\n", + "name = \"Alan\"\n", + "i = 0\n", + "res = len(name) - 1\n", + "while i <= res:\n", + " print(name[i])\n", + " i = i + 1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Iterate List using `while` loop\n", + "\n", + "**[Python list](https://github.com/milaan9/02_Python_Datatypes/blob/main/003_Python_List.ipynb)** is an ordered collection of items of different data types. It means Lists are ordered by index numbers starting from 0 to the total items-1. List items are enclosed in square **`[]`** brackets.\n", + "\n", + "Below are the few examples of Python list.\n", + "\n", + "```python\n", + ">>> numers = [1,2,4,6,7]\n", + ">>> players = [\"Messi\", \"Ronaldo\", \"Neymar\"]\n", + "```\n", + "Using a loop, we can perform various operations on the list. There are ways to iterate through elements in it. Here are some examples to help you understand better." + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:57.403172Z", + "start_time": "2021-10-04T12:15:57.389503Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n", + "6\n", + "9\n" + ] + } + ], + "source": [ + "# Example 1: Use while loop to iterate over a list.\n", + "\n", + "numbers = [1, 2, 3, 6, 9]\n", + "size = len(numbers)\n", + "i = 0\n", + "while i < size:\n", + " print(numbers[i])\n", + " i = i + 1" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:58.048679Z", + "start_time": "2021-10-04T12:15:58.029154Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "60\n", + "HelloWorld\n" + ] + } + ], + "source": [ + "# Example 2: printing the first two elements of a list\n", + "\n", + "list = [60, \"HelloWorld\", 90.96] # list with three elements\n", + "i = 0\n", + "while(i < 2):\n", + " print (list[i]) #printing the element in the index i\n", + " i = i + 1 " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + ">**Note**: When working with the **`while`** loop, it is important to declare the indexing variable **`i`** beforehand and to increment the indexing variable accordingly. Else it will result in an infinite loop." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Iterate Numbers using `while` loop\n", + "\n", + "Now, consider a program where you want to print out the squares of all the **[numbers](https://github.com/milaan9/02_Python_Datatypes/blob/main/001_Python_Numbers.ipynb)** less a particular number. Let's see how this works with a while statement." + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:59.143411Z", + "start_time": "2021-10-04T12:15:59.132670Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "4\n", + "9\n", + "16\n", + "25\n", + "36\n", + "49\n", + "64\n", + "81\n", + "100\n" + ] + } + ], + "source": [ + "# Example 1: printing the square of numbers less than `n`\n", + "\n", + "i = 1\n", + "while (i <= 10):\n", + " print (i ** 2) #printing the element in the index i\n", + " i = i + 1" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:59.452490Z", + "start_time": "2021-10-04T12:15:59.431010Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "8\n", + "27\n", + "64\n", + "125\n", + "216\n", + "343\n", + "512\n", + "729\n" + ] + } + ], + "source": [ + "# Example 2: Find the cube of number from 1 to 9.\n", + "\n", + "i = 1\n", + "while(i<10):\n", + " print(i*i*i)\n", + "# print(i**3)\n", + " i=i+1" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": { + "ExecuteTime": { + "end_time": "2021-10-04T12:15:59.835791Z", + "start_time": "2021-10-04T12:15:59.816265Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "4\n", + "Loop over\n" + ] + } + ], + "source": [ + "# Example 3:\n", + "\n", + "i = 1\n", + "while i < 3:\n", + " print(i ** 2)\n", + " i = i+1\n", + "print('Loop over')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## While loop in Python FAQs\n", + "\n", + "\n", + "1. A while loop in python is used for what type of iteration?\n", + "> A while loop is ideal for iteration when the number of iterations is not known. Also, it is ideal to use a while loop when you have a condition that needs to be satisfied.\n", + "\n", + "\n", + "2. Why does infinite while loop occur in Python?\n", + "> A loop becomes an infinite loop if the while condition never becomes FALSE. Such a loop that never terminates is called an infinite loop.\n", + "\n", + "\n", + "3. Is there a do...while loop in Python?\n", + ">No. There is no do while loop in Python.\n", + "\n", + "\n", + "4. How do you break a while loop in Python?\n", + ">Usually, the control shifts out of the while loop when the while condition is no False. Or you can use various control statements like break, continue, etc to break out of the while loop or break of the particular iteration of the while loop.\n", + "\n", + "\n", + "5. How to write an empty while function in Python?\n", + ">You can write an empty while function in Python using the pass statements. Here is how you can write it.\n", + "\n", + "```python\n", + "#empty while statement in python\n", + ">>> i = 0\n", + ">>> while (i < 10) :\n", + ">>> pass\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "hide_input": false, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.8" + }, + "toc": { + "base_numbering": 1, + "nav_menu": {}, + "number_sections": true, + "sideBar": true, + "skip_h1_title": false, + "title_cell": "Table of Contents", + "title_sidebar": "Contents", + "toc_cell": false, + "toc_position": {}, + "toc_section_display": true, + "toc_window_display": false + }, + "varInspector": { + "cols": { + "lenName": 16, + "lenType": 16, + "lenVar": 40 + }, + "kernels_config": { + "python": { + "delete_cmd_postfix": "", + "delete_cmd_prefix": "del ", + "library": "var_list.py", + "varRefreshCmd": "print(var_dic_list())" + }, + "r": { + "delete_cmd_postfix": ") ", + "delete_cmd_prefix": "rm(", + "library": "var_list.r", + "varRefreshCmd": "cat(var_dic_list()) " + } + }, + "types_to_exclude": [ + "module", + "function", + "builtin_function_or_method", + "instance", + "_Feature" + ], + "window_display": false + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/007_Python_break_continue_pass_statements.ipynb b/007_Python_break_continue_pass_statements.ipynb new file mode 100644 index 0000000..5487d06 --- /dev/null +++ b/007_Python_break_continue_pass_statements.ipynb @@ -0,0 +1,1308 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "All the IPython Notebooks in **Python Flow Control Statements** lecture series by Dr. Milaan Parmar are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)**\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Control Statements in Python\n", + "\n", + "As you may know, loops in Python are used to iterate repeatedly over a block of code. But at times, you might want to **shift the control once a particular condition is satisfied**. This is where control statements in Python come into the picture.\n", + "\n", + "Control statements in python are **used to control the flow of execution of the program based on the specified conditions**. Python supports **3 types of control statements**:\n", + "\n", + "| | Statement | Description |\n", + "|:----|:----| :--- |\n", + "|1| **`break`** | Terminate the current loop. Use the **`break`** statement to come out of the loop instantly. |\n", + "|2| **`continue`** | Skip the current iteration of a loop and move to the next iteration |\n", + "|3| **`pass`** | Do nothing. Ignore the condition in which it occurred and proceed to run the program as usual |\n", + "\n", + "Loops iterate over a block of code until the test expression is **`False`**, but sometimes we wish to terminate the current iteration or even the whole loop without checking test expression.\n", + "\n", + "The **`break`** and **`continue`** statements are part of a control flow statements that helps you to understand the basics of Python.\n", + "\n", + "
\n", + "\n", + "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 1. Python `break` statement\n", + "\n", + "In Python, the **`break`** statement provides you with the opportunity to **exit out** of a loop when an external condition is **triggered**, and the program control transfer to the next statement following the loop.\n", + "\n", + "If the **`break`** statement is inside a nested loop (loop inside another loop), the **`break`** statement will terminate the innermost loop.\n", + "\n", + "You’ll put the **`break`** statement within the block of code under your loop statement, usually after a conditional **[if statement](https://github.com/milaan9/03_Python_Flow_Control/blob/main/001_Python_if_statement.ipynb)**. This statement can only be used in **[for loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/005_Python_for_Loop.ipynb)** and **[while loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/006_Python_while_Loop.ipynb)**.\n", + "\n", + "
\n", + "\n", + "
\n", + "\n", + "The working of **`break`** statement in **`for`** loop and **`while`** loop is shown below.\n", + "\n", + "
\n", + "\n", + "
" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:08:12.834872Z", + "start_time": "2021-06-12T16:08:12.824130Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "current number 10\n", + "current number 30\n" + ] + } + ], + "source": [ + "# Example 1:\n", + "\n", + "numbers = [10, 30, 120, 330]\n", + "for i in numbers:\n", + " if i > 100:\n", + " break\n", + " print('current number', i)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:08:13.037991Z", + "start_time": "2021-06-12T16:08:13.020416Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Number is 1\n", + "Number is 2\n", + "Number is 3\n", + "Number is 4\n", + "Out of loop\n" + ] + } + ], + "source": [ + "# Example 2: Let’s look at an example that uses the break statement in a `for` loop\n", + "\n", + "number = 0\n", + "for number in range(10):\n", + " number = number + 1\n", + " if number == 5:\n", + " break # break here\n", + " print('Number is ' + str(number))\n", + "print('Out of loop')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "1. In this small program, the variable number is initialized at **`0`**. Then a **`for`** statement constructs the loop as long as the variable number is **less than 10**.\n", + "\n", + "2. Within the **`for`** loop, the number increases incrementally by **`1`** with each pass because of the line **number = number + 1**.\n", + "\n", + "3. Then, there is an **`if`** statement that presents the condition that if the variable number is **equivalent** to the integer **`5`**, then the loop will break.\n", + "\n", + "4. Within the loop is also a **[print()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/051_Python_print%28%29.ipynb)** statement that will execute with each iteration of the **`for`** loop until the loop breaks, since it is after the **`break`** statement.\n", + "\n", + "5. To see when we are out of the loop, we have included a final **`print()`** statement outside of the **`for`** loop.\n", + "\n", + "This shows that once the integer number is evaluated as equivalent to **`5`**, the loop breaks, as the program is told to do so with the **`break`** statement." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Nested `break` loops" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 1. `break` Statement in Nested Loop\n", + "\n", + "To terminate the nested loop, use a **`break`** statement inside the inner loop. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:08:13.736228Z", + "start_time": "2021-06-12T16:08:13.719632Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0...1...2...3...4...5...6...7...8...9...10...completed.\n" + ] + } + ], + "source": [ + "# Example 1:\n", + "\n", + "for i in range(100):\n", + " print(i,end=\"...\")\n", + " if i>=10:\n", + " break\n", + "print(\"completed.\")" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:08:13.954002Z", + "start_time": "2021-06-12T16:08:13.938378Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "s\n", + "t\n", + "r\n", + "The end\n" + ] + } + ], + "source": [ + "# Example 2: Use of break statement inside the loop\n", + "\n", + "for val in \"string\":\n", + " if val == \"i\":\n", + " break\n", + " print(val)\n", + "print(\"The end\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "In this program, we iterate through the \"**`string`**\" sequence. We check if the letter is **`i`**, upon which we break from the loop. Hence, we see in our output that all the letters up till **`i`** gets printed. After that, the loop terminates." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Print the letters in \"HELLOWORLD\" one by one untill the letter R is reached using break statement in Python." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:08:14.842176Z", + "start_time": "2021-06-12T16:08:14.824110Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "H\n", + "E\n", + "L\n", + "L\n", + "O\n", + "W\n", + "O\n", + "untill letter R printed\n" + ] + } + ], + "source": [ + "# Example 3: \n", + "\n", + "for letter in \"HELLOWORLD\": # letter is a variable which could have been with any name. each iteration the letter is advanced in the string \"FACEPREP\" and stored in variable letter.\n", + " if letter == \"R\": #check for condition\n", + " break # if condition true, then break out of the loop and print the final print statement.\n", + " print(letter) # if condition false, then print that letter.\n", + "print('untill letter R printed') #once the for loop is terminated, print this. \n", + "\n", + "# Note: observe the indentations carefully" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:08:22.314280Z", + "start_time": "2021-06-12T16:08:15.161023Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Enter a word: Happy\n", + "A not found\n" + ] + } + ], + "source": [ + "# Example 4: program to check if letter 'A' is present in the input\n", + "\n", + "a = input (\"Enter a word: \")\n", + "for i in a:\n", + " if (i == 'A'):\n", + " print (\"A is found\")\n", + " break \n", + "else:\n", + " print (\"A not found\")\n", + " \n", + "# Note: Python is case-sensitive language." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:08:22.376783Z", + "start_time": "2021-06-12T16:08:22.364087Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A l a n 9 9 " + ] + } + ], + "source": [ + "# Example 5: bested `while` loop with `break`\n", + "\n", + "name = 'Alan99 White'\n", + "\n", + "size = len(name)\n", + "i = 0\n", + "# iterate loop till the last character\n", + "while i < size:\n", + " # break loop if current character is space\n", + " if name[i].isspace():\n", + " break\n", + " # print current character\n", + " print(name[i], end=' ')\n", + " i = i + 1" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:08:27.087188Z", + "start_time": "2021-06-12T16:08:27.056921Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Multiplication table of 1\n", + "1 2 3 4 5 6 7 8 9 10 \n", + "Multiplication table of 2\n", + "2 4 6 8 10 12 14 16 18 20 \n", + "Multiplication table of 3\n", + "3 6 9 12 15 18 21 24 27 30 \n", + "Multiplication table of 4\n", + "4 8 12 16 20 24 28 32 36 40 \n", + "Multiplication table of 5\n", + "5 10 15 20 25 30 35 40 45 50 \n", + "Multiplication table of 6\n", + "6 12 18 24 30 \n", + "Multiplication table of 7\n", + "7 14 21 28 35 \n", + "Multiplication table of 8\n", + "8 16 24 32 40 \n", + "Multiplication table of 9\n", + "9 18 27 36 45 \n", + "Multiplication table of 10\n", + "10 20 30 40 50 \n" + ] + } + ], + "source": [ + "# Example 6:\n", + "\n", + "for i in range(1, 11):\n", + " print('Multiplication table of', i)\n", + " for j in range(1, 11):\n", + " # condition to break inner loop\n", + " if i > 5 and j > 5:\n", + " break\n", + " print(i * j, end=' ')\n", + " print('')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "We have two loops, the outer loop, and the inner loop. The outer for loop iterates the first 10 numbers using the **[range()](https://github.com/milaan9/04_Python_Functions/blob/main/002_Python_Functions_Built_in/053_Python_range%28%29.ipynb)** function, and the internal loop prints the multiplication table of each number.\n", + "\n", + "But if the current number of both the outer loop and the inner loop is greater than 5 then terminate the inner loop using the **`break`** statement." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 2. `break` Statement in Outer Loop\n", + "\n", + "To terminate the outside loop, use a **`break`** statement inside the outer loop. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:08:29.111587Z", + "start_time": "2021-06-12T16:08:29.095964Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Multiplication table of 1\n", + "1 2 3 4 5 6 7 8 9 10 \n", + "Multiplication table of 2\n", + "2 4 6 8 10 12 14 16 18 20 \n", + "Multiplication table of 3\n", + "3 6 9 12 15 18 21 24 27 30 \n", + "Multiplication table of 4\n", + "4 8 12 16 20 24 28 32 36 40 \n", + "Multiplication table of 5\n", + "5 10 15 20 25 30 35 40 45 50 \n" + ] + } + ], + "source": [ + "# Example 1: Break nested loop\n", + "\n", + "for i in range(1, 11):\n", + " # condition to break outer loop\n", + " if i > 5:\n", + " break\n", + " print('Multiplication table of', i)\n", + " for j in range(1, 11):\n", + " print(i * j, end=' ')\n", + " print('')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "We have two loops, the outer loop, and the inner loop. The outer loop iterates the first 10 numbers, and the internal loop prints the multiplication table of each number.\n", + "\n", + "But if the current number of the outer loop is greater than 5 then terminate the outer loop using the **`break`** statement." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:08:30.062754Z", + "start_time": "2021-06-12T16:08:30.048105Z" + }, + "scrolled": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Current Number is: 3\n", + "Square of a current number is: 9\n", + "Current Number is: 6\n", + "Square of a current number is: 36\n", + "Current Number is: 12\n", + "Current Number is: 9\n", + "Square of a current number is: 81\n" + ] + } + ], + "source": [ + "# Example 2:\n", + "\n", + "numbers = [3, 6, 12, 9]\n", + "for i in numbers:\n", + " print('Current Number is:', i)\n", + " # skip below statement if number is greater than 10\n", + " if i > 10:\n", + " continue\n", + " square = i * i\n", + " print('Square of a current number is:', square)" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:08:30.717046Z", + "start_time": "2021-06-12T16:08:30.705325Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "3\n", + "5\n", + "End of Loop\n" + ] + } + ], + "source": [ + "# Example 3: Python Continue Statement Example:\n", + "\n", + "a=0\n", + "\n", + "while a<=5:\n", + " a=a+1\n", + " if a%2==0: \n", + " continue\n", + " print (a)\n", + "print (\"End of Loop\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "You can use the **`continue`** statement to avoid deeply nested conditional code, or to optimize a loop by eliminating frequently occurring cases that you would like to reject.\n", + "\n", + "The **`continue`** statement causes a program to skip certain factors that come up within a loop, but then continue through the rest of the loop." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:08:32.292716Z", + "start_time": "2021-06-12T16:08:32.273183Z" + }, + "scrolled": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "s\n", + "t\n", + "r\n", + "n\n", + "g\n", + "The end\n" + ] + } + ], + "source": [ + "# Example 4: Program to show the use of continue statement inside loops\n", + "\n", + "for val in \"string\":\n", + " if val == \"i\":\n", + " continue\n", + " print(val)\n", + "\n", + "print(\"The end\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation**:\n", + "\n", + "This program is same as the above example except the **`break`** statement has been replaced with **`continue`**.\n", + "\n", + "We continue with the loop, if the string is **`i`**, not executing the rest of the block. Hence, we see in our output that all the letters except **`i`** gets printed." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:08:33.883035Z", + "start_time": "2021-06-12T16:08:33.872290Z" + }, + "scrolled": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Processed 0\n", + "Processed 1\n", + "Processed 2\n", + "Processed 3\n", + "Processed 4\n", + "Ignored 5\n", + "Ignored 6\n", + "Ignored 7\n", + "Ignored 8\n", + "Ignored 9\n" + ] + } + ], + "source": [ + "# Example 5:\n", + "\n", + "for i in range(10):\n", + " if i>4:\n", + " print(\"Ignored\",i)\n", + " continue\n", + " # this statement is not reach if i > 4\n", + " print(\"Processed\",i)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Write a program to skip all \"O\"s in a given string \"HELLOWORLD\"" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:08:34.880584Z", + "start_time": "2021-06-12T16:08:34.863981Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "H\n", + "e\n", + "l\n", + "l\n", + "o\n", + "W\n", + "o\n", + "r\n", + "l\n", + "d\n", + "The End\n" + ] + } + ], + "source": [ + "# Example 6:\n", + "\n", + "for letters in \"HelloWorld\": # for every letter in FACEPREP\n", + " if letters == \"O\": # if letter is E, then skip printing the letter and go to the next iteration with the next alphabet\n", + " continue # Remember that loop is not terminated like break statement.\n", + " print(letters)\n", + "print(\"The End\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 2. Python `continue` statement\n", + "\n", + "In Python, the **`continue`** statement is a **jump statement** which is used to skip execution of current iteration. After **skipping**, loop **`continue`** with next iteration. We can use **`continue`** statement **only** with **[for loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/005_Python_for_Loop.ipynb)** as well as **[while loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/006_Python_while_Loop.ipynb)** in Python. It is typically **only** used within an **[if statement](https://github.com/milaan9/03_Python_Flow_Control/blob/main/001_Python_if_statement.ipynb)** (otherwise the remainder of the loop would never be executed).\n", + "\n", + "
\n", + "\n", + "
\n", + "\n", + "The working of **`continue`** statement in **`for`** loop and **`while`** loop is shown below.\n", + "\n", + "
\n", + "\n", + "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## `continue` statement in `while` loop\n", + "\n", + "We can also use the **`continue`** statement inside a **`while`** loop. For example:\n", + "\n", + "Write a **[while loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/006_Python_while_Loop.ipynb)** to display each character from a string and if a character is a space, then don’t display it and move to the next character.\n", + "\n", + "Use the if condition with the **`continue`** statement to jump to the next iteration. If the current character is space, then the condition evaluates to true, then the **`continue`** statement will execute, and the loop will move to the next iteration by skipping the remeaning body." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:08:38.606624Z", + "start_time": "2021-06-12T16:08:38.592955Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A r t h u r " + ] + } + ], + "source": [ + "# Example 1: use the `continue` statement inside a `while` loop\n", + "\n", + "name = 'Art hu r'\n", + "\n", + "size = len(name)\n", + "i = -1\n", + "# iterate loop till the last character\n", + "while i < size - 1:\n", + " i = i + 1\n", + " # skip loop body if current character is space\n", + " if name[i].isspace():\n", + " continue\n", + " # print current character\n", + " print(name[i], end=' ')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## `continue` statement with `else` statements\n", + "\n", + "Sometimes we want to know if a loop exited 'normally' or via a **`break`** statement. This can be achieved with an **`else:`** statement in a loop which only executes if there was no **`break`** statement." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:08:51.357492Z", + "start_time": "2021-06-12T16:08:39.913255Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Enter a word: Honey is sweet\n" + ] + } + ], + "source": [ + "# Example 1: program to check if letter 'A' is present in the input\n", + "\n", + "a = input (\"Enter a word: \")\n", + "for i in a:\n", + " if(i != 'A'): \n", + " continue \n", + " else:\n", + " print(\"A is found\")\n", + " break\n", + " print(\"A is not found\")\n", + " \n", + "# Enter a word: Honey is sweet" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:09:00.030274Z", + "start_time": "2021-06-12T16:08:53.753959Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Enter a word: Honey is sweet\n", + "A is not found\n" + ] + } + ], + "source": [ + "# Example 1 :without using continue\n", + "\n", + "a = input (\"Enter a word: \")\n", + "for i in a:\n", + " if (i == 'A'):\n", + " print(\"A is found\")\n", + " break\n", + "else:\n", + " print (\"A is not found\")\n", + " \n", + "# Enter a word: Honey is sweet" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:09:06.199166Z", + "start_time": "2021-06-12T16:09:06.188425Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "count = 1\n", + "count = 5\n", + "count = 9\n", + "Normal exit with 12\n" + ] + } + ], + "source": [ + "# Example 2:\n", + "\n", + "count = 0\n", + "while count < 10:\n", + " count += 1\n", + " if count % 2 == 0: # even number\n", + " count += 2\n", + " continue\n", + " elif 5 < count < 9:\n", + " break # abnormal exit if we get here!\n", + " print(\"count =\",count)\n", + "else: # while-else\n", + " print(\"Normal exit with\",count)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Nested `continue` loops" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 1. `continue` Statement in Nested Loop\n", + "\n", + "To skip the current iteration of the nested loop, use the **`continue`** statement inside the body of the inner loop. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:09:08.793873Z", + "start_time": "2021-06-12T16:09:08.770437Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Multiplication table of 1\n", + "1 2 3 4 6 7 8 9 10 \n", + "Multiplication table of 2\n", + "2 4 6 8 12 14 16 18 20 \n", + "Multiplication table of 3\n", + "3 6 9 12 18 21 24 27 30 \n", + "Multiplication table of 4\n", + "4 8 12 16 24 28 32 36 40 \n", + "Multiplication table of 5\n", + "5 10 15 20 30 35 40 45 50 \n", + "Multiplication table of 6\n", + "6 12 18 24 36 42 48 54 60 \n", + "Multiplication table of 7\n", + "7 14 21 28 42 49 56 63 70 \n", + "Multiplication table of 8\n", + "8 16 24 32 48 56 64 72 80 \n", + "Multiplication table of 9\n", + "9 18 27 36 54 63 72 81 90 \n", + "Multiplication table of 10\n", + "10 20 30 40 60 70 80 90 100 \n" + ] + } + ], + "source": [ + "# Example 1: `continue` statement in nested loop\n", + "\n", + "for i in range(1, 11):\n", + " print('Multiplication table of', i)\n", + " for j in range(1, 11):\n", + " # condition to skip current iteration\n", + " if j == 5:\n", + " continue\n", + " print(i * j, end=' ')\n", + " print('')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "We have the outer loop and the inner loop. The outer loop iterates the first 10 numbers, and the internal loop prints the multiplication table of each number.\n", + "\n", + "But if the current number of the inner loop is equal to 5, then skip the current iteration and move to the next iteration of the inner loop using the **`continue`** statement." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 2. `continue` Statement in Outer Loop\n", + "\n", + "To skip the current iteration of an outside loop, use the **`continue`** statement inside the outer loop. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:09:11.154202Z", + "start_time": "2021-06-12T16:09:11.131744Z" + }, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Multiplication table of 1\n", + "1 2 3 4 5 6 7 8 9 10 \n", + "Multiplication table of 3\n", + "3 6 9 12 15 18 21 24 27 30 \n", + "Multiplication table of 5\n", + "5 10 15 20 25 30 35 40 45 50 \n", + "Multiplication table of 7\n", + "7 14 21 28 35 42 49 56 63 70 \n", + "Multiplication table of 9\n", + "9 18 27 36 45 54 63 72 81 90 \n" + ] + } + ], + "source": [ + "# Example 1: `continue` statement in outer loop\n", + "\n", + "for i in range(1, 11):\n", + " # condition to skip iteration\n", + " # Don't print multiplication table of even numbers\n", + " if i % 2 == 0:\n", + " continue\n", + " print('Multiplication table of', i)\n", + " for j in range(1, 11):\n", + " print(i * j, end=' ')\n", + " print('')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation:**\n", + "\n", + "The outer loop iterates the first 10 numbers, and the internal loop prints the multiplication table of each number.\n", + "\n", + "But if the current number of the outer loop is even, then skip the current iteration of the outer loop and move to the next iteration.\n", + "\n", + ">**Note:** If we skip the current iteration of an outer loop, the inner loop will not be executed for that iteration because the inner loop is part of the body of an outer loop." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Catching exceptions with `continue` statement\n", + "\n", + "Sometimes it is desirable to deal with errors without stopping the whole program. This can be achieved using a **try** statement. Appart from dealing with with system errors, it also alows aborting from somewhere deep down in nested execution. It is possible to attach multiple error handlers depending on the type of the exception\n", + "\n", + "```python\n", + "try:\n", + " code\n", + "except as :\n", + " # deal with error of this type\n", + "except:\n", + " # deal with any error\n", + "finally:\n", + " # execute irrespective of whether an exception occured or not\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:09:14.039436Z", + "start_time": "2021-06-12T16:09:14.025766Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Looping\n", + "Looping\n", + "Looping\n", + "Looping\n", + "Caught exception: abort\n", + "All done\n" + ] + } + ], + "source": [ + "try:\n", + " count=0\n", + " while True:\n", + " while True:\n", + " while True:\n", + " print(\"Looping\")\n", + " count = count + 1\n", + " if count > 3:\n", + " raise Exception(\"abort\") # exit every loop or function\n", + " if count > 4:\n", + " raise StopIteration(\"I'm bored\") # built in exception type\n", + "except StopIteration as e:\n", + " print(\"Stopped iteration:\",e)\n", + "except Exception as e: # this is where we go when an exception is raised\n", + " print(\"Caught exception:\",e)\n", + "finally:\n", + " print(\"All done\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This can also be useful to handle unexpected system errors more gracefully:" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:09:14.897340Z", + "start_time": "2021-06-12T16:09:14.890500Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Cannot calculate inverse because: float division by zero\n" + ] + } + ], + "source": [ + "try:\n", + " for i in [2,1.5,0.0,3]:\n", + " inverse = 1.0/i\n", + "except Exception as e: # no matter what exception\n", + " print(\"Cannot calculate inverse because:\", e)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 3. Python `pass` statement\n", + "\n", + "In Python, **`pass`** keyword is used to execute **nothing**; it means, when we don't want to execute code, the pass can be used to execute empty. It is same as the name refers to. It just makes the control to pass by without executing any code. If we want to bypass any code pass statement can be used.\n", + "\n", + "It is used as a placeholder for future implementation of functions, loops, etc.\n", + "\n", + "Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They cannot have an empty body. The interpreter would give an error. So, we use the **`pass`** statement to construct a body that does nothing.\n", + "\n", + "### Example:\n", + "\n", + "```python\n", + "'''pass is just a placeholder for\n", + "functionality to be added later.'''\n", + ">>> sequence = {'p', 'a', 's', 's'}\n", + ">>> for val in sequence:\n", + ">>> pass\n", + "```\n", + "\n", + "We can do the same thing in an empty **function** or **class** as well.\n", + "\n", + "```python\n", + ">>> def function(args):\n", + ">>> pass\n", + "```\n", + "or\n", + "```python\n", + ">>> class Example:\n", + ">>> pass\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:09:17.500828Z", + "start_time": "2021-06-12T16:09:17.481302Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['January', 'June', 'March', 'April']\n" + ] + } + ], + "source": [ + "# Example 1:\n", + "\n", + "months = ['January', 'June', 'March', 'April']\n", + "for mon in months:\n", + " pass\n", + "print(months)" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "ExecuteTime": { + "end_time": "2021-06-12T16:09:18.217623Z", + "start_time": "2021-06-12T16:09:18.195650Z" + }, + "scrolled": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Number is 1\n", + "Number is 2\n", + "Number is 3\n", + "Number is 4\n", + "Number is 5\n", + "Number is 6\n", + "Number is 7\n", + "Number is 8\n", + "Number is 9\n", + "Number is 10\n", + "Out of loop\n" + ] + } + ], + "source": [ + "# Example 2: Python Pass Statement\n", + "\n", + "number = 0\n", + "\n", + "for number in range(10):\n", + " number = number + 1\n", + " if number == 5:\n", + " pass # pass here\n", + " print('Number is ' + str(number))\n", + "print('Out of loop')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Explanation**:\n", + "\n", + "By using the **`pass`** statement in this program, we notice that the program runs exactly as it would if there were no conditional statement in the program. The **`pass`** statement tells the program to **disregard that condition** and **continue to run** the program as usual." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Control Statements in Python FAQs\n", + "\n", + "1. How many control statements are present in Python?\n", + "> In Python, there are 3 types of control statements. Namely, break, continue and pass statements.\n", + "\n", + "2. How to break from a loop in Python?\n", + ">The keyword break is used to break or terminate from the current loop. The control shifts to the next statement outside the loop.\n", + "\n", + "3. What is the difference between break and continue statements in Python?\n", + ">Break statement exits out of the loop, but the continue statement shifts the control to the next iteration and doesn’t exit out of the loop.\n", + "\n", + "4. Can we use continue in if statement in Python?\n", + ">Yes. Continue statements can be used within an if statement.\n", + "\n", + "5. What is the use of pass keyword in Python?\n", + ">Pass keyword helps in avoiding errors that result due to an empty loop." + ] + } + ], + "metadata": { + "hide_input": false, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.8" + }, + "toc": { + "base_numbering": 1, + "nav_menu": {}, + "number_sections": true, + "sideBar": true, + "skip_h1_title": false, + "title_cell": "Table of Contents", + "title_sidebar": "Contents", + "toc_cell": false, + "toc_position": {}, + "toc_section_display": true, + "toc_window_display": false + }, + "varInspector": { + "cols": { + "lenName": 16, + "lenType": 16, + "lenVar": 40 + }, + "kernels_config": { + "python": { + "delete_cmd_postfix": "", + "delete_cmd_prefix": "del ", + "library": "var_list.py", + "varRefreshCmd": "print(var_dic_list())" + }, + "r": { + "delete_cmd_postfix": ") ", + "delete_cmd_prefix": "rm(", + "library": "var_list.r", + "varRefreshCmd": "cat(var_dic_list()) " + } + }, + "types_to_exclude": [ + "module", + "function", + "builtin_function_or_method", + "instance", + "_Feature" + ], + "window_display": false + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} From 3bc63ad8ec8929709defdfee800a3a439a3acb25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Fri, 5 Nov 2021 23:10:13 +0530 Subject: [PATCH 20/23] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bc10040..1b2cfbb 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ These are online **read-only** versions. However you can **`Run ▶`** the code You can Star Badge and Fork Badge Starring and Forking is free for you, but it tells me and other people that it was helpful and you like this tutorial. -Go [**`here`**](https://github.com/milaan9/03_Python_Flow_Control) if you aren't here already and click ➞ **`✰ Star`** and **`ⵖ Fork`** button in the top right corner. You will be asked to create a GitHub account if you don't already have one. +Go [**`here`**](https://github.com/milaan9/03_Python_Flow_Control) if you aren't here already and click ➞ **`✰ Star`** and **`ⵖ Fork`** button in the top right corner. You'll be asked to create a GitHub account if you don't already have one. --- From e98569dc983dccbe290ee24e02c3fb28a773088f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Sun, 15 May 2022 15:14:24 +0800 Subject: [PATCH 21/23] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1b2cfbb..5ea7d45 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@

Last Commit +Created Last Commit From f32a787916dd408c49df9a70cc81f82026e999e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BC=D0=B0=D1=80=20/=20=5F=E7=B1=B3?= =?UTF-8?q?=E5=85=B0=20=E5=B8=95=E5=B0=94=E9=A9=AC?= Date: Sun, 12 Jun 2022 23:57:10 +0800 Subject: [PATCH 22/23] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5ea7d45..1868d2a 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ Go [**`here`**](https://github.com/milaan9/03_Python_Flow_Control) if you aren't --- -### How can I read this tutorial without an Internet connection? GIF +### How can I read this tutorial without an Internet connection? GIF 1. Go [**`here`**](https://github.com/milaan9/03_Python_Flow_Control) and click the big green ➞ **`Code`** button in the top right of the page, then click ➞ [**`Download ZIP`**](https://github.com/milaan9/03_Python_Flow_Control/archive/refs/heads/main.zip). From c7b66b2987ac70f94b20f736f0ce9d044eb8248a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milaan=20Parmar=20/=20=20=D0=9C=D0=B8=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=20/=20=E7=B1=B3=E5=85=B0?= Date: Fri, 9 Dec 2022 15:02:48 -0600 Subject: [PATCH 23/23] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1868d2a..1796d0a 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@

Last Commit -Created -Last Commit + + Stars Badge