Skip to content

Instantly share code, notes, and snippets.

@letscode0410
Created December 13, 2018 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save letscode0410/8a8e12f03c06706eb395defd0f9c2b05 to your computer and use it in GitHub Desktop.
Save letscode0410/8a8e12f03c06706eb395defd0f9c2b05 to your computer and use it in GitHub Desktop.
Created on Cognitive Class Labs
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n",
" <a href=\"http://cocl.us/NotebooksPython101\"><img src = \"https://ibm.box.com/shared/static/yfe6h4az47ktg2mm9h05wby2n7e8kei3.png\" width = 750, align = \"center\"></a>\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a href=\"https://www.bigdatauniversity.com\"><img src = \"https://ibm.box.com/shared/static/ugcqz6ohbvff804xp84y4kqnvvk3bq1g.png\" width = 300, align = \"center\"></a>\n",
"\n",
"<h1 align=center><font size = 5>LOOPS IN PYTHON</font></h1>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Table of Contents\n",
"\n",
"\n",
"<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n",
"<li><a href=\"#ref1\">For Loops</a></p></li>\n",
"<li><a href=\"#ref2\">While Loops </a></p></li>\n",
"<br>\n",
"<p></p>\n",
"Estimated Time Needed: <strong>15 min</strong>\n",
"</div>\n",
"\n",
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"ref1\"></a>\n",
"<center><h2>For Loops</h2></center>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Sometimes, you might want to repeat a given operation many times. Repeated executions like this are performed by **loops**. We will look at two types of loops, **for** loops and **while** loops.\n",
"\n",
"Before we discuss loops lets discuss the **range** object. It is helpful to think of the range object as an ordered list. For now, let's look at the simplest case. If we would like to generate a sequence that contains three elements ordered from 0 to 2 we simply use the following command:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"range(3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a ><img src = \"https://ibm.box.com/shared/static/mxzjehamhqq5dljnxeh0vwqlju67j6z8.png\" width = 300, align = \"center\"></a>\n",
" <h4 align=center>:Example of range function.\n",
"\n",
" </h4> \n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### The `for` loop\n",
"The **for** loop enables you to execute a code block multiple times. For example, you would use this if you would like to print out every element in a list. \n",
"Let's try to use a **for** loop to print all the years presented in the list **dates**:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This can be done as follows:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1982\n",
"1980\n",
"1973\n"
]
}
],
"source": [
"dates = [1982,1980,1973]\n",
"N=len(dates)\n",
"\n",
"for i in range(N):\n",
" \n",
" print(dates[i]) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The code in the indent is executed **N** times, each time the value of **i** is increased by 1 for every execution. The statement executed is to** print** out the value in the list at index **i** as shown here:\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a ><img src = \"https://ibm.box.com/shared/static/w021psh5dtxcl2qheyc5d19d8tik7vq3.gif\" width = 1000, align = \"center\"></a>\n",
" <h4 align=center> Example of printing out the elements of a list.\n",
" </h4> \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this example we can print out a sequence of numbers from 0 to 7:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"4\n",
"5\n",
"6\n",
"7\n"
]
}
],
"source": [
"for i in range(0,8):\n",
" print(i)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Write a for loop the prints out all the element between -5 and 5 using the range function."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Double-click __here__ for the solution.\n",
"<!-- \n",
"for i in range(-5,6):\n",
" print(i)\n",
" -->\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In Python we can directly access the elements in the list as follows: "
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1982\n",
"1980\n",
"1973\n"
]
}
],
"source": [
"for year in dates: \n",
" print(year) \n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For each iteration, the value of the variable **years** behaves like the value of **dates[i]** in the first example:\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a ><img src = \"https://ibm.box.com/shared/static/zljq7m9stw8znv7ca2it6vkekaudfuwf.gif\" width = 1100, align = \"center\"></a>\n",
" <h4 align=center> Example of a for loop\n",
"\n",
" </h4> "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Print the elements of the following list:\n",
"**Genres=[ 'rock', 'R&B', 'Soundtrack' 'R&B', 'soul', 'pop']**\n",
"Make sure you follow Python conventions. "
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"rock\n",
"R&B\n",
"SoundtrackR&B\n",
"soul\n",
"pop\n"
]
}
],
"source": [
"Genres = [ 'rock', 'R&B', 'Soundtrack' 'R&B', 'soul', 'pop']\n",
"for val in Genres:\n",
" print(val)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Double-click __here__ for the solution.\n",
"<!-- \n",
"Genres=[ 'rock', 'R&B', 'Soundtrack' 'R&B', 'soul', 'pop']\n",
"for Genre in Genres:\n",
" print(Genre)\n",
" -->"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can change the elements in a list:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Before square 0 is red\n",
"After square 0 is white\n",
"Before square 1 is yellow\n",
"After square 1 is white\n",
"Before square 2 is green\n",
"After square 2 is white\n",
"Before square 3 is purple\n",
"After square 3 is white\n",
"Before square 4 is blue \n",
"After square 4 is white\n"
]
}
],
"source": [
"squares=['red','yellow','green','purple','blue ']\n",
"\n",
"for i in range(0,5):\n",
" print(\"Before square \",i, 'is', squares[i])\n",
" \n",
" squares[i]='white'\n",
" \n",
" print(\"After square \",i, 'is', squares[i])\n",
" \n",
" \n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Write a for loop that prints out the following list: squares=['red','yellow','green','purple','blue ']:"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"red\n",
"yellow\n",
"green\n",
"purple\n",
"blue \n"
]
}
],
"source": [
"squares=['red','yellow','green','purple','blue ']\n",
"for color in squares:\n",
" print(color)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Double-click __here__ for the solution.\n",
"<!-- \n",
"squares=['red','yellow','green','purple','blue ']\n",
"for square in squares:\n",
" print(square)\n",
" -->\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" We can access the index and the elements of a list as follows: "
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 red\n",
"1 yellow\n",
"2 green\n",
"3 purple\n",
"4 blue \n"
]
}
],
"source": [
"squares=['red','yellow','green','purple','blue ']\n",
"\n",
"for i,square in enumerate(squares):\n",
" print(i,square)\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" <a id=\"ref2\"></a>\n",
"<center><h2>While Loops</h2></center>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As you can see, the **for** loop is used for a controlled flow of repetition. However, what if we don't know when we want to stop the loop? What if we want to keep executing a code block until a certain condition is met? The **while** loop exists as a tool for repeated execution based on a condition. The code block will keep being executed until the given logical condition returns a **False** boolean value.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let’s say we would like to iterate through list **dates** and stop at the year 1973, then print out the number of iterations. This can be done with the following block of code:"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1982\n",
"1980\n",
"1973\n",
"it took 3 repetitions to get out of loop\n"
]
}
],
"source": [
"dates = [1982,1980,1973,2000]\n",
"\n",
"i=0;\n",
"year=0\n",
"while(year!=1973):\n",
" year=dates[i]\n",
" i=i+1\n",
" print(year)\n",
" \n",
" \n",
"print(\"it took \", i ,\"repetitions to get out of loop\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A while loop iterates merely until the condition in the argument is not met, as shown in the following figure :"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a ><img src = \"https://ibm.box.com/shared/static/hhe9tiskw1qqpycs4b8l2l2q58e2kn54.gif\" width = 1000, align = \"center\"></a>\n",
" <h4 align=center> An Example of indices as negative numbers\n",
"\n",
" </h4> "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Write a while loop to display the values of the Rating of an album playlist stored in the list “PlayListRatings”. If the score is less than 6, exit the loop. The list “PlayListRatings” is given by: PlayListRatings = [10,9.5,10, 8,7.5, 5,10, 10]:\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10\n",
"9.5\n",
"10\n",
"8\n",
"7.5\n"
]
}
],
"source": [
"PlayListRatings = [10,9.5,10,8,7.5,5,10,10]\n",
"i=0\n",
"rating=PlayListRatings[0]\n",
"while(rating>6):\n",
" print(rating)\n",
" i =i+1\n",
" rating=PlayListRatings[i]\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Double-click __here__ for the solution.\n",
"<!-- \n",
"PlayListRatings = [10,9.5,10, 8,7.5, 5,10, 10]\n",
"i=0;\n",
"Rating=100\n",
"while(Rating>6):\n",
" Rating=PlayListRatings[i]\n",
" i=i+1\n",
" print(Rating)\n",
" -->"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Write a while loop to copy the strings 'orange' of the list 'squares' to the list 'new_squares'. Stop and exit the loop if the value on the list is not 'orange':"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"['orange', 'orange']"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"squares=['orange','orange','purple','blue ','orange']\n",
"new_squares=[];\n",
"i=0\n",
"while(squares[i]=='orange'):\n",
" new_squares.append(squares[i])\n",
" i=i+1\n",
"new_squares"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Double-click __here__ for the solution.\n",
"<!-- \n",
"squares=['orange','orange','purple','blue ','orange']\n",
"new_squares=[];\n",
"i=0\n",
"while(squares[i]=='orange'):\n",
" new_squares.append(squares[i])\n",
" i=i+1\n",
" -->"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" <a href=\"http://cocl.us/NotebooksPython101bottom\"><img src = \"https://ibm.box.com/shared/static/irypdxea2q4th88zu1o1tsd06dya10go.png\" width = 750, align = \"center\"></a>\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# About the Authors: \n",
"\n",
" [Joseph Santarcangelo]( https://www.linkedin.com/in/joseph-s-50398b136/) has a PhD in Electrical Engineering, his research focused on using machine learning, signal processing, and computer vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Copyright &copy; 2017 [cognitiveclass.ai](https:cognitiveclass.ai). This notebook and its source code are released under the terms of the [MIT License](cognitiveclass.ai)."
]
}
],
"metadata": {
"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.6.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment