Last active
May 9, 2023 04:18
-
-
Save mGalarnyk/4a0489a5c533aacfb00e22572e1bc33f to your computer and use it in GitHub Desktop.
Python for loop tutorial for the blog post: https://medium.com/@GalarnykMichael/python-basics-7-for-loop-4ebcbd9ae3ee
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"<h1 align=\"center\"> For Loops </h1>" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"For loops are a common way to iterate over the elements of an object (in this first example, a list)<br>\n", | |
"Any object with an iterable method can be used in a for loop." | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"One unique feature of python is that code blocks are NOT surrounded by {} begin,end. Instead, python uses indentation, The lines inside a block have to be indented by a tab, or by 4 spaces, relative to the surrounding commands." | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"While this might seem unintuitive at first, it encourages writing more readable code, over time, you'd learn to love it!" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 57, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"23\n", | |
"41\n", | |
"12\n", | |
"16\n", | |
"7\n", | |
"Hi\n" | |
] | |
} | |
], | |
"source": [ | |
"# The Python for statement iterates over the members of a sequence in order,\n", | |
"# executing the block each time. \n", | |
"\n", | |
"# take the first member of the list (iterable), call it number temporarily do something with it (print it)\n", | |
"# take second member of the list (iterable), call it number temporarily do something through and so on...\n", | |
"for number in [23, 41, 12, 16, 7]: \n", | |
" print(number)\n", | |
"print('Hi')" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"### Emunerate" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"Returns a tuple containing a count for every iteration (from start which defaults to 0) and the values obtained from iterating over sequence:" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 43, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"0 steve\n", | |
"1 rachel\n", | |
"2 michael\n", | |
"3 adam\n", | |
"4 monica\n" | |
] | |
} | |
], | |
"source": [ | |
"friends = ['steve', 'rachel', 'michael', 'adam', 'monica']\n", | |
"for index, friend in enumerate(friends):\n", | |
" print(index,friend)" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"### Task" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"<b>Remove the punctuation from the text and convert the final product to a list:</b> </br>\n", | |
"\n", | |
"On a dark desert highway, cool wind in my hair Warm smell of colitas, rising up through the air Up ahead in the distance, I saw a shimmering light My head grew heavy and my sight grew dim I had to stop for the night There she stood in the doorway; I heard the mission bell And I was thinking to myself, \"This could be Heaven or this could be Hell\" Then she lit up a candle and she showed me the way" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 62, | |
"metadata": { | |
"collapsed": true | |
}, | |
"outputs": [], | |
"source": [ | |
"text = '''On a dark desert highway, cool wind in my hair Warm smell of colitas, rising up through the air Up ahead in the distance, I saw a shimmering light My head grew heavy and my sight grew dim I had to stop for the night There she stood in the doorway; I heard the mission bell And I was thinking to myself, \"This could be Heaven or this could be Hell\" Then she lit up a candle and she showed me the way'''" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 63, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"On a dark desert highway, cool wind in my hair Warm smell of colitas, rising up through the air Up ahead in the distance, I saw a shimmering light My head grew heavy and my sight grew dim I had to stop for the night There she stood in the doorway; I heard the mission bell And I was thinking to myself, \"This could be Heaven or this could be Hell\" Then she lit up a candle and she showed me the way\n" | |
] | |
} | |
], | |
"source": [ | |
"print(text)" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"Basically, any object with an iterable method can be used in a for loop. Even strings, despite not having an iterable method - but we'll not get on to that here. Having an iterable method basically means that the data can be presented in list form, where there are multiple values in an orderly fashion. " | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 65, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"On a dark desert highway cool wind in my hair Warm smell of colitas rising up through the air Up ahead in the distance I saw a shimmering light My head grew heavy and my sight grew dim I had to stop for the night There she stood in the doorway I heard the mission bell And I was thinking to myself This could be Heaven or this could be Hell Then she lit up a candle and she showed me the way\n" | |
] | |
} | |
], | |
"source": [ | |
"for char in '-.,;\\n\"\\'':\n", | |
" text = text.replace(char,' ')\n", | |
"print(text)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 9, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": [ | |
"['On',\n", | |
" 'a',\n", | |
" 'dark',\n", | |
" 'desert',\n", | |
" 'highway',\n", | |
" '',\n", | |
" 'cool',\n", | |
" 'wind',\n", | |
" 'in',\n", | |
" 'my',\n", | |
" 'hair',\n", | |
" 'Warm',\n", | |
" 'smell',\n", | |
" 'of',\n", | |
" 'colitas',\n", | |
" '',\n", | |
" 'rising',\n", | |
" 'up',\n", | |
" 'through',\n", | |
" 'the']" | |
] | |
}, | |
"execution_count": 9, | |
"metadata": {}, | |
"output_type": "execute_result" | |
} | |
], | |
"source": [ | |
"# Split converts string to list.\n", | |
"# Each item in list is split on spaces\n", | |
"text.split(' ')[0:20]" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 9, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": [ | |
"0" | |
] | |
}, | |
"execution_count": 9, | |
"metadata": {}, | |
"output_type": "execute_result" | |
} | |
], | |
"source": [ | |
"# Dont want to have non words in my list for example ''\n", | |
"# which in this case are things of zero length\n", | |
"len('')" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 66, | |
"metadata": { | |
"collapsed": true | |
}, | |
"outputs": [], | |
"source": [ | |
"# Making new list with no empty words in it\n", | |
"cleaned_list = []" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 67, | |
"metadata": { | |
"collapsed": true | |
}, | |
"outputs": [], | |
"source": [ | |
"for word in text.split(' '): \n", | |
" word_length = len(word)\n", | |
" if word_length > 0:\n", | |
" cleaned_list.append(word)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 68, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": [ | |
"['On',\n", | |
" 'a',\n", | |
" 'dark',\n", | |
" 'desert',\n", | |
" 'highway',\n", | |
" 'cool',\n", | |
" 'wind',\n", | |
" 'in',\n", | |
" 'my',\n", | |
" 'hair',\n", | |
" 'Warm',\n", | |
" 'smell',\n", | |
" 'of',\n", | |
" 'colitas',\n", | |
" 'rising',\n", | |
" 'up',\n", | |
" 'through',\n", | |
" 'the',\n", | |
" 'air',\n", | |
" 'Up']" | |
] | |
}, | |
"execution_count": 68, | |
"metadata": {}, | |
"output_type": "execute_result" | |
} | |
], | |
"source": [ | |
"cleaned_list[0:20]" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"### Continue" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"continue statement will move onto the next iteration of the loop <br>\n", | |
"continue used for ignoring certain values, but not break out of loop " | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 69, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": [ | |
"['a',\n", | |
" 'dark',\n", | |
" 'desert',\n", | |
" 'highway',\n", | |
" 'cool',\n", | |
" 'wind',\n", | |
" 'in',\n", | |
" 'my',\n", | |
" 'hair',\n", | |
" 'Warm',\n", | |
" 'smell',\n", | |
" 'of',\n", | |
" 'colitas',\n", | |
" 'rising',\n", | |
" 'up',\n", | |
" 'through',\n", | |
" 'the',\n", | |
" 'air',\n", | |
" 'Up']" | |
] | |
}, | |
"execution_count": 69, | |
"metadata": {}, | |
"output_type": "execute_result" | |
} | |
], | |
"source": [ | |
"cleaned_list = []\n", | |
"\n", | |
"for word in text.split(' '): \n", | |
" if word == '':\n", | |
" continue\n", | |
" cleaned_list.append(word)\n", | |
"cleaned_list[1:20]" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"### Break" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"break statement will completely break out of loop " | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 71, | |
"metadata": { | |
"collapsed": true | |
}, | |
"outputs": [], | |
"source": [ | |
"cleaned_list = []" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 72, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"I found the word I was looking for\n" | |
] | |
}, | |
{ | |
"data": { | |
"text/plain": [ | |
"['On', 'a', 'dark']" | |
] | |
}, | |
"execution_count": 72, | |
"metadata": {}, | |
"output_type": "execute_result" | |
} | |
], | |
"source": [ | |
"for word in text.split(' '): \n", | |
" if word == 'desert':\n", | |
" print('I found the word I was looking for')\n", | |
" break\n", | |
" cleaned_list.append(word)\n", | |
"cleaned_list" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"### Task (Introducing the range function)" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"1. Write a Python program which iterates through integers from 1 to 50 (using a for loop). For an integer that is even, append it to the list even_numbers. For an integer that is odd, append it the list odd_numbers" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 75, | |
"metadata": { | |
"collapsed": true | |
}, | |
"outputs": [], | |
"source": [ | |
"# Making empty lists to append even and odd numbers to. \n", | |
"even_numbers = []\n", | |
"odd_numbers = []\n", | |
"\n", | |
"for number in range(1,51):\n", | |
" if number % 2 == 0:\n", | |
" even_numbers.append(number)\n", | |
" else: \n", | |
" odd_numbers.append(number) " | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 76, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"Even Numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50]\n" | |
] | |
} | |
], | |
"source": [ | |
"print(\"Even Numbers: \", even_numbers)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 77, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"Odd Numbers: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]\n" | |
] | |
} | |
], | |
"source": [ | |
"print(\"Odd Numbers: \", odd_numbers)" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"### Python 2 vs Python 3 (range function differences)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 23, | |
"metadata": { | |
"collapsed": true | |
}, | |
"outputs": [], | |
"source": [ | |
"# python 2 xrange and Python 3 range are same (resembles a generator)\n", | |
"# python 2 range generates a list\n", | |
"\n", | |
"# Importance: Long lists are slow" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"<b> Range Function Reference: </b> http://pythoncentral.io/pythons-range-function-explained/" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"**if this tutorial doesn't cover what you are looking for, please leave a comment on the youtube video and I will try to cover what you are interested in. (Please subscribe if you can!)**" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"https://youtu.be/8fswDyk9UIY" | |
] | |
} | |
], | |
"metadata": { | |
"anaconda-cloud": {}, | |
"kernelspec": { | |
"display_name": "Python [conda env:py36]", | |
"language": "python", | |
"name": "conda-env-py36-py" | |
}, | |
"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.1" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should also know that in Python, iterating over integer indices is bad style, and also slower than the alternative. If you just want to look at each of the items in a list or dict, loop directly through the list or dict.