Search

Introduction to the loops

Python has a powerful conceptcalled loops.Loops makes use of called looping (iteration), which helps cut out our repetitive code. This is very helpful when you want to do something times simply write the initial code then you can repeat multiple times till a particular condition will not met.The purpose of loops is to repeat the same, or similar, code several times. This number of times could be specified to a certain number, or the number of times could be dictated by a certain condition being met.  A conditional loop has the potential to become an infinite loop when nothing in the loop's body can affect the outcome of the loop's conditional statement. The While loop and the For loop are the two common types of conditional loops. You can also provide a numerical range(sequence) of values to control how many times the code will execute.  In Python, there are two primary structures for loops: for while For Loop: “for” loop is iteratively execute code for each item in a pre-defined list Iterations that you know how many times it will occur (even if you can stop it before) means that you know how many times loop will run. The syntax of a for loop is for (followed by (: ) ) With the for loop we can execute a number of statements, once for each item in a list, tuple, set. Let say, you want to repeat some code multiple times but you will not care about variable I, so it will be good practice to replace I with _, this means that we will not care about this valueWhere can we use for loop? A for loop is used for iterating over a sequence (either a list, a tuple, a dictionary, a set, or a strings). for loop are used for sequential traversal. Ex- traversing a list or strings or array etc. Syntax: for i in sequence: Body of for “All values inside the sequence will take i variable”In this above example, we have created list i.e A having strings values, “for” is the syntax of for loop followed by “:”, then there is a variable i that is called placeholder it will take all the values from the sequence i.e. A and then it will print all the values inside the placeholder i.e. i, print(i)In above example, we have created list B in that we took non-sequential order integer value, however loop will execute on each of the item, in the same manner in which we are defined in the list B.Placeholder(i) is the unique variable inside the for loop it will represent all the values inside the sequence i.e. B, i is not a pre-defined variable so in place of i we can use anything means that any variable, anystrings, except numeric value we can use anything. In the below example you will better understand how this placeholder will work, in place of placeholder we can use X variable and completely unrelated strings also we can putHope you will better understand that whichever placeholder you will put it does not matter. In the above example, list B contains only numeric values, but you can use other type as well like text strings.for loop on Text Strings:In the example below, a list called B is defined with two text strings that represent two statement. The for loop will run iteratively on each text strings (represented by the placeholder strings in each iteration). List B contains two text strings i.e. “This is str” and “This is boolean” so in the first iteration “This is str” will print then in the next iteration “This is boolean” will print.We can achieve the output in another way by using range method to loop.for loop on Data Structures:In the below example, we have created a list i.e. List, that contains other lists i.e Months and Income. Placeholder flist represent all the elements from the List and List contains two lists i.e Months and Income so it will repeat one by one in which you have defined.In the first iteration Months will print and in the second iteration Income will print.while loop: A loop is used to repetitively execute program until a defined condition will not met  Iterations that you will observe something else to decide when to stop an iteration - those are the while loops.While loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition will not satisfied then, after the loop in the program will execute.If the test expression is true, statements inside the body of while loop will execute. Then, the test expression is evaluated again. The process goes on till the test expression is evaluated to false. A while loop can also terminate when a break or return within the statement body is executed. You can use continue to terminate the current iteration without exiting the while loop. continue it will pass control to the next iteration of the while loop. The termination condition will evaluate at the top of the loop. Where can we use while loops? The while loop in Python will iterate over a block of code if the test expression (condition) is true. We generally use this loop when we don't know the number of times to iterate beforehand. Ex: - let say, If we want to check the grade of every student in the class, we loop from 1 to that particular range of number. When the number of times is not known, we use a "while" loop. The while loop is used repeat a section of code an unknown number of times until a specific condition is met. Ex- say we want to know how many times a given number can be divided by 2 before it is less than or equal to 1. Syntax: while condition: body_of_while Condition can be a limit that how many times the while loop will run, you can see in the below example the loop will run till 9 we have restrict the iteration. Once loop will reaches 10 (x=10) then loop will not executeA while loop start with while and then condition.  In the below code if you notice that we have given the indentation, it must have to give the indentation means that statement is inside the loop. In this example, we add 1 in the x and value of x does not exceed the given condition (x<10). In the below code we used ‘<’ operator that means the value of x will start from 0 till 9 exclude 10. We have used one more operator i.e. ‘+=’ that means 1 will add in each of the element of the xWhen loop will reaches 10 (x=10) then the condition no longer satisfied so the loop will not execute another iteration In the above example, the code will executed in order that means the first 1 will add in the value of x then print() function will execute. You can change the position if you want to print the value of x first then also you can add the 1 value in the xYou can also use the range operator instead of the comparison operator in this you need to specify the range for the iteration  In this range operator starting value is inclusive but not end value In the below example, while loop runs till 5 and 5 will not include then we have increment x by 1 means that it will add 1 in each of the x element. When x reaches to 5 then it will not execute another iteration of code.You can notice that structure of the while loop will remains same except condition and indentation Nested Loops: nested loopsare loopswhich run within another loop. Where can we use nested loops? Nested loops are useful when for each pass through the outer loop, you need to repeat some action on the data in the outer loop. Ex- you read a file line by line and for each line you must count how many times the word “the” is found. Nested for loop: Syntax: for iterating_var in sequence:     for iterating_var in sequence:        statements(s)     statements(s) Here,  iterating_varis the variable that takes the value of the item inside the sequence on each iteration. These are constructed like:In the above example, the program first runs the outer loop, execute the first code then it will runs the inner loop i.e. nested loop, nested loop will runs till sequence then program return to the top of the outer loop, run the next iteration and again run the nested loop till sequence and again program return back to top of the outer loop it will execute till the sequence will not complete.In the below example you can see how nested for loop will work, we have created two lists, A consist of numeric value and B consist of strings value. First program will runs the outer loop and print 1 then program will runs the nested loop, it will run till the sequence will not complete and print a, b, c then program return back to the top of the outer loop and run the next iteration and print 2 then program will run the nested loop till the sequence will not complete and print a, b, c etc. This will execute till the sequence of the outer loop will not complete.Nested while loop: When the while loop is present inside another while loop then it is called nested while loop. Syntax: while expression:     while expression:        statement(s)     statement(s) A nested while loop will present while statement inside another while statement. In a nested while loop, first iteration of the outer loop is first executed, after which the inner loop will execute. Once the condition of the inner loop is satisfied, the program moves to the next iteration of the outer loop.Practical examples of for loop: Ex: Calculate the sum Practical examples of while loops: Ex: Calculate the table from 1 to 2 Conclusion:In this post, we have learnt about  Loops: for loopfor loop will iteratively execute code for each item in a pre-defined list Nested for loop A nested loop is a loop that will occurs within another loop while loop A while loop is used to iteratively execute code until a pre-defined condition is no longer satisfied (i.e. results in a value of False) Nested while loop When the while loop is present inside another while loop then it is called nested while loop.

Introduction to the loops

6K
Introduction to the loops

Python has a powerful conceptcalled loops.Loops makes use of called looping (iteration), which helps cut out our repetitive code. This is very helpful when you want to do something times simply write the initial code then you can repeat multiple times till a particular condition will not met.The purpose of loops is to repeat the same, or similar, code several times. This number of times could be specified to a certain number, or the number of times could be dictated by a certain condition being met.  

A conditional loop has the potential to become an infinite loop when nothing in the loop's body can affect the outcome of the loop's conditional statement. The While loop and the For loop are the two common types of conditional loops. You can also provide a numerical range(sequence) of values to control how many times the code will execute.  

In Python, there are two primary structures for loops: 

  1. for 
  2. while 

For Loop: 

  • “for” loop is iteratively execute code for each item in a pre-defined list 
  • Iterations that you know how many times it will occur (even if you can stop it before) means that you know how many times loop will run. 
  • The syntax of a for loop is for (followed by (: ) ) 
  • With the for loop we can execute a number of statements, once for each item in a list, tuple, set. 
  • Let say, you want to repeat some code multiple times but you will not care about variable I, so it will be good practice to replace I with _, this means that we will not care about this value

Introduction to the loops

Where can we use for loop? 

A for loop is used for iterating over a sequence (either a list, a tuple, a dictionary, a set, or a strings). 

for loop are used for sequential traversal. Ex- traversing a list or strings or array etc. 

Syntax: 

for i in sequence: 

Body of for 

“All values inside the sequence will take i variable”

Introduction to the loops

In this above example, we have created list i.e A having strings values, “for” is the syntax of for loop followed by “:”, then there is a variable i that is called placeholder it will take all the values from the sequence i.e. A and then it will print all the values inside the placeholder i.e. i, print(i)

Introduction to the loops

In above example, we have created list B in that we took non-sequential order integer value, however loop will execute on each of the item, in the same manner in which we are defined in the list B.Placeholder(i) is the unique variable inside the for loop it will represent all the values inside the sequence i.e. B, i is not a pre-defined variable so in place of i we can use anything means that any variable, anystrings, except numeric value we can use anything. 

In the below example you will better understand how this placeholder will work, in place of placeholder we can use X variable and completely unrelated strings also we can put

Introduction to the loops

Hope you will better understand that whichever placeholder you will put it does not matter. In the above example, list B contains only numeric values, but you can use other type as well like text strings.

for loop on Text Strings:

In the example below, a list called B is defined with two text strings that represent two statement. The for loop will run iteratively on each text strings (represented by the placeholder strings in each iteration). List B contains two text strings i.e. “This is str” and “This is boolean” so in the first iteration “This is str” will print then in the next iteration “This is boolean” will print.

Introduction to the loops

We can achieve the output in another way by using range method to loop.

Introduction to the loops

for loop on Data Structures:

In the below example, we have created a list i.e. List, that contains other lists i.e Months and Income. Placeholder flist represent all the elements from the List and List contains two lists i.e Months and Income so it will repeat one by one in which you have defined.

In the first iteration Months will print and in the second iteration Income will print.

Introduction to the loops

while loop: 

A loop is used to repetitively execute program until a defined condition will not met  

Iterations that you will observe something else to decide when to stop an iteration - those are the while loops.While loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition will not satisfied then, after the loop in the program will execute.If the test expression is true, statements inside the body of while loop will execute. Then, the test expression is evaluated again. The process goes on till the test expression is evaluated to false. 

A while loop can also terminate when a break or return within the statement body is executed. You can use continue to terminate the current iteration without exiting the while loop. continue it will pass control to the next iteration of the while loop. The termination condition will evaluate at the top of the loop. 

Where can we use while loops? 

  • The while loop in Python will iterate over a block of code if the test expression (condition) is true. We generally use this loop when we don't know the number of times to iterate beforehand. 
  • Ex: - let say, If we want to check the grade of every student in the class, we loop from 1 to that particular range of number. When the number of times is not known, we use a "while" loop. 
  • The while loop is used repeat a section of code an unknown number of times until a specific condition is met. Ex- say we want to know how many times a given number can be divided by 2 before it is less than or equal to 1. 

Syntax: 

while condition: 

body_of_while 

  • Condition can be a limit that how many times the while loop will run, you can see in the below example the loop will run till 9 we have restrict the iteration. 
  • Once loop will reaches 10 (x=10) then loop will not execute

Introduction to the loops

  • A while loop start with while and then condition.  
  • In the below code if you notice that we have given the indentation, it must have to give the indentation means that statement is inside the loop. 
  • In this example, we add 1 in the x and value of x does not exceed the given condition (x<10). 
  • In the below code we used ‘<’ operator that means the value of x will start from 0 till 9 exclude 10. 
  • We have used one more operator i.e. ‘+=’ that means 1 will add in each of the element of the x

Introduction to the loops

  • When loop will reaches 10 (x=10) then the condition no longer satisfied so the loop will not execute another iteration 
  • In the above example, the code will executed in order that means the first 1 will add in the value of x then print() function will execute. 
  • You can change the position if you want to print the value of x first then also you can add the 1 value in the x

Introduction to the loops

  • You can also use the range operator instead of the comparison operator in this you need to specify the range for the iteration  
  • In this range operator starting value is inclusive but not end value 
  • In the below example, while loop runs till 5 and 5 will not include then we have increment x by 1 means that it will add 1 in each of the x element. 
  • When x reaches to 5 then it will not execute another iteration of code.

Introduction to the loops

  • You can notice that structure of the while loop will remains same except condition and indentation 

Nested Loops: 

  • nested loopsare loopswhich run within another loop. 

Where can we use nested loops? 

  • Nested loops are useful when for each pass through the outer loop, you need to repeat some action on the data in the outer loop. Ex- you read a file line by line and for each line you must count how many times the word “the” is found. 

Nested for loop: 

Syntax: 

for iterating_var in sequence: 
   for iterating_var in sequence: 
      statements(s) 
   statements(s) 

Here,  iterating_varis the variable that takes the value of the item inside the sequence on each iteration. 

These are constructed like:

Introduction to the loops

In the above example, the program first runs the outer loop, execute the first code then it will runs the inner loop i.e. nested loop, nested loop will runs till sequence then program return to the top of the outer loop, run the next iteration and again run the nested loop till sequence and again program return back to top of the outer loop it will execute till the sequence will not complete.

In the below example you can see how nested for loop will work, we have created two lists, A consist of numeric value and B consist of strings value. First program will runs the outer loop and print 1 then program will runs the nested loop, it will run till the sequence will not complete and print a, b, c then program return back to the top of the outer loop and run the next iteration and print 2 then program will run the nested loop till the sequence will not complete and print a, b, c etc. This will execute till the sequence of the outer loop will not complete.

Introduction to the loops

Nested while loop: 

  • When the while loop is present inside another while loop then it is called nested while loop. 

Syntax: 

while expression: 
   while expression: 
      statement(s) 
   statement(s) 
  • A nested while loop will present while statement inside another while statement. In a nested while loop, first iteration of the outer loop is first executed, after which the inner loop will execute. Once the condition of the inner loop is satisfied, the program moves to the next iteration of the outer loop.

Introduction to the loops

Practical examples of for loop: 

Ex: Calculate the sum Introduction to the loops

Practical examples of while loops: 

Ex: Calculate the table from 1 to 2 

Introduction to the loops

Conclusion:

In this post, we have learnt about  

  • Loops: 
    • for loop

for loop will iteratively execute code for each item in a pre-defined list 

  • Nested for loop 

A nested loop is a loop that will occurs within another loop 

  • while loop 

A while loop is used to iteratively execute code until a pre-defined condition is no longer satisfied (i.e. results in a value of False) 

  • Nested while loop 

When the while loop is present inside another while loop then it is called nested while loop.

KnowledgeHut

KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.
Website : https://www.knowledgehut.com

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

9 Stupendous Technologies You Might Be Using In Near Future

Our lives have made a 360 degree turn in the past decade. Technology is making us move at break neck speed and our lives are all about going somewhere and getting things done. The internet brought the world closer and it has been predicted that it will lead to the democratization of the world. While until a few years back we needed our PCs and laptops to get online, today we can do so with the touch of a button on our smartphones. Indeed, the smartphone has now become the most popular device in many parts of the world. Mobile technology is exactly what the name implies; technology that is mobile, portable and you can carry around in your pocket. A smartphone with an internet connection is all you need to get all your work done. Android and iOS are changing the way we live, eat, sleep, work and even travel. As consumerism grows so does the mobile technology, giving us better, richer and safer experiences than ever before. You will no longer be standing in a checkout line: The future of easy shopping is upon us. With the right app, you will soon be scanning your product and getting it delivered across to your address, which is already stored in the app and the payment would be deducted from your account which is already linked to this app. Of course, the app knows all about your shopping preferences and would suggest possible online stores if you do not get in at the store. Wearable technology: Google Glass and Apple Watch are not the only wearable technology out there. Medical wearable trends are fast changing the landscape of healthcare with such things as computer pills that when ingested send a patient’s medical information to a health centre wirelessly or artificial pancreas that monitor a patient’s glucose levels and also injects insulin at defined intervals. In fact, the future might be even more high-tech with a camera for a contact lens and a microphone under the skin. Your vehicle, a Wi-Fi hotspot: Your car might soon be an escape into a sci-fi movie. GPS enabled location trackers are already widely used but now your vehicle might have wi-fi and enhanced location guidance that may be displayed on the windshield. Data transfer between devices: You are working on your laptop, now on your phone and now on your tablet. There will soon be apps that will allow you to seamlessly move between devices without disrupting your work. No keys future: How many times have you locked yourself out of your house or your car? If carrying a hundred keys around is not exactly your cup of tea then you might as well make your smartphone your best friend since it might be all that you need to open your house, locker, car, safe or any other lock. No more charging: A charge less phone is a complete killjoy. But what if your phone charged by itself without a charger? This ‘”dream come true” situation might soon become a reality with a phenomenon called Piezoelectricity that converts mechanical movements into electric current. So your phone will charge as you are texting or talking. Now that is really a dream come true! Don’t like to type? Then just think: Technology that uses electroencephalography (EEG) might soon hit the market where in devices will be able to read your brain waves and allow interaction with phones or computers or other devices. Advent of the 5G: Once in every 5 years, cellular standards take a quantum leap and the 5G promises to be the most futuristic of them all in terms of power and functionality. This standard is expected to deliver higher speed internet services and greater levels of AI capabilities. No communication barriers: You will soon understand as many languages as you want due to the instant translation apps that will be available on your phone. Global communication barriers will be brought down as people can connect across geographies and text each other in multiple languages. The number of mobile users is expected to reach 5 billion by the year 2020 and this means better connectivity and infrastructure even in the remotest parts of the world. Technology is bringing the world closer and with such advances as interactive t-shirts, USB drives in ornaments and ear patches with voice recognition, the future of mobile technology will be you!
9 Stupendous Technologies You Might Be Using In Ne...

Our lives have made a 360 degree turn in the past ... Read More

Scala In Demand Technologies Built On Scala

The term Scala originated from “Scalable language” and it means that Scala grows with you. In recent times, Scala has attracted developers because it has enabled them to deliver things faster with fewer codes. Developers are now much more interested in having Scala training to excel in the big data field. The Scala community has grown over the years and it has now become a standard for enterprise, start-ups and universities alike. Scala is now being used by many companies and individuals to build their own new ideas. Play Framework, Akka, Apache Spark, etc are some of the tools and projects created using Scala. Scala is now the next wave of computation engines and more importance has been given to the speed processing rather than the size of the batch, and the ability to process event streaming in real-time. 1.Apache Spark Apache Spark can be considered as the replacement of MapReduce. In late 2013, Cloudera, the largest Hadoop vendor supported the idea of replacing MapReduce with Apache Spark. Spark is developed by AMPLab and it is a fast and general purpose engine for large-scale data processing. Spark effectively provides an alternative for Hadoop’s two stage MapReduce model. It has improved the performance of certain applications to 100 times with its fine grain operators, in-memory caching of intermediate data, and data flow optimization. 2. Scalding Scalding has been introduced and maintained by Twitter. It provides full benefits of Scala syntax and functional operations. Scala is a powerful language for solving functional problems. Scalding makes comprehensive use of Scala and it is an extension to cascading that enables application development with Scala. If we focus on the benefits of Scalding, data applications can be built with Scala. With simple and concise syntax code becomes easier to interpret. Scalding has filled the benefits of cascading application framework. 3. Apache Kafka Built and maintained by LinkedIn, Apache Kafka is a distributed streaming platform. Apache Kafka allows the user to publish and subscribe streams of data, just like a messaging system. Kafka is responsible for handling hundred of megabytes of read-write traffic per second from thousand of clients. It is also empowered by Scala and we can see the influence of the language. Real-time data pipelines and streaming apps can be built by using Apache Kafka. Yahoo Kafka Manager is also written in Scala and the web console is built using Play Framework. The Kafka Manager is being used by many teams including the Media Analytics team. It interacts with an actor-based, in-memory model built with Akka and Apache Curator. 4. Finagle Built by the people at twitter, Finagle can be considered as one of the best case using Scala. It is used to build high-concurrency servers and is an extensible RPC system for JVM. Finagle was intended to provide high performance, concurrency along with Scala and Java idiomatic APIs. Finagle is known for the optimal use of available system resources and high scalability through concurrency. It uses safe, simple and clean concurrent programming model which is based on Futures. All these results in safe and modular programs.
Scala In Demand Technologies Built On Scala

The term Scala originated from “Scalable languag... Read More

Web Development Using PHP And MySQL

PHP (or PHP Hypertext Preprocessor) is a server-side scripting language that is used to create dynamic web pages that can interact with databases. It is a widely-used open source language that is specifically used for web application development and can be embedded within HTML. Why PHP? The distinguishing feature of PHP is that the scripting code is executed on the server, which generates HTML that is sent back to the client. The client receives the result of executing the script without knowing the underlying code. Developers can configure the web server to process all the HTML files (containing the PHP script). PHP course is easy to learn for any newcomer, but also offers advanced programming features. Using PHP with a database system PHP, as a scripting language, is popular among web developers because of its ability to interact with database systems including Oracle and MySQL. This article discusses the use of PHP scripting language with the MySQL database. Any website can require a variety of data or information to display and to retrieve them from the database. This can include display of a simple list to the running of the website based on data stored in the database. Listed below are some examples where PHP and MySQL can be used together: • Digital Ad banners, where the PHP script can be used to retrieve a digital banner from the database, which then selects a random banner from its table records and sends it back to the calling script. The PHP script can also maintain a count of banner views and clicks from the website. • Internet forums or digital boards, which use PHP and MySQL to store and retrieve user messages. • Website designing, where the design of an entire website can be changed using a couple of PHP scripts, instead of changing and uploading each web page. The PHP script can access the MySQL database to retrieve all information about the web page. Setting up the MySQL database The procedure of setting up the MySQL database varies according to the host. Every database would require a user name and password, in order to access the database. Database administration can be done using PHP scripts or using a program like PHPMyAdmin. The next step is to create the database tables for storing the website information. Creating a database table using PHPMyAdmin is also simple. Alternatively, one can create and configure the entire database using the following PHP script: CREATE TABLE tablename { Fields } Where the Fields are coded as fieldname type(length) extra_info Example: first varchar(15) NOT NULL The following command is used in the PHP script to connect to the MySQL database: mysql_connect(localhost,$username,$password); where: • localhost is the server address on which the web site is running, • $username is the user name for the database access • $password is the password for the database access Executing PHP commands After configuring and connecting to the MySQL database, you can start executing PHP commands on the server. Following are the 2 methods of executing a PHP command: • Entering the command in PHP using the following syntax: Mysql_query($query) This form of command can be used to repeat the command simply by changing the variable. • Defining the command as a variable. The result of the operation will be assigned to the variable. Data input and output Inserting data using PHP is identical to the procedure of data input using HTML pages. The advantage of using PHP is that the script does not need to be changed for each new piece of input data. Users can also input their own data on the web page. Following is an example of an HTML page with textboxes that can be used to enter data in a form: Alternatively, you can use variables to input information into the database. Example: $first=$_POST[‘first’]; $last=$_POST[‘last’]; $phone=$_POST[‘phone’]; $mobile=$_POST[‘mobile’]; $fax=$_POST[‘fax’]; $email=$_POST[’email’]; $web=$_POST[‘web’]; … $query = “INSERT INTO contacts VALUES (”,’$first’,’$last’,’$phone’,’$mobile’,’$fax’,’$email’,’$web’)”; mysql_query($query); This script is saved in the insert.php file, which can be called from the HTML form. Using this method, data entered in the web page form is stored in the defined variables, which are then passed to the PHP. To display (or output) the entered data using PHP, you can use the following MySQL command with the result assigned to the variable. $query=”SELECT * FROM contacts”; $result=mysql_query($query); PHP provides 2 submission methods, GET and POST to get the data submitted by the form into your PHP script. GET method displays the variables and the data in the page address, while they are invisible in the POST method. For example, a script can be created that will display different web pages depending on the clicked link. yourpage.php?user=david (to show David’s page) yourpage.php?user=tom (to show Tom’s page)
3972
Web Development Using PHP And MySQL

PHP (or PHP Hypertext Preprocessor) is a server-si... Read More

20% Discount