Seleziona una pagina

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.

##### Banner Pubblicitario

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.

##### Banner pubblicitario

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 ```
``` (adsbygoogle = window.adsbygoogle || []).push({}); I migliori prodotti Invia commento Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *Commento * Nome * Email * Sito web Δ ```
``` ```
``` Adsense (adsbygoogle = window.adsbygoogle || []).push({}); Algobuild Algoritmi in C Algoritmi in C++ Apache App inventor Bootstrap Canva Coding con scratch Come creare un sito web CSS Html JavaScript Javascript jQuery Linguaggio C Linguaggio C++ PHP Pygame Python Python Reti Scratch Tutorial C Tutorial scratch 3.0 Vue Web Ricerca per: Articoli recenti Generare array con valori predefiniti np.concatenate Broadcasting Operazioni aritmetiche con gli array Numpy Installazione NumPy Commenti recentipaolo carratello su Funzioni Pythonpaolo carratello su Stringhe in Pythondaniele su Numero primo in CPaolo su Topologia di reteCristina su Coding ```
``` ```
``` ```
``` Coding Creativo Python Javascript jQuery Html CSS Bootstrap Algoritmi in C Facebook Instagram RSS © Copyright Coding Creativo Cristina Galfo - P. IVA: 02629150208 Privacy Policy ```
``` ```
``` Newsletter Rimani aggiornato sui nostri articoli, iscriviti alla newsletter inserendo la tua mail! Nome Email Iscrivendomi accetto le regole sulla privacy di questo sito Python Corso base Python for Data Analysis  Python e Pygame .wp-container-core-columns-is-layout-1.wp-container-core-columns-is-layout-1{flex-wrap:nowrap;}.wp-block-gallery.wp-block-gallery-1{--wp--style--unstable-gallery-gap:var( --wp--style--gallery-gap-default, var( --gallery-block--gutter-size, var( --wp--style--block-gap, 0.5em ) ) );gap:var( --wp--style--gallery-gap-default, var( --gallery-block--gutter-size, var( --wp--style--block-gap, 0.5em ) ) );}.wp-block-gallery.wp-block-gallery-2{--wp--style--unstable-gallery-gap:var( --wp--style--gallery-gap-default, var( --gallery-block--gutter-size, var( --wp--style--block-gap, 0.5em ) ) );gap:var( --wp--style--gallery-gap-default, var( --gallery-block--gutter-size, var( --wp--style--block-gap, 0.5em ) ) );} /* <![CDATA[ */ "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[ */ (function() { "use strict";var e=function(){function n(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),e}}();function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var t=function(){function r(e,t){n(this,r),this.attrName="data-rocketlazyloadscript",this.browser=t,this.options=this.browser.options,this.triggerEvents=e,this.userEventListener=this.triggerListener.bind(this)}return e(r,[{key:"init",value:function(){this._addEventListener(this)}},{key:"reset",value:function(){this._removeEventListener(this)}},{key:"_addEventListener",value:function(t){this.triggerEvents.forEach(function(e){return window.addEventListener(e,t.userEventListener,t.options)})}},{key:"_removeEventListener",value:function(t){this.triggerEvents.forEach(function(e){return window.removeEventListener(e,t.userEventListener,t.options)})}},{key:"_loadScriptSrc",value:function(){var r=this,e=document.querySelectorAll("script["+this.attrName+"]");0!==e.length&&Array.prototype.slice.call(e).forEach(function(e){var t=e.getAttribute(r.attrName);e.setAttribute("src",t),e.removeAttribute(r.attrName)}),this.reset()}},{key:"triggerListener",value:function(){this._loadScriptSrc(),this._removeEventListener(this)}}],[{key:"run",value:function(){RocketBrowserCompatibilityChecker&&new r(["keydown","mouseover","touchmove","touchstart","wheel"],new RocketBrowserCompatibilityChecker({passive:!0})).init()}}]),r}();t.run(); }()); /* ]]> */ /* <![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"}; /* ]]> */ /* <![CDATA[ */ (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(); }()); /* ]]> */ /* <![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":"f62ecef40e","subscription_failed":"Si prega di verificare i campi di seguito per assicurarsi di aver inserito le informazioni corrette.","et_ab_log_nonce":"920e4e9b41","fill_message":"Compila i seguenti campi:","contact_error_message":"Per favore, correggi i seguenti errori:","invalid":"E-mail non valido","captcha":"Captcha","prev":"Indietro","previous":"Precedente","next":"Accanto","wrong_captcha":"Hai inserito un numero errato nei captcha.","wrong_checkbox":"Casella di controllo","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 pum_vars = {"version":"1.19.0","pm_dir_url":"https:\/\/www.codingcreativo.it\/wp-content\/plugins\/popup-maker\/","ajaxurl":"https:\/\/www.codingcreativo.it\/wp-admin\/admin-ajax.php","restapi":"https:\/\/www.codingcreativo.it\/wp-json\/pum\/v1","rest_nonce":null,"default_theme":"55701","debug_mode":"","disable_tracking":"","home_url":"\/","message_position":"top","core_sub_forms_enabled":"1","popups":[],"cookie_domain":"","analytics_route":"analytics","analytics_api":"https:\/\/www.codingcreativo.it\/wp-json\/pum\/v1"}; var pum_sub_vars = {"ajaxurl":"https:\/\/www.codingcreativo.it\/wp-admin\/admin-ajax.php","message_position":"top"}; var pum_popups = {"pum-55711":{"triggers":[{"type":"auto_open","settings":{"delay":10000,"cookie_name":["pum-55711"]}}],"cookies":[{"event":"on_popup_close","settings":{"name":"pum-55711","key":"","session":null,"path":true,"time":"1 day"}}],"disable_on_mobile":false,"disable_on_tablet":false,"atc_promotion":null,"explain":null,"type_section":null,"theme_id":"55703","size":"small","responsive_min_width":"0%","responsive_max_width":"100%","custom_width":"300px","custom_height_auto":true,"custom_height":"380px","scrollable_content":false,"animation_type":"fade","animation_speed":"350","animation_origin":"bottom","open_sound":"none","custom_sound":"","location":"center","position_top":"100","position_bottom":"10","position_left":"0","position_right":"10","position_from_trigger":false,"position_fixed":false,"overlay_disabled":false,"stackable":false,"disable_reposition":false,"zindex":"1999999999","close_button_delay":"100","fi_promotion":null,"close_on_form_submission":false,"close_on_form_submission_delay":"0","close_on_overlay_click":false,"close_on_esc_press":false,"close_on_f4_press":false,"disable_form_reopen":true,"disable_accessibility":false,"theme_slug":"enterprise-blue","id":55711,"slug":"registrazione"},"pum-79519":{"triggers":[{"type":"auto_open","settings":{"cookie_name":["pum-79519"],"delay":"2500"}}],"cookies":[{"event":"on_popup_close","settings":{"name":"pum-79519","key":"","session":null,"path":true,"time":"1 day"}}],"disable_on_mobile":false,"disable_on_tablet":false,"atc_promotion":null,"explain":null,"type_section":null,"theme_id":"55702","size":"small","responsive_min_width":"0%","responsive_max_width":"100%","custom_width":"300px","custom_height_auto":true,"custom_height":"380px","scrollable_content":false,"animation_type":"fade","animation_speed":"350","animation_origin":"bottom","open_sound":"none","custom_sound":"","location":"center","position_top":"100","position_bottom":"10","position_left":"0","position_right":"10","position_from_trigger":false,"position_fixed":false,"overlay_disabled":false,"stackable":false,"disable_reposition":false,"zindex":"1999999999","close_button_delay":"1500","fi_promotion":null,"close_on_form_submission":false,"close_on_form_submission_delay":"0","close_on_overlay_click":false,"close_on_esc_press":false,"close_on_f4_press":false,"disable_form_reopen":false,"disable_accessibility":false,"theme_slug":"lightbox","id":79519,"slug":"corsi-python"}}; /* ]]> */ window.lazyLoadOptions={elements_selector:"img[data-lazy-src],.rocket-lazyload,iframe[data-lazy-src]",data_src:"lazy-src",data_srcset:"lazy-srcset",data_sizes:"lazy-sizes",class_loading:"lazyloading",class_loaded:"lazyloaded",threshold:300,callback_loaded:function(element){if(element.tagName==="IFRAME"&&element.dataset.rocketLazyload=="fitvidscompatible"){if(element.classList.contains("lazyloaded")){if(typeof window.jQuery!="undefined"){if(jQuery.fn.fitVids){jQuery(element).parent().fitVids()}}}}}};window.addEventListener('LazyLoad::Initialized',function(e){var lazyLoadInstance=e.detail.instance;if(window.MutationObserver){var observer=new MutationObserver(function(mutations){var image_count=0;var iframe_count=0;var rocketlazy_count=0;mutations.forEach(function(mutation){for(i=0;i<mutation.addedNodes.length;i++){if(typeof mutation.addedNodes[i].getElementsByTagName!=='function'){continue} if(typeof mutation.addedNodes[i].getElementsByClassName!=='function'){continue} images=mutation.addedNodes[i].getElementsByTagName('img');is_image=mutation.addedNodes[i].tagName=="IMG";iframes=mutation.addedNodes[i].getElementsByTagName('iframe');is_iframe=mutation.addedNodes[i].tagName=="IFRAME";rocket_lazy=mutation.addedNodes[i].getElementsByClassName('rocket-lazyload');image_count+=images.length;iframe_count+=iframes.length;rocketlazy_count+=rocket_lazy.length;if(is_image){image_count+=1} if(is_iframe){iframe_count+=1}}});if(image_count>0||iframe_count>0||rocketlazy_count>0){lazyLoadInstance.update()}});var b=document.getElementsByTagName("body")[0];var config={childList:!0,subtree:!0};observer.observe(b,config)}},!1) ```