Select Page
I 100 libri da non perdere

In this lesson we will learn how to use nested loops in Python, that is, iterations that run inside other iterations.

So, let’s take some examples to understand how they work.

## Example on nested loops in Python

Produce a rectangle of asterisks of base 4 asterisks and height 3.

The output must therefore be this:

``````* * * *
* * * *
* * * *``````

To accomplish this we use two loops, one external and one internal.

Two nested for loops require different counters, we denote with i the counter of the first loop, while with j the counter of the second loop.

So, in this case, the external cycle will be repeated three times, while the internal one four times for each external cycle.

Here is the complete code:

``````
for i in range(3):
for j in range(4):
print('*', end=' ')
print()
``````

We use the keyword end inside the print to insert the asterisks on the same line and therefore avoid going to the head.

While the last print() is simply used to wrap, after printing each line.

So let’s explain step by step what happens.

1. First iteration of the outer loop: i = 0
• First iteration of the inner loop: j = 0 prints the asterisk followed by the empty space.
• Second iteration of the inner loop: j = 1 prints another asterisk followed by white space.
• Third iteration of the inner loop: j = 2 prints an asterisk followed by white space.
• Fourth iteration of the inner loop: j = 3 prints an asterisk followed by white space.

2. Second iteration of the outer loop: i = 1

We proceed similarly to what was said before.

To test what explained, try replacing the asterisks for the values of i and j, inserting the code indicated below instead of print (‘*’, end = ”):

``````
print('i:',i,'j:',j, end=' ')
``````

The same rectangle could be made with a single for loop, simply by multiplying the asterisk (*) character 4 times for each line.

``````
for i in range(3):
print('* '*4)
``````

## Second example on nested loops in Python

We vary the previous exercise by now producing a rectangle with the numbers from 1 to 4.

That is, the output must be this:

1 2 3 4 1 2 3 4 1 2 3 4

We only have to change the inner loop, setting the values (1,5) in the range.

After, at each iteration of the internal cycle we print the index j.

So here’s the code:

``````
for i in range(3):
for j in range(1,5):
print(j, end=' ')
print()
``````

## Third example on nested loops in Python

Print the numbers in descending order, then we run the previous example in order to have the following output:

4 3 2 1 4 3 2 1 4 3 2 1

To print the numbers in descending order we can change the range so that j varies from 4 to 1 with steps of -1.

Here is the complete code:

``````
for i in range(3):
for j in range(4,0,-1):
print(j, end=' ')
print()
``````

## Fourth example

We now want to create another example using two nested for loops, like the example below:

1234567 123456 12345 1234 123 12 1

Just print j and from time to time decrease the number of lines by 1:

``````
n=7
for i in range(n):
for j in range(1, n+1-i):
print(j, end='')
print()
``````

## Fifth example on nested loops in Python

Let’s take another example:

7654321 654321 54321 4321 321 21 1
``````
n=7
for i in range(n):
for j in range(n-i,0, -1):
print(j, end='')
print()
``````

## Sixth example

Let’s take another example on nested loops:

1 21 321 4321 54321 654321 7654321
``````
n=7
for i in range(1,n+1):
for j in range(i,0, -1):
print(j, end='')
print()
``````

## Seventh example on nested loops in Python

Let’s make a figure like this:

* ** *** **** ***** **** *** ** *

Let’s analyze some solutions. First solution:

``````
n=5
for i in range(1,n*2):
if i<=n:
for j in range(i,0, -1):
print('*', end='')
else:
for j in range(1,n*2+1-i):
print('*', end='')

print()
``````

The outer loop will print the nine lines. In fact i varies from 1 to 9.

Within the cycle, if i <= 5, we perform another for cycle which will print 1 asterisk the first time, then 2, etc … up to 5.

In fact, at the first iteration i is equal to 1, at the next it is 2 and so on up to i = 5.

``````
for j in range(i,0, -1):
print('*', end='')
``````

When i is equal to 5, what is written in the else will be done and then the other for loop which will print n * 2-i asterisks. The first time n * 2-i = 10-6 that is 4 asterisks, the second time n * 2-i = 10-7 that is 3 and so on.

Second simplified solution with two for loops:

``````
n=5
for i in range(1,n*2):
for j in range(1,n+1):
if i<=n and j<=i:
print('*', end='')
elif i>n and j``````
``` Third solution with logical operators: n=5 for i in range(1,n*2): for j in range(1,n+1): if i<=n and j<=i or i>n and j Prev lesson: Python examples Next lesson: Rectangles of asterisks with for loops Some useful links Python tutorial Python Compiler Install Python Variables Assignment operators How to find the maximum of N numbers How to use the math module Bubble sort Matplotlib Plot jQuery(document).ready(function(\$) { \$.post('https://www.codingcreativo.it/wp-admin/admin-ajax.php', {action: 'wpt_view_count', id: '61441'}); }); ```
``` Submit a Comment Your email address will not be published. Required fields are marked *Comment * Name * Email * Website Δdocument.getElementById( "ak_js_1" ).setAttribute( "value", ( new Date() ).getTime() ); ```
``` ```
``` Iscriviti alla nostra newsletter! Nome Email Iscrivendomi accetto le regole sulla privacy di questo sito Corsi su C, C++, Python, JavaScript, PHP Tanti corsi di programmazione registrati ed in diretta per aituarti a studiare! vai al link Tag CloudJavaScript Python Calcolatrice in PythonMetodi delle classi in PythonClassi in PythonClass PythonLa programmazione ad oggettiCodingGioco di macchine con ScratchCruciverba con ScratchArea di un triangolo rettangoloConfronto tra numeri Corsi su C, C++, Python, JavaScript, PHP Tanti corsi di programmazione registrati ed in diretta per aituarti a studiare! vai al link Tag CloudJavaScript Python ```
``` ```
``` ```
``` Facebook Instagram RSS © Copyright Coding Creativo Cristina Galfo - P. IVA: 02629150208 Privacy Policy ```
``` ```
``` (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; js = d.createElement(s); js.id = id; js.src = 'https://connect.facebook.net/it_IT/sdk/xfbml.customerchat.js#xfbml=1&version=v6.0&autoLogAppEvents=1' fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-133407883-1', 'auto'); ga('send', 'pageview'); .wp-container-5.wp-container-5,.wp-container-8.wp-container-8,.wp-container-11.wp-container-11,.wp-container-12.wp-container-12,.wp-container-14.wp-container-14{flex-wrap:nowrap;}.wp-elements-f1b2504e12e4ec23cdfcb3fb9f154282 a,.wp-elements-93c84df8d8d3a17bdf55af7912775939 a{color:#000000;}.wp-container-6.wp-container-6,.wp-container-9.wp-container-9{justify-content:center;} /* <![CDATA[ */ var wpcf7 = {"api":{"root":"https:\/\/www.codingcreativo.it\/wp-json\/","namespace":"contact-form-7\/v1"},"cached":"1"}; /* ]]> */ "use strict";var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var RocketBrowserCompatibilityChecker=function(){function RocketBrowserCompatibilityChecker(options){_classCallCheck(this,RocketBrowserCompatibilityChecker),this.passiveSupported=!1,this._checkPassiveOption(this),this.options=!!this.passiveSupported&&options}return _createClass(RocketBrowserCompatibilityChecker,[{key:"_checkPassiveOption",value:function(self){try{var options={get passive(){return!(self.passiveSupported=!0)}};window.addEventListener("test",null,options),window.removeEventListener("test",null,options)}catch(err){self.passiveSupported=!1}}},{key:"initRequestIdleCallback",value:function(){!1 in window&&(window.requestIdleCallback=function(cb){var start=Date.now();return setTimeout(function(){cb({didTimeout:!1,timeRemaining:function(){return Math.max(0,50-(Date.now()-start))}})},1)}),!1 in window&&(window.cancelIdleCallback=function(id){return clearTimeout(id)})}},{key:"isDataSaverModeOn",value:function(){return"connection"in navigator&&!0===navigator.connection.saveData}},{key:"supportsLinkPrefetch",value:function(){var elem=document.createElement("link");return elem.relList&&elem.relList.supports&&elem.relList.supports("prefetch")&&window.IntersectionObserver&&"isIntersecting"in IntersectionObserverEntry.prototype}},{key:"isSlowConnection",value:function(){return"connection"in navigator&&"effectiveType"in navigator.connection&&("2g"===navigator.connection.effectiveType||"slow-2g"===navigator.connection.effectiveType)}}]),RocketBrowserCompatibilityChecker}(); /* <![CDATA[ */ var RocketPreloadLinksConfig = {"excludeUris":"\/(.+\/)?feed\/?.+\/?|\/(?:.+\/)?embed\/|\/(index\\.php\/)?wp\\-json(\/.*|\$)|\/wp-admin\/|\/logout\/|\/wp-login.php","usesTrailingSlash":"1","imageExt":"jpg|jpeg|gif|png|tiff|bmp|webp|avif","fileExt":"jpg|jpeg|gif|png|tiff|bmp|webp|avif|php|pdf|html|htm","siteUrl":"https:\/\/www.codingcreativo.it","onHoverDelay":"100","rateThrottle":"3"}; /* ]]> */ (function() { "use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e=function(){function i(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),e}}();function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var t=function(){function n(e,t){i(this,n),this.browser=e,this.config=t,this.options=this.browser.options,this.prefetched=new Set,this.eventTime=null,this.threshold=1111,this.numOnHover=0}return e(n,[{key:"init",value:function(){!this.browser.supportsLinkPrefetch()||this.browser.isDataSaverModeOn()||this.browser.isSlowConnection()||(this.regex={excludeUris:RegExp(this.config.excludeUris,"i"),images:RegExp(".("+this.config.imageExt+")\$","i"),fileExt:RegExp(".("+this.config.fileExt+")\$","i")},this._initListeners(this))}},{key:"_initListeners",value:function(e){-1<this.config.onHoverDelay&&document.addEventListener("mouseover",e.listener.bind(e),e.listenerOptions),document.addEventListener("mousedown",e.listener.bind(e),e.listenerOptions),document.addEventListener("touchstart",e.listener.bind(e),e.listenerOptions)}},{key:"listener",value:function(e){var t=e.target.closest("a"),n=this._prepareUrl(t);if(null!==n)switch(e.type){case"mousedown":case"touchstart":this._addPrefetchLink(n);break;case"mouseover":this._earlyPrefetch(t,n,"mouseout")}}},{key:"_earlyPrefetch",value:function(t,e,n){var i=this,r=setTimeout(function(){if(r=null,0===i.numOnHover)setTimeout(function(){return i.numOnHover=0},1e3);else if(i.numOnHover>i.config.rateThrottle)return;i.numOnHover++,i._addPrefetchLink(e)},this.config.onHoverDelay);t.addEventListener(n,function e(){t.removeEventListener(n,e,{passive:!0}),null!==r&&(clearTimeout(r),r=null)},{passive:!0})}},{key:"_addPrefetchLink",value:function(i){return this.prefetched.add(i.href),new Promise(function(e,t){var n=document.createElement("link");n.rel="prefetch",n.href=i.href,n.onload=e,n.onerror=t,document.head.appendChild(n)}).catch(function(){})}},{key:"_prepareUrl",value:function(e){if(null===e||"object"!==(void 0===e?"undefined":r(e))||!1 in e||-1===["http:","https:"].indexOf(e.protocol))return null;var t=e.href.substring(0,this.config.siteUrl.length),n=this._getPathname(e.href,t),i={original:e.href,protocol:e.protocol,origin:t,pathname:n,href:t+n};return this._isLinkOk(i)?i:null}},{key:"_getPathname",value:function(e,t){var n=t?e.substring(this.config.siteUrl.length):e;return n.startsWith("/")||(n="/"+n),this._shouldAddTrailingSlash(n)?n+"/":n}},{key:"_shouldAddTrailingSlash",value:function(e){return this.config.usesTrailingSlash&&!e.endsWith("/")&&!this.regex.fileExt.test(e)}},{key:"_isLinkOk",value:function(e){return null!==e&&"object"===(void 0===e?"undefined":r(e))&&(!this.prefetched.has(e.href)&&e.origin===this.config.siteUrl&&-1===e.href.indexOf("?")&&-1===e.href.indexOf("#")&&!this.regex.excludeUris.test(e.href)&&!this.regex.images.test(e.href))}}],[{key:"run",value:function(){"undefined"!=typeof RocketPreloadLinksConfig&&new n(new RocketBrowserCompatibilityChecker({capture:!0,passive:!0}),RocketPreloadLinksConfig).init()}}]),n}();t.run(); }()); jqueryParams.length&&\$.each(jqueryParams,function(e,r){if("function"==typeof r){var n=String(r);n.replace("\$","jQuery");var a=new Function("return "+n)();\$(document).ready(a)}}); /* <![CDATA[ */ var DIVI = {"item_count":"%d Item","items_count":"%d Items"}; var et_builder_utils_params = {"condition":{"diviTheme":true,"extraTheme":false},"scrollLocations":["app","top"],"builderScrollLocations":{"desktop":"app","tablet":"app","phone":"app"},"onloadScrollLocation":"app","builderType":"fe"}; var et_frontend_scripts = {"builderCssContainerPrefix":"#et-boc","builderCssLayoutPrefix":"#et-boc .et-l"}; var et_pb_custom = {"ajaxurl":"https:\/\/www.codingcreativo.it\/wp-admin\/admin-ajax.php","images_uri":"https:\/\/www.codingcreativo.it\/wp-content\/themes\/Divi\/images","builder_images_uri":"https:\/\/www.codingcreativo.it\/wp-content\/themes\/Divi\/includes\/builder\/images","et_frontend_nonce":"fe81a031fc","subscription_failed":"Please, check the fields below to make sure you entered the correct information.","et_ab_log_nonce":"c13078ba60","fill_message":"Please, fill in the following fields:","contact_error_message":"Please, fix the following errors:","invalid":"Invalid email","captcha":"Captcha","prev":"Prev","previous":"Previous","next":"Next","wrong_captcha":"You entered the wrong number in captcha.","wrong_checkbox":"Checkbox","ignore_waypoints":"no","is_divi_theme_used":"1","widget_search_selector":".widget_search","ab_tests":[],"is_ab_testing_active":"","page_id":"61441","unique_test_id":"","ab_bounce_rate":"5","is_cache_plugin_active":"yes","is_shortcode_tracking":"","tinymce_uri":"https:\/\/www.codingcreativo.it\/wp-content\/themes\/Divi\/includes\/builder\/frontend-builder\/assets\/vendors","accent_color":"#2ea3f2","waypoints_options":{"context":[".pum-overlay"]}}; var et_pb_box_shadow_elements = []; /* ]]> */ /* <![CDATA[ */ var _wpUtilSettings = {"ajax":{"url":"\/wp-admin\/admin-ajax.php"}}; /* ]]> */ /* <![CDATA[ */ var wpreview = {"ajaxurl":"https:\/\/www.codingcreativo.it\/wp-admin\/admin-ajax.php","loginRequiredMessage":"You must log in to add your review"}; /* ]]> */ (function() { var expirationDate = new Date(); expirationDate.setTime( expirationDate.getTime() + 31536000 * 1000 ); document.cookie = "pll_language=en; expires=" + expirationDate.toUTCString() + "; path=/; secure; SameSite=Lax"; }()); ```