{"id":11438,"date":"2016-03-21T12:07:24","date_gmt":"2016-03-21T10:07:24","guid":{"rendered":"http:\/\/www.webcodegeeks.com\/?p=11438"},"modified":"2018-06-20T16:29:53","modified_gmt":"2018-06-20T13:29:53","slug":"python-tutorial-beginners","status":"publish","type":"post","link":"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/","title":{"rendered":"Python Tutorial for Beginners"},"content":{"rendered":"<p>Let&#8217;s talk about <strong>Python<\/strong>. If you want to learn Python from scratch, this tutorial will be a good read for you.<\/p>\n<p>By using Python 3.4.3 (which you can download <a href=\"https:\/\/www.python.org\/downloads\/release\/python-343\/\">here<\/a>), we&#8217;ll see the basics of this awesome language.<\/p>\n<p>This tutorial expects you to have some basic knowledge of programming. And knowing any other language will be a big plus.<\/p>\n<p>[ulp id=&#8217;R7QVpFMZmjosABLC&#8217;]<\/p>\n<div class=\"toc\">\n<h3>Table Of Contents<\/h3>\n<dl>\n<dt><a href=\"#whatispython\">1. What is Python?<\/a><\/dt>\n<dt><a href=\"#thecode\">2. The code<\/a><\/dt>\n<dt><a href=\"#variables\">3. Variables<\/a><\/dt>\n<dt><a href=\"#datastructures\">4. Data Structures<\/a><\/dt>\n<dd>\n<dl>\n<dt><a href=\"#lists\">4.1. Lists<\/a><\/dt>\n<\/dl>\n<dl>\n<dt><a href=\"#tuples\">4.2. Tuples<\/a><\/dt>\n<\/dl>\n<dl>\n<dt><a href=\"#sets\">4.3. Sets<\/a><\/dt>\n<\/dl>\n<dl>\n<dt><a href=\"#dicts\">4.4. Dictionaries<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dt><a href=\"#typesandops\">5. Python Types and Operators<\/a><\/dt>\n<dd>\n<dl>\n<dt><a href=\"#bools\">5.1. Booleans<\/a><\/dt>\n<\/dl>\n<dl>\n<dt><a href=\"#numbers\">5.2. Numbers<\/a><\/dt>\n<\/dl>\n<dl>\n<dt><a href=\"#str\">5.3. Strings<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dt><a href=\"#flowcontrols\">6. Flow Control Tools<\/a><\/dt>\n<dt><a href=\"#functions\">7. Functions<\/a><\/dt>\n<dt><a href=\"#classes\">8. Classes<\/a><\/dt>\n<dt><a href=\"#practice\">9. A Little Practice<\/a><\/dt>\n<dt><a href=\"#download\">10. Download the Code Project<\/a><\/dt>\n<\/dl>\n<\/div>\n<h2><a name=\"whatispython\"><\/a>1. What is Python?<\/h2>\n<p><strong>Python<\/strong> is a high-level, object oriented, interpreted programming language. It was created by Guido van Rossum, and its source code is available under the GNU General Public License.<\/p>\n<p>It&#8217;s a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to big web applications and even games.<\/p>\n<p>This language has a lot of awesome features:<\/p>\n<ul>\n<li>It&#8217;s easy to learn, as there are few keywords and it has a simple structure and a clearly defined syntax.<\/li>\n<li>It&#8217;s easy to read, as Python code is more clearly defined and visible to the eyes.<\/li>\n<li>Its code is fairly easy to maintain.<\/li>\n<li>It has a broad standard library that is very portable and cross-platform compatible with UNIX, Windows and Macintosh.<\/li>\n<li>It has an interactive mode which allows interactive testing and debugging of snippets of code.<\/li>\n<li>It can run on a wide variety of hardware platforms and has the same interface on all platforms.<\/li>\n<li>You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient.<\/li>\n<li>Python provides interfaces to all major commercial databases.<\/li>\n<li>Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix.<\/li>\n<li>Python provides a better structure and support for large programs than shell scripting.<\/li>\n<\/ul>\n<p>Also, it supports functional programming, which is a huge plus for me at least, and it can be used as a scripting language or be compiled to build big applications too.<\/p>\n<p>It provides high-level dynamic data types and supports dynamic type checking. It also supports automatic garbage collection.<\/p>\n<p>Python has a lot of implementations, but the default and most used across all platforms is CPython, as this is the one you download from <a href=\"python.org\">python.org<\/a>. It&#8217;s the Python interpreter most used right now, despite one big issue it has: The <strong>Global Interpreter Lock (GIL)<\/strong>.<\/p>\n<p>The GIL is a mutex that prevents multiple native threads from executing Python bytecodes at once. This lock is necessary mainly because CPython&#8217;s memory management is not thread-safe. This means that, although you can do multi-threading with Python, the threads will not actually run in parallel, but synchronized instead. This makes Python (when running on CPython implementation) a <strong>single-thread<\/strong> programming language.<\/p>\n<p>Enough with the introduction to Python, if you are still reading it means that you are actually interested in this language so, let&#8217;s get on with it.<\/p>\n<h2><a name=\"thecode\"><\/a>2. The code<\/h2>\n<p>The code in python is mainly written in *.py files. Let&#8217;s give it a try writing a <em>hello world<\/em> application.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>hello_world.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">print(\"Hello World!\")\r\n<\/pre>\n<p>We can run this program by executing on bash the command: <code>python3 hello_world.py<\/code>. We&#8217;ll see:<\/p>\n<pre class=\"brush:bash\">$ python3 hello_world.py\r\nHello World!\r\n<\/pre>\n<p>But this is not the only way to run Python scripts, if you add the shebang line and give the file execution permissions, like this:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>hello_world<\/em><\/span><\/p>\n<pre class=\"brush:bash\">#!\/usr\/bin\/python3\r\n\r\nprint(\"Hello World!\")\r\n<\/pre>\n<p>You can do something like this:<\/p>\n<pre class=\"brush:bash\">$ .\/hello_world\r\nHello World!\r\n<\/pre>\n<p>So, there it is. You&#8217;ve written some Python.<\/p>\n<h2><a name=\"variables\"><\/a>3. Variables<\/h2>\n<p>Now, in almost every program, you need to store values somewhere for later processing. You may have some process that returns an exit code, and you want to do some stuff according to the resulting exit code. In that case you surely want to save that exit code in a <strong>variable<\/strong>.<\/p>\n<p>Variables are reserved memory locations to store values, that means that whenever you define a variable you reserve some memory for whatever you are going to store in it.<\/p>\n<p>In Python, you don&#8217;t need to explicitly define variables to reserve the memory. The declaration happens automatically when you assign a value to it with the equals sign (=).<\/p>\n<p>So, basically, when you are doing <code>variable = value<\/code>, you are doing two things there. You are reserving memory enough to store the value, and you are storing the value there. Let&#8217;s see it on practice:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>variables.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">my_integer = 1000\r\nmy_decimal = 10.9\r\nmy_string = \"Hi!\"\r\n\r\nprint(my_integer)\r\nprint(my_decimal)\r\nprint(my_string)\r\n<\/pre>\n<p>Here, we are defining three variables. An integer, a decimal and a string. As you can see, we are not explicitly telling the interpreter the type of the variables, as it dynamically infers it from the values.<\/p>\n<p>Then we are printing each of them, and when we run this script will see:<\/p>\n<pre class=\"brush:bash\">python3 variables.py\r\n1000\r\n10.9\r\nHi!\r\n<\/pre>\n<p>I&#8217;ll use this opportunity to introduce you to a very useful feature Python (but not only Python) has, <strong>built-in functions<\/strong>.<\/p>\n<p>Built-In Functions are functions provided by the language that are available everywhere. Throughout this example we&#8217;ll see some of the most used built-in functions. Here we&#8217;ll talk about <code>type<\/code>.<\/p>\n<p>As Python has dynamic type inference, we sometimes can&#8217;t be sure of the type of a variable by just seeing the code. Passing a variable as argument to the <code>type<\/code> function, it will return the class of the provided variable. Let&#8217;s see:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>variables.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">my_integer = 1000\r\nmy_decimal = 10.9\r\nmy_string = \"Hi!\"\r\n\r\nprint(my_integer)\r\nprint(type(my_integer))\r\n\r\nprint(my_decimal)\r\nprint(type(my_decimal))\r\n\r\nprint(my_string)\r\nprint(type(my_string))\r\n<\/pre>\n<p>We are now printing the type of the variables below their values. When we run it:<\/p>\n<pre class=\"brush:bash\">python3 variables.py\r\n1000\r\n&lt;class 'int'&gt;\r\n10.9\r\n&lt;class 'float'&gt;\r\nHi!\r\n&lt;class 'str'&gt;\r\n<\/pre>\n<p>There you see. Our integer variable type is <code>int<\/code>, the decimal&#8217;s is <code>float<\/code> and the string&#8217;s is <code>str<\/code>.<\/p>\n<p>There are also built-in functions for casting purposes. When you want the string representation of an integer you can write <code>str(my_integer_value)<\/code>, and it will output what you need. It works for all types (<code>int<\/code>, <code>float<\/code>, etc.).<\/p>\n<p>Now, we have some understanding of variables. Let&#8217;s jump to&#8230;<\/p>\n<h2><a name=\"datastructures\"><\/a>4. Data Structures<\/h2>\n<p>Python provides some data structures that makes value storing a lot more easy. Available data structures are: <code>lists<\/code>, <code>tuples<\/code>, <code>sets<\/code> and <code>dictionaries<\/code>.<\/p>\n<p>This section will make an introduction to all data structures in Python, but will see how to work with them in a more advanced way when we get to iterations and decisions.<\/p>\n<h3><a name=\"lists\"><\/a>4.1. Lists<\/h3>\n<p>Lists are a way to group together other values. A list is a sorted array of values, written as a list of coma separated values between two square brackets like:<\/p>\n<pre class=\"brush:python\">my_list = [1, 2, 3, 4]\r\n<\/pre>\n<p>Of course, to define an empty list we just write <code>[]<\/code> (empty square brackets). Also, lists may contain items of different types as in <code>[\"a string\", 1, 2.0]<\/code>, but usually the items will be all of the same type.<\/p>\n<p>Of course, data structures can contain each other, so a list of lists is actually possible as in <code>[[1,2,3], [3,4], [\"asd\", \"qwe]]<\/code>.<\/p>\n<p>Lists are indexed, to access an item within one we just need to write something like <code>my_list[1]<\/code>, and this will return the second element of our list. Yes, the second element, lists&#8217; indexes, in good languages, start at 0 (let the hate begin, but you are wrong if you think otherwise :P).<\/p>\n<p>Also, to put an element into a list we can either assign it to the index as in <code>my_list[1] = \"a value\"<\/code>, or we can append it as in <code>my_list.append(\"a value\")<\/code>. The first option is often a bad idea, as the index must exist first to assign something to it, let&#8217;s see:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>index_out_of_bounds.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">my_list = [1, 2, 3]\r\n\r\nprint(str(my_list))\r\n\r\nmy_list.append(4)\r\n\r\nmy_list[2] = 5\r\n\r\nprint(str(my_list))\r\n\r\nmy_list[4] = 2\r\n<\/pre>\n<p>Here we are defining a list of three elements and printing it. Then we append a fourth element, <strong>replace<\/strong> the third and print again. And then we are assigning something to the fifth element, <strong>BUT<\/strong> the fifth element does not yet exist in the array, let&#8217;s see what happens:<\/p>\n<pre class=\"brush:bash\">$ python3 index_out_of_bounds.py\r\n[1, 2, 3]\r\n[1, 2, 5, 4]\r\nTraceback (most recent call last):\r\n  File \"index_out_of_bounds.py\", line 11, in &lt;module&gt;\r\n    my_list[4] = 2\r\nIndexError: list assignment index out of range\r\n<\/pre>\n<p>That <em>&#8220;IndexError: list assignment index out of range&#8221;<\/em> is a Python exception, telling us that we are assigning an element to an index of the array that wasn&#8217;t defined yet. Which takes us to our first reserved words in Python: <code>try-except<\/code>.<\/p>\n<p>Imagine we want to replace an element if it exists, but if it doesn&#8217;t we don&#8217;t want to do anything. There are better ways than the one explained below, but I want you to see how try-except works.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>replaces_if_exists.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">my_array = [1, 2, 3]\r\n\r\ntry:\r\n    my_array[3] = 4\r\nexcept IndexError:\r\n    print(\"element did not exist. ignoring.\")\r\n<\/pre>\n<p>Here we define a list of three elements again, and want to replace the fourth (which does not yet exist). If an <code>IndexError<\/code> is thrown, the except clause will execute the block of code within it. Let&#8217;s see:<\/p>\n<pre class=\"brush:python\">$ python3 replaces_if_exists.py\r\nelement did not exist. ignoring.\r\n<\/pre>\n<p>That is one way of doing error handling in Python.<\/p>\n<p>Now, you also may want to delete an item of a list, and here we meet another keyword: <code>del<\/code>. Let&#8217;s imagine we need to remove the las element of an array, but we don&#8217;t know its length. Here comes another built-in function: <code>len<\/code>.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>remove_last_element.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">my_list = [1, 2, 3]\r\n\r\ndel my_list[len(my_list) - 1]\r\n\r\nprint(my_list)\r\n<\/pre>\n<p>Here we define a list with three items in it, but we treat it as if we didn&#8217;t know its length. By using <code>len(my_list)<\/code> we get its length (three), so by subtracting one we get the last index (two). Applying <code>del<\/code> to that index of our list will remove it. When we run this script:<\/p>\n<pre class=\"brush:bash\">python3 remove_last_element.py\r\n[1, 2]\r\n<\/pre>\n<p>Now we know how to define arrays, add items to them, retrieve those items, delete them and even get their length. Of course, more advanced ways of working with them will be described later. Let&#8217;s skip to the next data structure.<\/p>\n<h3><a name=\"tuples\"><\/a>4.2. Tuples<\/h3>\n<p>Tuples are a very simple, yet useful, data structure in python. They behave a lot like lists, but they are immutable, which means that they can not be modified after declaration. They also support nesting (a tuple can be present within another tuple).<\/p>\n<p>Tuples are defined almost like a list, but without the brackets as in <code>my_tuple = 1, 2, \"a string\", 4.5<\/code>. They are also indexed, which means that providing an index within square brackets will return an element in that position (as always, the first index is zero). The built-in function <code>len<\/code> is also available here.<\/p>\n<p>Let&#8217;s see a little example:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>tuples_basic.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">my_tuple = 1, \"a string\", 3.5\r\n\r\nprint(str(my_tuple[0]))\r\n\r\ntry:\r\n    del my_tuple[1]\r\nexcept TypeError:\r\n    print(\"tuples are immutable. can't remove\")\r\n\r\ntry:\r\n    my_tuple[1] = 3\r\nexcept TypeError:\r\n    print(\"tuples are immutable. can't assign\")\r\n\r\nprint(str(my_tuple))\r\n<\/pre>\n<p>Here we define a tuple of three elements, print the first one, delete the second and replacing the second. The last two operations are within a try-except to show you that tuples are immutable. Then we print the whole tuple.<\/p>\n<pre class=\"brush:bash\">$ python3 tuples\/tuples_basic.py\r\n1\r\ntuples are immutable. can't remove\r\ntuples are immutable. can't assign\r\n(1, 'a string', 3.5)\r\n<\/pre>\n<p>Of course, as in lists, tuples maintain the order of the elements in which they were defined. You might think that this is pretty obvious for any data structure but we will see that it isn&#8217;t.<\/p>\n<h3><a name=\"sets\"><\/a>4.3. Sets<\/h3>\n<p>A set is an unordered collection with no duplicate elements. As it is unordered, it is not indexed, which means that the access and assignment we saw with lists will not be available with sets. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.<\/p>\n<p>Curly braces or the set() function can be used to create sets. To create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss below.<\/p>\n<p>Let&#8217;s see a simple example on sets:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>tuples_basic.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">my_set = {\"a string\", 2, \"another string\"}\r\nprint(str(my_set))\r\n\r\nmy_set.add(3.5)\r\nprint(str(my_set))\r\n\r\nprint(str(my_set.pop()))\r\nprint(str(my_set))\r\n\r\nprint(str(my_set.pop()))\r\nprint(str(my_set))\r\n\r\nprint(str(my_set.pop()))\r\nprint(str(my_set))\r\n\r\nprint(str(my_set.pop()))\r\nprint(str(my_set))\r\n<\/pre>\n<p>In this script we are defining a set, adding an element, and then popping out elements. The method <code>pop<\/code> in sets, returns an element, removing it from the set. We are printing the set after every operation. The output:<\/p>\n<pre class=\"brush:bash\">$ python3 sets\/sets_basic.py\r\n{'a string', 2, 'another string'}\r\n{'a string', 2, 3.5, 'another string'}\r\na string\r\n{2, 3.5, 'another string'}\r\n2\r\n{3.5, 'another string'}\r\n3.5\r\n{'another string'}\r\nanother string\r\nset()\r\n<\/pre>\n<p>Here we can see a couple of things going on. First, to add an element to the set we don&#8217;t use append as in our lists, we use <code>add<\/code>, and as we see, the element is added in any position, not the last nor the first.<\/p>\n<p>Now we&#8217;ll talk about the operations we said it supports earlier: union, intersection, difference, and symmetric difference.<\/p>\n<ul>\n<li>Union between two sets should return another set containing all the elements that are present in those sets. In other words, union between a set <code>a<\/code> containing <code>{1,2,3}<\/code> and a set <code>b<\/code> containing <code>{3,4,5}<\/code> should return another set containing <code>{1,2,3,4,5}<\/code>.<\/li>\n<li>Intersection between two sets should return another set containing all the elements that are present in <strong>both<\/strong> involved sets. In other words, intersection between a set <code>a<\/code> containing <code>{1,2,3}<\/code> and a set <code>b<\/code> containing <code>{3,4,5}<\/code> should return another set containing <code>{3}<\/code>.<\/li>\n<li>Difference between two sets should return a set containing all the elements that are present in the first but not in the second. In other words, difference between a set <code>a<\/code> containing <code>{1,2,3}<\/code> and a set <code>b<\/code> containing <code>{3,4,5}<\/code> should return another set containing <code>{1,2}<\/code>.<\/li>\n<li>Symmetric difference between two sets should return a set containing all the elements that are not present in both sets. In other words, symmetric difference between a set <code>a<\/code> containing <code>{1,2,3}<\/code> and a set <code>b<\/code> containing <code>{3,4,5}<\/code> should return another set containing <code>{1,2,4,5}<\/code>.<\/li>\n<\/ul>\n<p>Now, let&#8217;s talk about a couple things all these data structures support before going on with an example. The keyword <code>in<\/code> and the fact that strings are, in fact, some kind of data structure.<\/p>\n<p>The keyword <code>in<\/code> provides a way of seeing if an item is present within some of these data structures. If we define an array like <code>my_list = [1,2,3]<\/code> and then evaluate the expression <code>2 in my_list<\/code>, we&#8217;ll get the boolean value <code>True<\/code>. It&#8217;s an easy and convenient way of checking whether an element is in an array or not.<\/p>\n<p>Another thing to notice, is the resemblance of the behavior of string and arrays. As in any other language (at least every one I know of), string are actually arrays of chars. This means that the built-in function <code>len<\/code> and the keyword <code>in<\/code> also works in string. Also, strings are indexed sequences, so <code>\"hello\"[2]<\/code> will work and return <code>'l'<\/code>.<\/p>\n<p>Now we&#8217;ll see some weird things, but I&#8217;ll explain them all after the example.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>tuples_basic.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">a = set(\"abcdef\")\r\nb = {\"b\", \"d\", \"g\", \"h\"}\r\n\r\nprint(\"a: \" + str(a))\r\nprint(\"b: \" + str(b))\r\n\r\nunion = a.union(b)\r\nintersection = a.intersection(b)\r\ndifference = a.difference(b)\r\nsymmetric_difference = a.symmetric_difference(b)\r\n\r\nprint(\"union: \" + str(union))\r\nprint(\"intersection: \" + str(intersection))\r\nprint(\"difference: \" + str(difference))\r\nprint(\"symmetric difference: \" + str(symmetric_difference))\r\n\r\nprint(\"a in union: \" + str(\"a\" in union))\r\nprint(\"b in difference: \" + str(\"b\" in difference))\r\n<\/pre>\n<p>The output:<\/p>\n<pre class=\"brush:bash\">$ python3 sets\/set_operations.py\r\na: {'d', 'b', 'f', 'c', 'e', 'a'}\r\nb: {'g', 'h', 'd', 'b'}\r\nunion: {'g', 'b', 'f', 'c', 'e', 'd', 'h', 'a'}\r\nintersection: {'d', 'b'}\r\ndifference: {'e', 'f', 'a', 'c'}\r\nsymmetric difference: {'g', 'f', 'c', 'e', 'h', 'a'}\r\na in union: True\r\nb in difference: False\r\n<\/pre>\n<p>Now, what is going on there? We are instantiating two sets. One using the built in function <code>set<\/code>, which receives any of the data structures mentioned here (and more) as argument and returns a set with the contained elements. This built-in function belongs to a group of functions that instantiate these data structures from another data structure, like <code>list<\/code> which receives any iterable and builds a list with its content.<\/p>\n<p>The second set is being built with the literal (values separated by commas within curly braces). Then we are printing them, doing some operations and printing the results too.<\/p>\n<p>Also, we are checking if the strings &#8220;a&#8221; and &#8220;b&#8221; are present in the union and difference respectively. As a result you can see that <code>True<\/code> is returned for <code>\"a\" in union<\/code> and <code>False<\/code> is being returned for <code>\"b\" in difference<\/code>. Here you see, besides the use of the <code>in<\/code> keyword, an example of boolean values in Python.<\/p>\n<p>Keep in mind that any value can be tested for a boolean value. Every value in the below list, will evaluate to false:<\/p>\n<ul>\n<li>None (The <code>null<\/code> of Python if you want)<\/li>\n<li>False (The <code>False<\/code> boolean value)<\/li>\n<li>Zero (For any numeric type, for example, <code>0<\/code>, <code>0.00<\/code>, etc.)<\/li>\n<li>Any empty sequence (<code>''<\/code>, <code>[]<\/code>, <code>{}<\/code>, etc.)<\/li>\n<li>Instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False (We&#8217;ll talk about this in a couple sections).<\/li>\n<\/ul>\n<p>Now we have a good understanding on sets, let&#8217;s move on to&#8230;<\/p>\n<h3><a name=\"dicts\"><\/a>4.4. Dictionaries<\/h3>\n<p>Dictionaries in Python are data structures that optimize element lookups by associating keys to values. You could say that dictionaries are arrays of (key, value) pairs, where the keys can be of any immutable type (strings, numbers, etc.).<\/p>\n<p>The syntax is somewhat familiar to any one that has worked with REST services or JavaScript applications, as they look a lot like JSON. An object starts and ends in curly braces, each pair is separated by a comma, and the (key, value) pairs are associated through a colon (:). Let&#8217;s see an example:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>dictionary_def.py<\/em><\/span><\/p>\n<pre class=\"brush:bash\">my_dictionary = {\r\n    \"a key\": \"a value\",\r\n    \"another key with numeric value\": 3.6,\r\n    True: \"A boolean as a key\",\r\n    5: \"An int as a key\"\r\n}\r\nprint(str(my_dictionary))\r\n<\/pre>\n<p>See? It&#8217;s a JSON. And the string representation looks the same when we print it, as in any other sequence:<\/p>\n<pre class=\"brush:bash\">$ python3 dictionaries\/dictionary_def.py\r\n{True: 'A boolean as a key', 'a key': 'a value', 5: 'An int as a key', 'another key with numeric value': 3.6}\r\n<\/pre>\n<p>Now, the keys of a dictionary are not ordered. We&#8217;ll make a little experiment when we get to iterations. Also, they are unique, a key can not be present twice in the same dictionary. If we open the intepreter running <code>$ python3<\/code> in our shell we can do something like:<\/p>\n<pre class=\"brush:python\">$ python3\r\nPython 3.4.3 (default, Oct 14 2015, 20:28:29)\r\n[GCC 4.8.4] on linux\r\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\r\n&gt;&gt;&gt; a = {\"key\": \"value\", \"key\": \"value2\"}\r\n&gt;&gt;&gt; print(str(a))\r\n{'key': 'value2'}\r\n<\/pre>\n<p>On the result, the key <code>'key'<\/code> is only present one with the last value we assigned to it.<\/p>\n<p>Now, we&#8217;ve got two ways of accessing dictionaries in Python: using square brackets providing the key, or using the method <code>get<\/code>. The later is the best approach most of the times, let&#8217;s talk about why.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>access.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">my_dict = {\r\n    \"name\": \"Sebastian\",\r\n    \"age\": 21\r\n}\r\n\r\nprint(str(my_dict.get(\"name\")))\r\nprint(str(my_dict[\"name\"]))\r\nprint(str(my_dict.get(\"key that does not exist\")))\r\nprint(str(my_dict[\"key that does not exist\"]))\r\n<\/pre>\n<p>We are creating a dictionary with my name and my age, and then retrieving the name using both of the ways we talked about. This will work just fine as the key is present in our dictionary, but when we try to access a <em>key that does not exist<\/em>, well let&#8217;s see the output:<\/p>\n<pre class=\"brush:bash\">$ python3 dictionaries\/access.py\r\nSebastian\r\nSebastian\r\nNone\r\nTraceback (most recent call last):\r\n  File \"dictionaries\/access.py\", line 9, in &lt;module&gt;\r\n    print(str(my_dict[\"key that does not exist\"]))\r\nKeyError: 'key that does not exist'\r\n<\/pre>\n<p>A <code>KeyError<\/code> is raised when we try to gain access to a key that doesn&#8217;t exist with the square brackets. The line before the error says <code>None<\/code>, in my opinion every alternative that does not raise an error is better.<\/p>\n<p>In programming I think that errors should be treated as that, as errors, we should not use them to control the flow of an application but as exceptions that should not happen and we should recover from them.<\/p>\n<p>If we know a key might not be present when treating with a dictionary, I think we should use <code>None<\/code> to represent an absent key, instead of an ugly <code>KeyError<\/code>. Again, that&#8217;s just how I think.<\/p>\n<p>Dictionaries are mutable, that means that we can modify them. We can replace values assigned to keys, delete key-value pairs and add new ones. The replacement and addition are made the same way, by assigning the value to a key within square brackets, like <code>my_dict[\"key\"] = \"new value\"<\/code>. If a &#8220;key&#8221; exists, then replaces its value with &#8220;new value&#8221;, else it creates it and assigns it.<\/p>\n<p>To delete a key we use, as in lists, the keyword <code>del<\/code>, as in <code>del my_dickt[\"key\"]<\/code>. Let&#8217;s see an example of this:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>write_dictionary.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">my_dog = {\r\n    \"breed\": \"German Shepperd\",\r\n    \"name\": \"Qwerty\",\r\n    \"age\": 9,\r\n    \"gender\": \"MALE\"\r\n}\r\n\r\nprint(str(my_dog))\r\n\r\nmy_dog[\"age\"] = my_dog.get(\"age\", 0) + 1\r\nmy_dog[\"girlfriend_name\"] = \"Quiara\"\r\n\r\nprint(str(my_dog))\r\n\r\ndel my_dog[\"girlfriend_name\"]\r\n\r\nprint(str(my_dog))\r\n<\/pre>\n<p>Here we are defining&#8230; my dog, and then printing it. Then he turned ten and got a girlfriend, and then his girlfriend moved to another city.<\/p>\n<p>What is really happening is that we are defining a dictionary, overriding a key (adding one to it if it exists), creating another key and then deleting it. Here is an example of how to operate with numbers, which we&#8217;ll see more in detail soon.<\/p>\n<p>Where we add one to the age, we are providing a second argument to the method <code>get<\/code>, that is a default value if the key does not exist. In this case this will not happen, but I wanted you to see that this could be done.<\/p>\n<p>Now, the keyword <code>in<\/code> works with dictionaries too, it checks if a key exists. In the previous example, the default age thing could be implemented using it, let&#8217;s modify the script to do it:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>write_dictionary.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">my_dog = {\r\n    \"breed\": \"German Shepperd\",\r\n    \"name\": \"Qwerty\",\r\n    \"age\": 9,\r\n    \"gender\": \"MALE\"\r\n}\r\n\r\nprint(str(my_dog))\r\n\r\nif \"age\" in my_dog:\r\n    my_dog[\"age\"] += 1\r\nelse:\r\n    my_dog[\"age\"] = 1\r\n\r\nmy_dog[\"girlfriend_name\"] = \"Quiara\"\r\n\r\nprint(str(my_dog))\r\n\r\ndel my_dog[\"girlfriend_name\"]\r\n\r\nprint(str(my_dog))\r\n<\/pre>\n<p>Hey! You&#8217;ve just saw an if-else there! This is an easy way of safely using the square brackets notation, but let&#8217;s explain the if-else before we dive into it. The syntax is pretty simple:<\/p>\n<pre class=\"brush:python\">if condition:\r\n    action\r\nelif another condition:\r\n    another action\r\nelif another condition:\r\n    another action\r\n...\r\nelse:\r\n    action if none of the above conditions is met\r\n<\/pre>\n<p>We&#8217;ll see how to make decisions deeper later. So, in the example we are checking if age exists, if it does we add one and if it doesn&#8217;t we assign one to it. Pretty simple, it&#8217;s kind of the same thing the method <code>get<\/code> does for us.<\/p>\n<p>The <code>len<\/code> built-in function also works with dictionaries, it will return the amount of key-value pairs it contains. It also provides some methods that, later, will help us iterate over dictionaries more easily.<\/p>\n<p>This is all about data structures for now, we&#8217;ll soon jump into flow control tools so we can make something more interesting with python, but before we jump into it (I know, but we need to), we have to talk a little bit about operators and dig deeper into Python types.<\/p>\n<h2><a name=\"typesandops\"><\/a>5. Python Types and Operators<\/h2>\n<p>In this section we&#8217;ll talk about, mainly, three data types: <code>boolean<\/code>, <code>string<\/code> and <code>number<\/code>.<\/p>\n<p>As we said before, we never tell Python the type of a variable (at least not explicitly), it infers it from the value we are assigning to it. When we assign <code>1<\/code> to a variable, Python automatically defines that variable as <code>int<\/code>, as it is the simplest type that can contain the value you are trying to assign. But, although the language is able to tell the types you are handling, you should too, as it will help you debug your code more easily.<\/p>\n<h3><a name=\"bools\"><\/a>5.1. Booleans (<code>bool<\/code>)<\/h3>\n<p>Booleans, or bool values, are logical values that can be either <code>True<\/code> or <code>False<\/code>. They are immutable and support some useful operators:<\/p>\n<ul>\n<li><code>and<\/code>: Given two bool values <code>a<\/code> and <code>b<\/code>, the expression <code>a and b<\/code> will evaluate to <code>True<\/code> if both of them are true. It will be <code>False<\/code> otherwise.<\/li>\n<li><code>or<\/code>: Given two bool values <code>a<\/code> and <code>b<\/code>, the expression <code>a or b<\/code> will evaluate to <code>True<\/code> if at least one of them is true. It will be <code>False<\/code> otherwise.<\/li>\n<li><code>not<\/code>: Given a bool value <code>a<\/code>, the expression <code>not a<\/code> will evaluate to <code>True<\/code> if <code>a<\/code> is <code>False<\/code>. It will be <code>False<\/code> otherwise.<\/li>\n<\/ul>\n<p>Let&#8217;s do a couple of exercises with the interpreter:<\/p>\n<pre class=\"brush:python\">$ python3\r\nPython 3.4.3 (default, Oct 14 2015, 20:28:29)\r\n[GCC 4.8.4] on linux\r\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\r\n&gt;&gt;&gt; a = True\r\n&gt;&gt;&gt; b = False\r\n&gt;&gt;&gt; a and b\r\nFalse\r\n&gt;&gt;&gt; a or b\r\nTrue\r\n&gt;&gt;&gt; not a and b\r\nFalse\r\n&gt;&gt;&gt; not (a and b)\r\nTrue\r\n&gt;&gt;&gt;\r\n<\/pre>\n<p>So, here we have two bool values, a and b, and test our logical operators. As you see in the operations involving <code>not<\/code>, you can combine them, but you have to use a combination of parentheses to be sure that you are actually doing the operations you want to do.<\/p>\n<p>Now, Python also provides <strong>comparators<\/strong>, which gives us a way of comparing values resulting in booleans. Available comparators are:<\/p>\n<ul>\n<li><code>&lt;<\/code>: Strictly less than. (4 &lt; 2 = False, 10 &lt; 30 = True)<\/li>\n<li><code>&lt;=<\/code>: Less than or equal. (4 &lt;= 4 = True, 5 &lt;= 9 = True, 5 &lt;= 2 = False)<\/li>\n<li><code>&gt;<\/code>: Strictly greater than. (4 &gt; 2 = True, 4 &gt; 5 = False)<\/li>\n<li><code>&gt;=<\/code>: Greater than or equal. (4 &gt;= 4 = True, 5 &gt;= 9 = False, 5 &gt;= 2 = True)<\/li>\n<li><code>==<\/code>: Equals. (4 == 4 = True, 5 == 4 = False)<\/li>\n<li><code>!=<\/code>: Not Equals. (4 != 4 = False, 5 != 4 = True)<\/li>\n<li><code>is<\/code>: Object identity. (4 is 4 = True, 4 is 5 = False, 4 is None = False)<\/li>\n<li><code>is not<\/code>: Negated object identity. (4 is not 4 = False, 4 is not 5 = True, 4 is not None = True)<\/li>\n<\/ul>\n<p>With this comparators and the logical operators we can do now pretty useful stuff. Let&#8217;s see an example:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>comparators.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">a = 5\r\nb = 3\r\nc = 2\r\n\r\n# True\r\nprint(a &gt; b &gt; c)\r\nprint(a &gt;= c)\r\nprint(a &gt; b &gt; c &lt; a)\r\nprint(a == b or c &lt; b)\r\nprint(not (a == b and c &gt;= a))\r\nprint(b != c)\r\nprint(a is not None)\r\n\r\nprint(\"-----------------\")\r\n\r\n# False\r\nprint(a &lt; b &lt; c)\r\nprint(b &gt; 10)\r\nprint(b is None and a != 5)\r\nprint(not a)\r\n<\/pre>\n<p>The output:<\/p>\n<pre class=\"brush:bash\">$ python3 data-types\/comparators.py\r\nTrue\r\nTrue\r\nTrue\r\nTrue\r\nTrue\r\nTrue\r\nTrue\r\n-----------------\r\nFalse\r\nFalse\r\nFalse\r\nFalse\r\n<\/pre>\n<p>Here you see stuff like <code>a &gt; b &gt; c &lt; a<\/code>, comparators have all the same priority, so this is like <code>a &gt; b and b &gt; c and c &lt; a<\/code>. The other operations are just combinations of the stuff we saw recently. Let&#8217;s jump into numbers now.<\/p>\n<h3><a name=\"numbers\"><\/a>5.2. Numbers (<code>int<\/code>, <code>float<\/code>, <code>long<\/code>, <code>complex<\/code>)<\/h3>\n<p>There are four distinct numeric types: plain integers (<code>int<\/code>), long integers (<code>long<\/code>), floating point numbers (<code>float<\/code>), and complex numbers (<code>complex<\/code>).<\/p>\n<p>Python provides operators that are very similar to the ones available in other languages. Sum (+), difference (-), product (*), quotient (\/), floored quotient (\/\/), remainder (%) and power (**). There are also some built-in functions that let us do some other operations, like <code>abs<\/code> which returns the absolute value of magnitude of a number provided as argument, or <code>divmod<\/code>, which receives two numbers, a and b, and returns a pair containing <code>a \/\/ b<\/code> and <code>a % b<\/code>.<\/p>\n<p>Let&#8217;s see some operations at work:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>operations.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">a = 10\r\nb = 7\r\n\r\nsum = a + b\r\ndiff = a - b\r\nproduct = a * b\r\nquotient = a \/ b\r\nfloored_quotient = a \/\/ b\r\nremainder = a % b\r\n\r\nprint(sum)\r\nprint(diff)\r\nprint(product)\r\nprint(quotient)\r\nprint(floored_quotient)\r\nprint(remainder)\r\n\r\nprint(abs(b - a))\r\nprint(int(a \/ b))\r\nprint(complex(0.3, 5) - complex(1, 2))\r\n<\/pre>\n<p>Here we see some of the operations we talked about, in the output we can see the results:<\/p>\n<pre class=\"brush:bash\">$ python3 data-types\/operations.py\r\n17\r\n3\r\n70\r\n1.4285714285714286\r\n1\r\n3\r\n3\r\n1\r\n(-0.7+3j)\r\n<\/pre>\n<p>The operators in python respect the priorities we learnt in math, as in <code>a + b * c<\/code> behaves as <code>a + (b * c)<\/code>. Now, let&#8217;s talk about strings.<\/p>\n<h3><a name=\"str\"><\/a>5.3. Strings (<code>str<\/code>)<\/h3>\n<p>As we talked before, string are arrays of characters. They behave a lot like lists, but they are immutable. This means that doing <code>\"hel\" in \"hello\"<\/code> will work and will return true, that doing <code>\"hello\"[1]<\/code> will work and return &#8220;e&#8221; and that doing <code>len(\"hello\")<\/code> will work and return 5.<\/p>\n<p>Let&#8217;s do some operations with strings so we can see how they behave:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>string_ops.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">my_string = \"Hello World!!\"\r\n\r\nprint(my_string)\r\nprint(len(my_string))\r\nprint(\"He\" in my_string)\r\nprint(my_string[3])\r\nprint(my_string[1:4])\r\nprint(my_string[1:4] + my_string[6:8])\r\n<\/pre>\n<p>Let&#8217;s explain this a little bit before seeing the output. We defined a string and printing it. Then we print its length, the result of checking if it contains the string &#8220;He&#8221; and the character in the index 3.<\/p>\n<p>The other two lines are slices, they work in any indexed sequence. Between square brackets you define a slice <code>array[n:m]<\/code> and you will receive an array that contains the element present in that interval. A thing to notice is that the interval is [n;m), open at the end.<\/p>\n<p>The last operation we do is the concatenation of two slices of the string. Let&#8217;s see the output:<\/p>\n<pre class=\"brush:bash\">$ python3 data-types\/string_ops.py\r\nHello World!!\r\n13\r\nTrue\r\nl\r\nell\r\nellWo\r\n<\/pre>\n<p>That&#8217;s how you work with strings in Python. Now let&#8217;s jump into those flow control tools.<\/p>\n<h2><a name=\"flowcontrols\"><\/a>6. Flow Control Tools<\/h2>\n<p>Flow control tools are tools that Python provides to make decisions and iterate through some data. The most common ones are <code>while<\/code>, <code>for<\/code> and <code>if<\/code>.<\/p>\n<p>The <code>while<\/code> and <code>for<\/code> statements are tools to repeat executions.<\/p>\n<p>The <code>while<\/code> loop is a conditional iteration. Its syntax is pretty simple:<\/p>\n<pre class=\"brush:python\">while condition:\r\n    action\r\nelse:\r\n    some action\r\n<\/pre>\n<p>The loop will evaluate the provided condition executing the action until the condition is no longer met. If the condition is not met and the else clause is present, its body is executed and the while is terminated, of course, the else is optional. Let&#8217;s see:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>while-else.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">i = 0\r\nmy_list = [1, 2, 3, 4, 5, 6]\r\n\r\nwhile i &lt; len(my_list):\r\n    print(my_list[i])\r\n    i += 1\r\nelse:\r\n    print(\"no element is left to print\")\r\n<\/pre>\n<p>Here we define an array and an int index initialized with 0, while that index is less than the array&#8217;s length, we print the respective element and add one to the index. When the condition is no longer met, we print a message. The output:<\/p>\n<pre class=\"brush:bash\">$ python3 flow-control\/while-else.py\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\nno element is left to print\r\n<\/pre>\n<p>Now, there are a few reserved words that come in handy some times with loops: <code>break<\/code> and <code>continue<\/code>. A <code>break<\/code> statement in a loop will terminate its execution without executing the else clause. A <code>continue<\/code> statement will skip the rest of the action and go back to testing the condition. Let&#8217;s modify our example to test these keywords:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>while-else.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">i = 0\r\nmy_list = [1, 2, 3, 4, 5, 6]\r\n\r\nwhile i &lt; len(my_list):\r\n    if my_list[i] == 5:\r\n        i += 1\r\n        break\r\n    if my_list[i] % 2 == 0:\r\n        i += 1\r\n        continue\r\n    print(my_list[i])\r\n    i += 1\r\nelse:\r\n    print(\"no element is left to print\")\r\n<\/pre>\n<p>We just added two if statements. The first one will <code>break<\/code> if the actual element is 5, and the second one will skip this step if its an even number. The output will look like:<\/p>\n<pre class=\"brush:bash\">$ python3 flow-control\/while-else.py\r\n1\r\n3\r\n<\/pre>\n<p>This script is only printing odd numbers until 5 appears. That&#8217;s a while loop. Another way we can achieve this is with a for loop.<\/p>\n<p>The for loop is a non-conditional iteration statement. It is used to iterate over items in any iterable object. The syntax is beautiful:<\/p>\n<pre class=\"brush:python\">for element in iterable:\r\n    action\r\nelse:\r\n    action\r\n<\/pre>\n<p>The iterable expression is only evaluated once, this means that if we have a function (we&#8217;ll talk about them later) that returns a sequence, we can put the call right in the for statement and be sure that it will be called only once, as the for will create an iterator of the result of evaluating that expression.<\/p>\n<p>The action will be called for every element contained by the resulting iterator, in the order returned by it. When all the elements in that iterator are exhausted, the action in the else statement (if present) is executed and then the loop is terminated.<\/p>\n<p>The <code>break<\/code> and <code>continue<\/code> keywords behave the same as in the while loop. Let&#8217;s rewrite our previous example to make it work with a for loop:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>for-else.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">my_list = [1, 2, 3, 4, 5, 6]\r\n\r\nfor item in my_list:\r\n    if item == 5:\r\n        break\r\n    if item % 2 == 0:\r\n        continue\r\n    print(item)\r\nelse:\r\n    print(\"no element is left to print\")\r\n<\/pre>\n<p>The output remains the same:<\/p>\n<pre class=\"brush:bash\">$ python3 flow-control\/for-else.py\r\n1\r\n3\r\n<\/pre>\n<p>I don&#8217;t know what you are thinking now, but the for loop seems a lot more elegant for this case, as we don&#8217;t need to retrieve the element from the array in the body of the loop, the for does it for us. The while loop was not meant to be used to iterate over indexes, but to perform actions until a condition is met.<\/p>\n<p>Let&#8217;s write an example that will actually do something interesting and shows us both iterations in the way they were meant to work: Let&#8217;s write a script that translates numbers from decimal to binary!<\/p>\n<p>The thing here is that, we will work with 0 and positive numbers that are &lt; 256, but we want the 8 bits to be displayed. For example, binary representation for the decimal &#8220;2&#8221; is &#8220;10&#8221;, but we want to see 8 bits, so &#8220;00000010&#8221; should be displayed. Let&#8217;s get to work:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>binary_translator.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">my_numbers = [2, 125, 9, 255, 0]\r\n\r\nfor n in my_numbers:\r\n    binary_representation = \"\"\r\n    remain = n\r\n    while remain &gt;= 2:\r\n        binary_representation = str(remain % 2) + binary_representation\r\n        remain \/\/= 2\r\n    binary_representation = str(remain) + binary_representation\r\n    binary_representation = (\"0\" * (8 - len(binary_representation))) + binary_representation\r\n    print(binary_representation)\r\n<\/pre>\n<p>Here we see some magic. We have a list of numbers to translate, so we iterate though them with a for loop, then, while the subject number is greater or equal than 2 we append the remainder of n \/\/ 2 to the start of our <code>binary_representation<\/code>, then we change our subject to the result of that division.<\/p>\n<p>Then we append what&#8217;s left of our subject to its representation and prepend as many zeros as we need to display 8 bits. Yes, the product (*) operation works with any iterable, <code>[2] * 3<\/code> will return <code>[2,2,2]<\/code>. Now, let&#8217;s see the output of this script:<\/p>\n<pre class=\"brush:bash\">$ python3 flow-control\/binary_translator.py\r\n00000010\r\n01111101\r\n00001001\r\n11111111\r\n00000000\r\n<\/pre>\n<p>That was our first interesting exercise, see how Python is now starting to look good? Well, it gets better. Let&#8217;s go back to our previous example, the one with the odds number. One thing you may have noticed is that we wrote <code>i += 1<\/code> three times in the body of our while loop. There is a better way to do it using the <code>try<\/code> statement we saw before.<\/p>\n<p>The <code>try<\/code> statement does not only helps us handle errors, it also comes with a handy <code>finally<\/code> clause. The syntax of the try statement is very convenient:<\/p>\n<pre class=\"brush:python\">try:\r\n    action\r\nexcept Error as identifier:\r\n    on error action\r\nexcept AnotherError as identifier:\r\n    on another error action\r\nfinally:\r\n    another action\r\n<\/pre>\n<p>The <code>try<\/code> statement will try to execute action, and if an error is raised it will look for an <code>except<\/code> clause that matches the error. The <code>finally<\/code> clause will execute <strong>always<\/strong> after the action was performed (or tried to) and any error has been handled. So, let&#8217;s rewrite our while-else example to use this useful statement:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>while-else.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">i = 0\r\nmy_list = [1, 2, 3, 4, 5, 6]\r\n\r\nwhile i &lt; len(my_list):\r\n    try:\r\n        if my_list[i] == 5:\r\n            break\r\n        if my_list[i] % 2 == 0:\r\n            continue\r\n        print(my_list[i])\r\n    finally:\r\n        i += 1\r\nelse:\r\n    print(\"no element is left to print\")\r\n<\/pre>\n<p>Now it looks better. We don&#8217;t care if any condition is met in the body of our while, we always want the <code>i<\/code> to be incremented, so we put it in a <code>finally<\/code> statement and everything looks better now.<\/p>\n<p>Now, another flow control tool we need to check before jumping into functions is the <code>with<\/code> statement. The <code>with<\/code> statement is used to wrap the execution of a block with methods defined by a context manager. This allows common try&#8230;except&#8230;finally usage patterns to be encapsulated for convenient reuse.<\/p>\n<p>It&#8217;s a statement the comes handy when we have to handle closable resources as the <code>with<\/code> will automatically close them when it&#8217;s body is finished executing.<\/p>\n<p>To explain the <code>with<\/code> statement we need to meet at least one of the resources that are compliant with it.<\/p>\n<p>We&#8217;ll meet files, and more precisely, CSV files. CSV stands for <em>comma separated values<\/em>, and it is a standard for exporting and importing data across multiple formats.<\/p>\n<p>It stores numbers and text in plain text. Each row of the file is a data record and every record consists of one or more fields which values are separated by commas. The use of the comma to separate every record\u2019s fields is the source of the name given to this standard.<\/p>\n<p>A CSV file, most of the times, consists of a row with the headers, which describes what does every column represent, and then every row after that is a set of data. Let&#8217;s see how we can read and write dictionaries to CSV files with Python:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>with.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">import csv\r\n\r\nmy_dictionaries = [\r\n    {\r\n        \"id\": 0,\r\n        \"value\": 123\r\n    },\r\n    {\r\n        \"id\": 1,\r\n        \"value\": 749\r\n    },\r\n    {\r\n        \"id\": 2,\r\n        \"value\": 913\r\n    }\r\n]\r\n\r\nwith open('\/tmp\/with_statement.csv', 'w+', newline='') as csv_file:\r\n    head = my_dictionaries[0]\r\n    keys = sorted([k for k in head.keys()])\r\n    writer = csv.DictWriter(csv_file, fieldnames=keys)\r\n    writer.writeheader()\r\n    for d in my_dictionaries:\r\n        writer.writerow(d)\r\n\r\nwith open('\/tmp\/with_statement.csv', 'r+', newline='') as csv_file:\r\n    read_dictionaries = [d for d in csv.DictReader(csv_file)]\r\n\r\nfor d in read_dictionaries:\r\n    print(str(d))\r\n<\/pre>\n<p>Well, there is a lot of new stuff in that script. Let&#8217;s see&#8230; The first line is an <code>import<\/code>, python provides a lot of libraries that gives us interfaces to do a lot of fun stuff, and there are even more libraries we can download from the internet and do even more fun stuff. These libraries have modules inside, and the <code>import<\/code> statement is how we import these modules and the components within them to our programs. So here we are importing csv, a module Python provides to handle CSV files.<\/p>\n<p>Then we are defining a list of dictionaries, that is the information we want to store in our CSV. With the <code>with<\/code> statement, we are calling a built-in function called <code>open<\/code>, which receives the location of a file, a mode to open it and a new line character (among other stuff we don&#8217;t need right now), then it returns the file it opened which is used as context in our <code>with<\/code> statement. The mode &#8220;w+&#8221; we used to open our file, means that we want to create the file if it doesn&#8217;t exist and write in it.<\/p>\n<p>The trickiest part comes now, we are using a method provided by dictionaries that is called <code>keys<\/code> and returns an iterable containing all the keys in our dictionary and then sorting it with the built-in function <code>sorted<\/code>, as we know keys in a dictionary are not always ordered the same way, and it could be very chaotic if every time we write in a csv the columns are sorted differently. The rest of the writing process is just how you use the <code>csv<\/code> module.<\/p>\n<p>On the read process there is another weird thing going on with a <code>for<\/code> statement between square brackets. That is called <em>for comprehension<\/em>, we are basically building an array of <code>d<\/code> for every <code>d<\/code> in an iterable (<code>csv.DictReader(csv_file)<\/code> returns an iterable with every row in our csv file).<\/p>\n<p>The last for is just printing out the dicts in <code>read_dictionaries<\/code>. Let&#8217;s check out the output:<\/p>\n<pre class=\"brush:bash\">$ python3 flow-control\/with.py\r\n{'value': '123', 'id': '0'}\r\n{'value': '749', 'id': '1'}\r\n{'value': '913', 'id': '2'}\r\n<\/pre>\n<p>Now, if you&#8217;ve ever worked with files in other languages, you remember how you had to close the resources manually after reading\/writing from a file. The <code>with<\/code> statement is doing it for us, as files are one of many resources supported by this statement. There are resources not supported by this feature, like sockets, but there is always a workaround.<\/p>\n<h2><a name=\"functions\"><\/a>7. Functions<\/h2>\n<p>This gets more and more interesting. Functions are a big deal in Python, as they are first-class objects. This means that we can do a lot of fun stuff with them here. Let&#8217;s first check out the syntax:<\/p>\n<pre class=\"brush:python\">def function_name(arguments):\r\n    body\r\n<\/pre>\n<p>Pretty simple, huh? The <code>def<\/code> keyword always starts the definition of a function, then comes its name, arguments between parentheses, a colon and then the body. A <code>return<\/code> statement is optional.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>basic.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">def format_hello(name):\r\n    return \"hello \" + name + \"!\"\r\n\r\nprint(format_hello(\"Sebasti\u00e1n\"))\r\n<\/pre>\n<p>Here we defined a function called <code>format_hello<\/code> that takes one argument called <code>name<\/code> and returns a custom hello message.<\/p>\n<p>Let&#8217;s go back to that &#8220;functions are first-class objects&#8221; thing. What can we do with functions in Python? Well, we can treat them as variables, so we can assign them to other variables, we can pass them around as arguments, we can print them, we can define functions inside another function and we can return functions from other functions. Let&#8217;s see some of this features at work.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>first_class.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">def a_function(an_array, a_function_argument):\r\n    return [a_function_argument(item) for item in an_array]\r\n\r\n\r\ndef add_one(n):\r\n    return n + 1\r\n\r\nmy_array = [5, 6, 7, 8]\r\n\r\nprint(str(a_function(my_array, add_one)))\r\n<\/pre>\n<p>Here we are defining a function that receives an array and another function as arguments and applies the argument function to each element of the array, returning the resulting array using for comprehension. Then we defined a function <code>add_one<\/code> that receives a number as argument and returns that number plus one. Let&#8217;s check out the output:<\/p>\n<pre class=\"brush:bash\">$ python3 functions\/first_class.py\r\n[6, 7, 8, 9]\r\n<\/pre>\n<p>There it is. The behavior we expected. That&#8217;s an awesome feature, right? We are passing a function as argument, this might not seem a big deal for you, but it is a very useful feature. We&#8217;ll get back to it later, now let&#8217;s see what other things can be done with functions.<\/p>\n<p>One thing I struggle a lot with other languages, like Java or JavaScript, is to set default values to function parameters. You have to check if the argument is present and if it&#8217;s not use the default value&#8230; I hate it. Python, as many other languages, provides an easy way of setting default values to function parameters. Check this out.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>default_parameter.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">def add(a, b=1):\r\n    return a + b\r\n\r\nprint(str(add(2, 2)))\r\nprint(str(add(9)))\r\n<\/pre>\n<p>Here we defined a function called <code>add<\/code> that receives two arguments, a and b, and returns de sum of them, but b as a default value (1). So when we call this function to print the results we can provide both arguments, or simply provide a and the default b is used. See the output below.<\/p>\n<pre class=\"brush:python\">$ python3 functions\/default_parameter.py\r\n4\r\n10\r\n<\/pre>\n<p>See? 2 + 2 = 4 and 9 + 1 = 10. I love this feature, but it has a big gotcha. The default values are not created when the function is called, but when it is defined instead. That means that, every time you use the default value of a parameter, it will be the exact same instance. Why I am telling you this? Well, because if you use a type that is mutable as a default value, you might get surprised about the results. See:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>mutable_default_parameter.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">def append_to(item, array=[]):\r\n    array.append(item)\r\n    return array\r\n\r\nprint(append_to(1))\r\nprint(append_to(2))\r\nprint(append_to(2, []))\r\nprint(append_to(3))\r\n<\/pre>\n<p>This piece of code seems harmless, you might expect 4 different arrays to be printed out, <code>[1]<\/code>, <code>[2]<\/code>, <code>[2]<\/code> again and <code>[3]<\/code>, but this won&#8217;t happen, as you are modifying the default value of the parameter, so the output actually is:<\/p>\n<pre class=\"brush:python\">$ python3 functions\/mutable_default_parameter.py\r\n[1]\r\n[1, 2]\r\n[2]\r\n[1, 2, 3]\r\n<\/pre>\n<p>When we provide an array as argument (third print statement), a new array is created, but otherwise not. The same array is being modified again and again. Having this in mind, you shouldn&#8217;t avoid to have mutable default arguments in your functions, but know how to treat them instead. See, this would be a correct implementation of the above method:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>mutable_default_parameter.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">def append_to(item, array=[]):\r\n    return array + [item]\r\n\r\nprint(append_to(1))\r\nprint(append_to(2))\r\nprint(append_to(2, []))\r\nprint(append_to(3))\r\n<\/pre>\n<p>The <code>append_to<\/code> function is not modifying the arguments. This function is compliant with functional programming, it doesn&#8217;t modify the given array, but return a new one instead. The output is now what we wanted it to be:<\/p>\n<pre class=\"brush:bash\">$ python3 functions\/mutable_default_parameter.py\r\n[1]\r\n[2]\r\n[2]\r\n[3]\r\n<\/pre>\n<p>I feel a better person just by telling you this, I&#8217;m sure that if you remember this you&#8217;ll do fine with Python in production environments.<\/p>\n<p>With this knowledge we can jump into another very useful feature Python has for us. Decorators.<\/p>\n<p>Python decorators provide a nice and simple syntax to call higher-order functions. By definition, a decorator takes a function as a parameter, and returns a wrapper of that given function to extend its behavior without actually modifying it.<\/p>\n<p>Imagine you want to print the arguments and results of a couple functions. There are two ways of doing this:<\/p>\n<ul>\n<li>Inserting print statements in all the functions in which you want this behavior<\/li>\n<li>Python decorators<\/li>\n<\/ul>\n<p>Let&#8217;s solve this problem with decorators so I show you how they work:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>decorators.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">def print_args_and_result(target):\r\n    def wrapper(*args):\r\n        print(\"calling {} with arguments: {}\".format(target.__name__, str(args)))\r\n        result = target(*args)\r\n        print(\"{} result: {}\".format(target.__name__, str(result)))\r\n        return result\r\n    return wrapper\r\n\r\n\r\n@print_args_and_result\r\ndef power(a, b):\r\n    return a ** b\r\n\r\n\r\n@print_args_and_result\r\ndef root(a, b):\r\n    return a ** (1 \/ b)\r\n\r\n\r\nprint(power(5, 2))\r\nprint(root(9, 2))\r\n<\/pre>\n<p>We defined a function called <code>print_args_and_result<\/code> that receives a function as an argument and returns a wrapper, this by definition is a decorator. The star symbol (*) before the arguments tell Python that the number of arguments we receive can vary, it&#8217;s like saying &#8220;this function can receive any number of arguments&#8221;. This way, we receive the arguments as a tuple <code>args<\/code>. You&#8217;ll see it when we see the output.<\/p>\n<p>The <code>{}<\/code> in string is a place holder, so we can call the function <code>format<\/code> the <code>str<\/code> type provides, that will replace the place holders with the arguments provided. Also, functions, classes, and other objects in Python has some attributes that are defined by the language, one of them is <code>__name__<\/code> that holds, in this case, the function&#8217;s name.<\/p>\n<p>Now the decorator is defined, we annotate with it all the functions we want to decorate, and it&#8217;s just magic. Python will override our functions with the wrapper the decorator returns. The output below.<\/p>\n<pre class=\"brush:bash\">$ python3 functions\/decorators.py\r\ncalling power with arguments: (5, 2)\r\npower result: 25\r\n25\r\ncalling root with arguments: (9, 2)\r\nroot result: 3.0\r\n3.0\r\n<\/pre>\n<p>Now, as I said at the top of the tutorial, Python is an object-oriented language, so we&#8217;ve got classes around here.<\/p>\n<h2><a name=\"classes\"><\/a>8. Classes<\/h2>\n<p>A class is a user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.<\/p>\n<p>To create a class we use the keyword <code>class<\/code> as in:<\/p>\n<pre class=\"brush:python\">class MyClass:\r\n    'optional documentation, like java docs'\r\n    class stuff\r\n<\/pre>\n<p>Here we defined a class called <code>MyClass<\/code>. The documentation can be accessed via the class attribute <code>__doc__<\/code>. Let&#8217;s talk about that class stuff:<\/p>\n<ul>\n<li>Classes should have a constructor, which is a special function Python will call when an instance of a class is created.<\/li>\n<li>There are Class Variables, which are variables available for all instances of a class.<\/li>\n<li>Instance variables are variables that belongs only to the current instance of a class.<\/li>\n<li>There are functions and methods in classes, they have only one difference from normal functions, and we&#8217;ll talk about it after the next example.<\/li>\n<\/ul>\n<p>Here is an example of a, kind of, complete class:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>definition.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">class Dog:\r\n\r\n    \"\"\"A Dog representation\"\"\"\r\n    animal = \"dog\"\r\n\r\n    def __init__(self, name, breed):\r\n        self.name = name\r\n        self.breed = breed\r\n        self.age = 0\r\n\r\n    def birth_day(self):\r\n        self.age += 1\r\n\r\n    def get_age(self):\r\n        return self.age\r\n\r\n    def get_name(self):\r\n        return self.name\r\n\r\nif __name__ == '__main__':\r\n    qwerty = Dog(\"Qwerty\", \"German Shepperd\")\r\n    while qwerty.get_age() &lt; 9:\r\n        qwerty.birth_day()\r\n    print(\"My {}, {}, has {} years\".format(qwerty.animal, qwerty.get_name(), qwerty.get_age()))\r\n<\/pre>\n<p>Here we are defining a class called <code>Dog<\/code>, which has a string documentation defined with triple double-quotes. Strings defined with triple double-quotes can contain enters, it just look nicer in the code.<\/p>\n<p>This class has a class variable called <code>animal<\/code> which holds the value <code>\"dog\"<\/code>, this variable will be available with the same value for all instances of this class.<\/p>\n<p>The constructor method of every class is called <code>__init__<\/code>, and, as every other method in a class, the first parameter is <code>self<\/code>, self is a reference to the instance in question. It&#8217;s kind of messy if you come from other languages, but it is not that hard actually, you don&#8217;t need to worry about this argument as Python injects it implicitly every time you call a function of a class&#8217; instance.<\/p>\n<p>The <code>self<\/code> argument can be seen as the <code>this<\/code> in Java or JavaScript, it&#8217;s just that, it isn&#8217;t just a global keyword, but an argument present in every function. You&#8217;ll get the hang of it by practicing.<\/p>\n<p>On the constructor method of this class we are receiving the name and the breed of the dog, and assigning those values to instance variables, along with the age initialized in zero.<\/p>\n<p>Then there is a method called <code>birth_day<\/code> that adds one to the age of the dog. The other two methods are accessor methods. This is kind of weird because every variable in an object (whether they are instance variables or class variables) are public, but as I come from JVM languages I just like to have accessor methods and leave the variables of an object alone.<\/p>\n<p>The <code>if __name__ == '__main__':<\/code> clause is the correct way of defining the top-level script that must be executed only if the script is being called as such. In other words, I want this code to be executed only if this code is being called with <code>python3 |file_name|<\/code>, but if this script is being imported by another file, this code should not be executed. Let&#8217;s check the output:<\/p>\n<pre class=\"brush:bash\">$ python3 classes\/definition.py\r\nMy dog, Qwerty, has 9 years\r\n<\/pre>\n<p>There it is, we defined a class and actually added some behavior to it. You see how we created an instance of that class? Just by running <code>Dog(\"qwerty\", \"german shepperd\")<\/code> we are creating an instance of <code>Dog<\/code>, which is calling the <code>__init__<\/code> method, as we can see by the fact that the name and age are being properly initialized.<\/p>\n<p>To invoke functions within classes we just use dot notation, as in <code>Class.function(args)<\/code>. And just to clarify the <code>self<\/code> argument issue, as you can see, we are not providing it explicitly, Python takes care of it for us. A thing to notice about it, is that when we call <code>birth_day<\/code> to access the instance variable <code>age<\/code>, we need to do it through <code>self<\/code>, which also happens in all the other accessors.<\/p>\n<p>Now let&#8217;s talk about inheritance. Instead of creating two classes that look the same but one has an attribute that another one does not, you can create a class that has every attribute and function that those classes have in common, and make those sub-classes of the parent class you&#8217;ve just created. Let&#8217;s see this in practice by creating a <code>Cat<\/code> class in the above example.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>definition.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">class Cat:\r\n\r\n    \"\"\"A Cat representation\"\"\"\r\n    animal = \"cat\"\r\n\r\n    def __init__(self, name, breed):\r\n        self.name = name\r\n        self.breed = breed\r\n        self.age = 0\r\n\r\n    def birth_day(self):\r\n        self.age += 1\r\n\r\n    def get_age(self):\r\n        return self.age\r\n\r\n    def get_name(self):\r\n        return self.name\r\n\r\n\r\nclass Dog:\r\n\r\n    \"\"\"A Dog representation\"\"\"\r\n    animal = \"dog\"\r\n\r\n    def __init__(self, name, breed):\r\n        self.name = name\r\n        self.breed = breed\r\n        self.age = 0\r\n\r\n    def birth_day(self):\r\n        self.age += 1\r\n\r\n    def get_age(self):\r\n        return self.age\r\n\r\n    def get_name(self):\r\n        return self.name\r\n\r\nif __name__ == '__main__':\r\n    qwerty = Dog(\"Qwerty\", \"German Shepperd\")\r\n    raul = Cat(\"Raul\", \"Siamese\")\r\n    while qwerty.get_age() &lt; 9:\r\n        qwerty.birth_day()\r\n    while raul.get_age() &lt; 3:\r\n        raul.birth_day()\r\n    print(\"My {}, {}, has {} years\".format(qwerty.animal, qwerty.get_name(), qwerty.get_age()))\r\n    print(\"My {}, {}, has {} years\".format(raul.animal, raul.get_name(), raul.get_age()))\r\n<\/pre>\n<p>See? These classes look the same, there is a lot of repeated code here. Well, let&#8217;s make a parent class called <code>Animal<\/code> and make <code>Dog<\/code> and <code>Cat<\/code> subclasses of <code>Animal<\/code>. The code looks like this:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>definition.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">class Animal:\r\n\r\n    \"\"\"An animal representation\"\"\"\r\n\r\n    def __init__(self, animal_type, name, breed):\r\n        self.animal_type = animal_type\r\n        self.name = name\r\n        self.breed = breed\r\n        self.age = 0\r\n\r\n    def birth_day(self):\r\n        self.age += 1\r\n\r\n    def get_age(self):\r\n        return self.age\r\n\r\n    def get_name(self):\r\n        return self.name\r\n\r\n\r\nclass Cat(Animal):\r\n\r\n    \"\"\"A Cat representation\"\"\"\r\n\r\n    def __init__(self, name, breed):\r\n        Animal.__init__(self, \"cat\", name, breed)\r\n\r\n\r\nclass Dog(Animal):\r\n\r\n    \"\"\"A Dog representation\"\"\"\r\n\r\n    def __init__(self, name, breed):\r\n        Animal.__init__(self, \"dog\", name, breed)\r\n\r\nif __name__ == '__main__':\r\n    qwerty = Dog(\"Qwerty\", \"German Shepperd\")\r\n    raul = Cat(\"Raul\", \"Siamese\")\r\n    while qwerty.get_age() &lt; 9:\r\n        qwerty.birth_day()\r\n    while raul.get_age() &lt; 3:\r\n        raul.birth_day()\r\n    print(\"My {}, {}, has {} years\".format(qwerty.animal_type, qwerty.get_name(), qwerty.get_age()))\r\n    print(\"My {}, {}, has {} years\".format(raul.animal_type, raul.get_name(), raul.get_age()))\r\n<\/pre>\n<p>This code looks nicer, more elegant and scalable. If we wan&#8217;t to add a <code>Cow<\/code> to our system, now takes four lines of executable code, and that is only if we add the documentation.<\/p>\n<p>If you read through the whole article, you now know a lot about Python. It would be rude not to show you how you can build an application with all this knowledge right?<\/p>\n<h2><a name=\"practice\"><\/a>9. A Little Practice<\/h2>\n<p>Let&#8217;s build a software for one of those places where they help lost dogs and cats to find new owners. Our application will be called <code>PuppyPlace<\/code>.<\/p>\n<p>First of all, we need a model. We&#8217;ll write a file <code>model.py<\/code> where we will define our business model.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>model.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">class Animal:\r\n\r\n    \"\"\"An animal representation in PuppyPlace system\"\"\"\r\n\r\n    def __init__(self, id, date, breed, estimated_age, notes=[]):\r\n        self.id = id\r\n        self.admission_date = date\r\n        self.breed = breed\r\n        self.estimated_age = estimated_age\r\n        for note in notes:\r\n            self.validate_note_type(note)\r\n        self.notes = notes.copy()\r\n\r\n    def get_id(self):\r\n        return self.id\r\n\r\n    def get_admission_date(self):\r\n        return self.admission_date\r\n\r\n    def get_breed(self):\r\n        return self.breed\r\n\r\n    def get_estimated_age(self):\r\n        return self.estimated_age\r\n\r\n    def get_notes(self):\r\n        return self.notes\r\n\r\n    def validate_note_type(self, note):\r\n        if type(note) == str:\r\n            return True\r\n        else:\r\n            raise TypeError(\"A note should be a string message\")\r\n\r\n    def add_note(self, note):\r\n        if self.validate_note_type(note):\r\n            self.notes = self.notes + [note]\r\n\r\n\r\nclass Cat(Animal):\r\n\r\n    \"\"\"A cat representation in PuppyPlace system\"\"\"\r\n\r\n    def __init__(self, id, date, breed, estimated_age, notes=[]):\r\n        Animal.__init__(self, id, date, breed, estimated_age, notes)\r\n\r\n\r\nclass Dog(Animal):\r\n\r\n    \"\"\"A dog representation in PuppyPlace system\"\"\"\r\n\r\n    def __init__(self, id, date, breed, estimated_age, notes=[]):\r\n        Animal.__init__(self, id, date, breed, estimated_age, notes)\r\n<\/pre>\n<p>Notice that, in the <code>Animal<\/code> constructor, the default value for the <code>notes<\/code> argument is a list, which is mutable. I use the function <code>copy<\/code> that iterables provide, this function returns a shallow copy of the iterable instance. Also, we are validating that notes must be string objects.<\/p>\n<p>We&#8217;ve got our model properly defined, now we need a place to store the animals. Let&#8217;s write a file called <code>repository.py<\/code> where we&#8217;ll define in-memory repositories to store these entities.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>repository.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">class Repository:\r\n\r\n    \"\"\"In memory storage for PuppyPlace entities\"\"\"\r\n\r\n    def __init__(self):\r\n        self.storage = {}\r\n\r\n    def create_or_update(self, id, entry):\r\n        self.storage[id] = entry\r\n\r\n    def delete(self, id):\r\n        del self.storage[id]\r\n\r\n    def find_by_id(self, id):\r\n        return self.storage.get(id)\r\n\r\n    def all(self):\r\n        return list(self.storage.values())\r\n<\/pre>\n<p>Now, we glue it all together in a file called <code>service.py<\/code> where we&#8217;ll build our entities and store them in our repository.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>service.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">import repository\r\nimport model\r\nfrom datetime import date\r\n\r\n\r\nclass CatService:\r\n\r\n    def __init__(self):\r\n        self.repository = repository.Repository()\r\n        self.next_id = 0\r\n\r\n    def store(self, breed, estimated_age, notes=[]):\r\n        cat = model.Cat(self.next_id, date.today(), breed, estimated_age, notes)\r\n        self.repository.create_or_update(cat.get_id(), cat)\r\n        self.next_id += 1\r\n\r\n    def update(self, cat):\r\n        self.repository.create_or_update(cat.get_id(), cat)\r\n\r\n    def remove(self, id):\r\n        self.repository.delete(id)\r\n\r\n    def get_by_id(self, id):\r\n        return self.repository.find_by_id(id)\r\n\r\n    def all(self):\r\n        return self.repository.all()\r\n\r\n\r\nclass DogService:\r\n\r\n    def __init__(self):\r\n        self.repository = repository.Repository()\r\n        self.next_id = 0\r\n\r\n    def store(self, breed, estimated_age, notes=[]):\r\n        dog = model.Dog(self.next_id, date.today(), breed, estimated_age, notes)\r\n        self.repository.create_or_update(dog.get_id(), dog)\r\n        self.next_id += 1\r\n\r\n    def update(self, dog):\r\n        self.repository.create_or_update(dog.get_id(), dog)\r\n\r\n    def remove(self, id):\r\n        self.repository.delete(id)\r\n\r\n    def get_by_id(self, id):\r\n        return self.repository.find_by_id(id)\r\n\r\n    def all(self):\r\n        return self.repository.all()\r\n<\/pre>\n<p>These services receive some parameters and build our entities to store them in our repositories. Here we encapsulated some logic that we will not have to worry about later. There is something new here, in the imports. The <code>from<\/code> keyword. Sometimes, there are big modules that contain a lot of classes and functions, and maybe we only want to import one class to use it. Well, we can do that with the <code>from<\/code> keyword.<\/p>\n<p>These services shall do the job. Now let&#8217;s jump to the user interface. It will be a console application, so we&#8217;ll write a menu and receive some input from the user, and then display the information through <code>print<\/code> statements. The way of getting input from the user in a console application with Python, is with the built-in function <code>input<\/code>, which receives a prompt message as argument and returns the string the user provided. So, let&#8217;s write a file called <code>menu.py<\/code> and start PuppyPlace&#8217;s UI.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>menu.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">from service import DogService, CatService\r\n\r\n\r\nclass Menu:\r\n    def __init__(self, options={}):\r\n        self.options = options.copy()\r\n        self.options[0] = \"Exit\"\r\n\r\n    def print_options(self):\r\n        keys = sorted(self.options.keys())\r\n        for k in keys:\r\n            print(\"{}. {}\".format(k, self.options.get(k)))\r\n        try:\r\n            selected = int(input(\"What do you want to do? \"))\r\n        except ValueError:\r\n            print(\"Please provide a valid option.\")\r\n            selected = None\r\n        return selected\r\n\r\n\r\nclass AnimalSelectionMenu(Menu):\r\n    def __init__(self, dog_callback, cat_callback):\r\n        Menu.__init__(self, {\r\n            1: \"Dog\",\r\n            2: \"Cat\"\r\n        })\r\n        self.dog_callback = dog_callback\r\n        self.cat_callback = cat_callback\r\n\r\n    def start(self):\r\n        selected = self.print_options()\r\n        if selected == 1:\r\n            self.dog_callback()\r\n        elif selected == 2:\r\n            self.cat_callback()\r\n\r\n\r\nclass GuestCheckInMenu:\r\n    def __init__(self, dog_service, cat_service):\r\n        self.dog_service = dog_service\r\n        self.cat_service = cat_service\r\n\r\n    def create_dog(self):\r\n        self.dog_service.store(input(\"breed: \"), input(\"estimated age: \"))\r\n\r\n    def create_cat(self):\r\n        self.cat_service.store(input(\"breed: \"), input(\"estimated age: \"))\r\n\r\n    def start(self):\r\n        AnimalSelectionMenu(self.create_dog, self.create_cat).start()\r\n\r\n\r\nclass GuestCheckOutMenu:\r\n    def __init__(self, dog_service, cat_service):\r\n        self.dog_service = dog_service\r\n        self.cat_service = cat_service\r\n\r\n    def check_out_dog(self):\r\n        ListMenu(self.dog_service, self.cat_service).list_dogs()\r\n        id = int(input(\"dog id: \"))\r\n        self.dog_service.remove(id)\r\n\r\n    def check_out_cat(self):\r\n        ListMenu(self.dog_service, self.cat_service).list_cats()\r\n        id = int(input(\"cat id: \"))\r\n        self.cat_service.remove(id)\r\n\r\n    def start(self):\r\n        AnimalSelectionMenu(self.check_out_dog, self.check_out_cat).start()\r\n\r\n\r\nclass ListMenu:\r\n    def __init__(self, dog_service, cat_service):\r\n        self.dog_service = dog_service\r\n        self.cat_service = cat_service\r\n\r\n    def list_dogs(self):\r\n        sorted_dogs = sorted(self.dog_service.all(), key=lambda d: d.get_id())\r\n        dogs = map(lambda dog: \"{}) {} - {} - {} - {}\".format(dog.get_id(), dog.get_admission_date(), dog.get_breed(),\r\n                                                              dog.get_estimated_age(), \",\".join(dog.get_notes())),\r\n                   sorted_dogs)\r\n        for dog in dogs:\r\n            print(dog)\r\n\r\n    def list_cats(self):\r\n        sorted_cats = sorted(self.cat_service.all(), key=lambda c: c.get_id())\r\n        cats = map(lambda cat: \"{}) {} - {} - {} - {}\".format(cat.get_id(), cat.get_admission_date(), cat.get_breed(),\r\n                                                              cat.get_estimated_age(), \",\".join(cat.get_notes())),\r\n                   sorted_cats)\r\n        for cat in cats:\r\n            print(cat)\r\n\r\n    def start(self):\r\n        AnimalSelectionMenu(self.list_dogs, self.list_cats).start()\r\n\r\n\r\nclass AddNotesMenu:\r\n    def __init__(self, dog_service, cat_service):\r\n        self.dog_service = dog_service\r\n        self.cat_service = cat_service\r\n\r\n    def add_notes_dog(self):\r\n        ListMenu(self.dog_service, self.cat_service).list_dogs()\r\n        id = int(input(\"dog id: \"))\r\n        note = input(\"note: \")\r\n        self.dog_service.get_by_id(id).add_note(note)\r\n\r\n    def add_notes_cat(self):\r\n        ListMenu(self.dog_service, self.cat_service).list_cats()\r\n        id = int(input(\"cat id: \"))\r\n        note = input(\"note: \")\r\n        self.cat_service.get_by_id(id).add_note(note)\r\n\r\n    def start(self):\r\n        AnimalSelectionMenu(self.add_notes_dog, self.add_notes_cat).start()\r\n\r\n\r\nclass MainMenu(Menu):\r\n    def __init__(self, dog_service=DogService(), cat_service=CatService()):\r\n        Menu.__init__(self, {\r\n            1: \"Guest Check-In\",\r\n            2: \"Guest Check-Out\",\r\n            3: \"Guests List\",\r\n            4: \"Add Notes\"\r\n        })\r\n        self.dog_service = dog_service\r\n        self.cat_service = cat_service\r\n\r\n    def check_in(self):\r\n        GuestCheckInMenu(self.dog_service, self.cat_service).start()\r\n\r\n    def check_out(self):\r\n        GuestCheckOutMenu(self.dog_service, self.cat_service).start()\r\n\r\n    def list(self):\r\n        ListMenu(self.dog_service, self.cat_service).start()\r\n\r\n    def add_notes(self):\r\n        AddNotesMenu(self.dog_service, self.cat_service).start()\r\n\r\n    def start(self):\r\n        print(\"Welcome to Puppy Place's system!\")\r\n\r\n        selected = None\r\n        while selected != 0:\r\n\r\n            selected = self.print_options()\r\n\r\n            if selected == 1:\r\n                self.check_in()\r\n            elif selected == 2:\r\n                self.check_out()\r\n            elif selected == 3:\r\n                self.list()\r\n            elif selected == 4:\r\n                self.add_notes()\r\n\r\n<\/pre>\n<p>Here it is, this is our user interface. This file is kind of big, if this was a real application we should split this classes into smaller modules.<\/p>\n<p>There are a couple new things here again, <code>lambda<\/code> expressions, a new parameter in the built-in function <code>sorted<\/code> and a new built-in function <code>map<\/code>. Let&#8217;s start with the <code>lambda<\/code> expressions.<\/p>\n<p>Lambdas are functions defined on the fly, they are convenient when we have to pass functions as arguments, as sometimes we don&#8217;t want to define those functions in a scope where other pieces of code have access to. Also, sometimes those functions have no other use, and we just need them as argument to a <code>map<\/code> or <code>sorted<\/code>.<\/p>\n<p>The syntax is really simple, it&#8217;s just defined as <code>lambda parameter1, parameter2, ..., parameterN: body<\/code>. A return clause is not needed, as lambdas always have to return something and are one-liners (functions with only one line in their body), so the <code>return<\/code> statement is implicit there.<\/p>\n<p>The <code>key<\/code> argument in the <code>sorted<\/code> built-in function is a function that receives an element of the array we are sorting, and returns the value the algorithm must use as sorting criteria. In this case, the <code>key<\/code> argument is a lambda that receives one of our entities and returns its id, as we want the animals sorted by id.<\/p>\n<p>The <code>map<\/code> function is one of the most used built-in functions for iterables. It receives a function (called transformation) and an array, then returns an array with the results of applying the transformation to every element of the provided array. You can see the <code>map<\/code> function more in detail in <a title=\"Python Map Example\" href=\"https:\/\/www.webcodegeeks.com\/python\/python-map-example\/\">this<\/a> example.<\/p>\n<p>So, now we need a main script, which we&#8217;ll write in a file called <code>main.py<\/code>.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>menu.py<\/em><\/span><\/p>\n<pre class=\"brush:python\">from menu import MainMenu\r\n\r\nif __name__ == '__main__':\r\n    MainMenu().start()\r\n<\/pre>\n<p>This script only starts the <code>MainMenu<\/code>. Now, let&#8217;s test this!<\/p>\n<pre class=\"brush:bash\">python3 main.py\r\nWelcome to Puppy Place's system!\r\n0. Exit\r\n1. Guest Check-In\r\n2. Guest Check-Out\r\n3. Guests List\r\n4. Add Notes\r\nWhat do you want to do? 1\r\n0. Exit\r\n1. Dog\r\n2. Cat\r\nWhat do you want to do? 1\r\nbreed: German Shepperd\r\nestimated age: 4\r\n0. Exit\r\n1. Guest Check-In\r\n2. Guest Check-Out\r\n3. Guests List\r\n4. Add Notes\r\nWhat do you want to do? 1\r\n0. Exit\r\n1. Dog\r\n2. Cat\r\nWhat do you want to do? 1\r\nbreed: Poodle\r\nestimated age: 8\r\n0. Exit\r\n1. Guest Check-In\r\n2. Guest Check-Out\r\n3. Guests List\r\n4. Add Notes\r\nWhat do you want to do? 1\r\n0. Exit\r\n1. Dog\r\n2. Cat\r\nWhat do you want to do? 2\r\nbreed: Siamese\r\nestimated age: 9\r\n0. Exit\r\n1. Guest Check-In\r\n2. Guest Check-Out\r\n3. Guests List\r\n4. Add Notes\r\nWhat do you want to do? 3\r\n0. Exit\r\n1. Dog\r\n2. Cat\r\nWhat do you want to do? 1\r\n0) 2016-03-14 - German Shepperd - 4 -\r\n1) 2016-03-14 - Poodle - 8 -\r\n0. Exit\r\n1. Guest Check-In\r\n2. Guest Check-Out\r\n3. Guests List\r\n4. Add Notes\r\nWhat do you want to do? 2\r\n0. Exit\r\n1. Dog\r\n2. Cat\r\nWhat do you want to do? 1\r\n0) 2016-03-14 - German Shepperd - 4 -\r\n1) 2016-03-14 - Poodle - 8 -\r\ndog id: 0\r\n0. Exit\r\n1. Guest Check-In\r\n2. Guest Check-Out\r\n3. Guests List\r\n4. Add Notes\r\nWhat do you want to do? 1\r\n0. Exit\r\n1. Dog\r\n2. Cat\r\nWhat do you want to do? 1\r\nbreed: Schnauzer\r\nestimated age: 5\r\n0. Exit\r\n1. Guest Check-In\r\n2. Guest Check-Out\r\n3. Guests List\r\n4. Add Notes\r\nWhat do you want to do? 3\r\n0. Exit\r\n1. Dog\r\n2. Cat\r\nWhat do you want to do? 1\r\n1) 2016-03-14 - Poodle - 8 -\r\n2) 2016-03-14 - Schnauzer - 5 -\r\n0. Exit\r\n1. Guest Check-In\r\n2. Guest Check-Out\r\n3. Guests List\r\n4. Add Notes\r\nWhat do you want to do? 3\r\n0. Exit\r\n1. Dog\r\n2. Cat\r\nWhat do you want to do? 2\r\n0) 2016-03-14 - Siamese - 9 -\r\n0. Exit\r\n1. Guest Check-In\r\n2. Guest Check-Out\r\n3. Guests List\r\n4. Add Notes\r\nWhat do you want to do? 4\r\n0. Exit\r\n1. Dog\r\n2. Cat\r\nWhat do you want to do? 2\r\n0) 2016-03-14 - Siamese - 9 -\r\ncat id: 0\r\nnote: Violent\r\n0. Exit\r\n1. Guest Check-In\r\n2. Guest Check-Out\r\n3. Guests List\r\n4. Add Notes\r\nWhat do you want to do? 3\r\n0. Exit\r\n1. Dog\r\n2. Cat\r\nWhat do you want to do? 2\r\n0) 2016-03-14 - Siamese - 9 - Violent\r\n0. Exit\r\n1. Guest Check-In\r\n2. Guest Check-Out\r\n3. Guests List\r\n4. Add Notes\r\nWhat do you want to do? 0\r\n<\/pre>\n<p>See? It works! Download the project and test it yourself. Also, there is homework for you! See the code of the services and menus of cats and dogs? They all look the same! Why don&#8217;t you try and improve that?<\/p>\n<h2><a name=\"download\"><\/a>10. Download the Code Project<\/h2>\n<p>This was an extensive introduction to Python. Keep in mind that there is still a lot to learn from this awesome language!<\/p>\n<div class=\"download\"><strong>Download<\/strong><br \/>\nYou can download the full source code of this example here: <a href=\"http:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2016\/03\/python-beginners.zip\"><strong>python-beginners<\/strong><\/a><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Let&#8217;s talk about Python. If you want to learn Python from scratch, this tutorial will be a good read for you. By using Python 3.4.3 (which you can download here), we&#8217;ll see the basics of this awesome language. This tutorial expects you to have some basic knowledge of programming. And knowing any other language will &hellip;<\/p>\n","protected":false},"author":109,"featured_media":1651,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[53],"tags":[],"class_list":["post-11438","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Python Tutorial for Beginners - Web Code Geeks - 2026<\/title>\n<meta name=\"description\" content=\"Interested to learn about python? Then check out our Tutorial which expects you to have some basic knowledge of programming or knowing any other language.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Tutorial for Beginners - Web Code Geeks - 2026\" \/>\n<meta property=\"og:description\" content=\"Interested to learn about python? Then check out our Tutorial which expects you to have some basic knowledge of programming or knowing any other language.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/\" \/>\n<meta property=\"og:site_name\" content=\"Web Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/webcodegeeks\" \/>\n<meta property=\"article:author\" content=\"https:\/\/www.facebook.com\/sgvinci\" \/>\n<meta property=\"article:published_time\" content=\"2016-03-21T10:07:24+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2018-06-20T13:29:53+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Sebastian Vinci\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@sebastianvinci_\" \/>\n<meta name=\"twitter:site\" content=\"@webcodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Sebastian Vinci\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"56 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/\"},\"author\":{\"name\":\"Sebastian Vinci\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/06a43c63e373dff2e159bbc029b405aa\"},\"headline\":\"Python Tutorial for Beginners\",\"datePublished\":\"2016-03-21T10:07:24+00:00\",\"dateModified\":\"2018-06-20T13:29:53+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/\"},\"wordCount\":7790,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg\",\"articleSection\":[\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/\",\"url\":\"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/\",\"name\":\"Python Tutorial for Beginners - Web Code Geeks - 2026\",\"isPartOf\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg\",\"datePublished\":\"2016-03-21T10:07:24+00:00\",\"dateModified\":\"2018-06-20T13:29:53+00:00\",\"description\":\"Interested to learn about python? Then check out our Tutorial which expects you to have some basic knowledge of programming or knowing any other language.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/#primaryimage\",\"url\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg\",\"contentUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg\",\"width\":150,\"height\":150},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.webcodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python\",\"item\":\"https:\/\/www.webcodegeeks.com\/category\/python\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Python Tutorial for Beginners\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#website\",\"url\":\"https:\/\/www.webcodegeeks.com\/\",\"name\":\"Web Code Geeks\",\"description\":\"Web Developers Resource Center\",\"publisher\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.webcodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/www.webcodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/webcodegeeks\",\"https:\/\/x.com\/webcodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/06a43c63e373dff2e159bbc029b405aa\",\"name\":\"Sebastian Vinci\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/12d0233b49dd2a282330a987b16e81c3fbd4a8a8f5d5338348a6edd47cfff99e?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/12d0233b49dd2a282330a987b16e81c3fbd4a8a8f5d5338348a6edd47cfff99e?s=96&d=mm&r=g\",\"caption\":\"Sebastian Vinci\"},\"description\":\"Sebastian is a full stack programmer, who has strong experience in Java and Scala enterprise web applications. He is currently studying Computers Science in UBA (University of Buenos Aires) and working a full time job at a .com company as a Semi-Senior developer, involving architectural design, implementation and monitoring. He also worked in automating processes (such as data base backups, building, deploying and monitoring applications).\",\"sameAs\":[\"http:\/\/www.webcodegeeks.com\/\",\"https:\/\/www.facebook.com\/sgvinci\",\"https:\/\/x.com\/sebastianvinci_\"],\"url\":\"https:\/\/www.webcodegeeks.com\/author\/sebastian-vinci\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Tutorial for Beginners - Web Code Geeks - 2026","description":"Interested to learn about python? Then check out our Tutorial which expects you to have some basic knowledge of programming or knowing any other language.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/","og_locale":"en_US","og_type":"article","og_title":"Python Tutorial for Beginners - Web Code Geeks - 2026","og_description":"Interested to learn about python? Then check out our Tutorial which expects you to have some basic knowledge of programming or knowing any other language.","og_url":"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/","og_site_name":"Web Code Geeks","article_publisher":"https:\/\/www.facebook.com\/webcodegeeks","article_author":"https:\/\/www.facebook.com\/sgvinci","article_published_time":"2016-03-21T10:07:24+00:00","article_modified_time":"2018-06-20T13:29:53+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg","type":"image\/jpeg"}],"author":"Sebastian Vinci","twitter_card":"summary_large_image","twitter_creator":"@sebastianvinci_","twitter_site":"@webcodegeeks","twitter_misc":{"Written by":"Sebastian Vinci","Est. reading time":"56 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/#article","isPartOf":{"@id":"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/"},"author":{"name":"Sebastian Vinci","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/06a43c63e373dff2e159bbc029b405aa"},"headline":"Python Tutorial for Beginners","datePublished":"2016-03-21T10:07:24+00:00","dateModified":"2018-06-20T13:29:53+00:00","mainEntityOfPage":{"@id":"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/"},"wordCount":7790,"commentCount":0,"publisher":{"@id":"https:\/\/www.webcodegeeks.com\/#organization"},"image":{"@id":"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/#primaryimage"},"thumbnailUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg","articleSection":["Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/","url":"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/","name":"Python Tutorial for Beginners - Web Code Geeks - 2026","isPartOf":{"@id":"https:\/\/www.webcodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/#primaryimage"},"image":{"@id":"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/#primaryimage"},"thumbnailUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg","datePublished":"2016-03-21T10:07:24+00:00","dateModified":"2018-06-20T13:29:53+00:00","description":"Interested to learn about python? Then check out our Tutorial which expects you to have some basic knowledge of programming or knowing any other language.","breadcrumb":{"@id":"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/#primaryimage","url":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg","contentUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg","width":150,"height":150},{"@type":"BreadcrumbList","@id":"https:\/\/www.webcodegeeks.com\/python\/python-tutorial-beginners\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.webcodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Python","item":"https:\/\/www.webcodegeeks.com\/category\/python\/"},{"@type":"ListItem","position":3,"name":"Python Tutorial for Beginners"}]},{"@type":"WebSite","@id":"https:\/\/www.webcodegeeks.com\/#website","url":"https:\/\/www.webcodegeeks.com\/","name":"Web Code Geeks","description":"Web Developers Resource Center","publisher":{"@id":"https:\/\/www.webcodegeeks.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.webcodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.webcodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/www.webcodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/webcodegeeks","https:\/\/x.com\/webcodegeeks"]},{"@type":"Person","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/06a43c63e373dff2e159bbc029b405aa","name":"Sebastian Vinci","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/12d0233b49dd2a282330a987b16e81c3fbd4a8a8f5d5338348a6edd47cfff99e?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/12d0233b49dd2a282330a987b16e81c3fbd4a8a8f5d5338348a6edd47cfff99e?s=96&d=mm&r=g","caption":"Sebastian Vinci"},"description":"Sebastian is a full stack programmer, who has strong experience in Java and Scala enterprise web applications. He is currently studying Computers Science in UBA (University of Buenos Aires) and working a full time job at a .com company as a Semi-Senior developer, involving architectural design, implementation and monitoring. He also worked in automating processes (such as data base backups, building, deploying and monitoring applications).","sameAs":["http:\/\/www.webcodegeeks.com\/","https:\/\/www.facebook.com\/sgvinci","https:\/\/x.com\/sebastianvinci_"],"url":"https:\/\/www.webcodegeeks.com\/author\/sebastian-vinci\/"}]}},"_links":{"self":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/posts\/11438","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/users\/109"}],"replies":[{"embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/comments?post=11438"}],"version-history":[{"count":0,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/posts\/11438\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/media\/1651"}],"wp:attachment":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/media?parent=11438"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/categories?post=11438"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/tags?post=11438"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}