<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ python developer - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ python developer - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 30 May 2026 08:56:34 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/python-developer/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Learn Python – Free Python Courses for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Python is a great programming language to learn and you can use it in a variety of areas in software development.  You can use Python for web development, data analysis, machine learning, artificial intelligence, and more. In this article, I will lis... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-python-free-python-courses-for-beginners/</link>
                <guid isPermaLink="false">66b8da03eb5c4db85a0b342e</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ python developer ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jessica Wilkins ]]>
                </dc:creator>
                <pubDate>Mon, 13 Dec 2021 16:57:33 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/12/chris-ried-ieic5Tq8YMk-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Python is a great programming language to learn and you can use it in a variety of areas in software development. </p>
<p>You can use Python for web development, data analysis, machine learning, artificial intelligence, and more.</p>
<p>In this article, I will list out 15 free Python courses for beginners. </p>
<ol>
<li><a class="post-section-overview" href="#heading-learn-python-full-course-for-beginners">Learn Python - Full Course for Beginners</a> - freeCodeCamp</li>
<li><a class="post-section-overview" href="#heading-programming-for-everybody-getting-started-with-python">Programming for Everybody (Getting Started with Python)</a> - University of Michigan</li>
<li><a class="post-section-overview" href="#heading-the-python-handbook">The Python Handbook</a> - Flavio Copes</li>
<li><a class="post-section-overview" href="#heading-python-tutorials-for-absolute-beginners-by-cs-dojo">Python Tutorials for Absolute Beginners by CS Dojo</a> - CS Dojo</li>
<li><a class="post-section-overview" href="#heading-python-tutorial-python-for-beginners">Python Tutorial (Python for Beginners)</a> - Programming with Mosh </li>
<li><a class="post-section-overview" href="#heading-studytonight-python-courses">Studytonight Python Courses</a> - Studytonight</li>
<li><a class="post-section-overview" href="#heading-python-crash-course-for-beginners">Python Crash Course for Beginners</a> - Traversy Media</li>
<li><a class="post-section-overview" href="#heading-python-core">Python Core</a> - SoloLearn</li>
<li><a class="post-section-overview" href="#heading-python-basics-with-sam">Python Basics with Sam</a> -  freeCodeCamp</li>
<li><a class="post-section-overview" href="#heading-python-beginner-tutorials">Python Beginner Tutorials</a> - Pythonspot </li>
<li><a class="post-section-overview" href="#heading-python-tutorial">Python Tutorial</a> - PythonForBeginners</li>
<li><a class="post-section-overview" href="#heading-automate-the-boring-stuff-with-python">Automate the Boring Stuff with Python</a> - Al Sweigart</li>
<li><a class="post-section-overview" href="#heading-learn-python-in-12-hours-python-tutorial-for-beginners">Learn Python in 12 Hours (Python Tutorial For Beginners)</a> - Edureka</li>
<li><a class="post-section-overview" href="#heading-python-tutorial-for-beginners-learn-python-in-5-hours">Python Tutorial for Beginners (Learn Python in 5 Hours)</a> - TechWorld with Nana </li>
<li><a class="post-section-overview" href="#heading-scientific-computing-with-python">Scientific Computing with Python</a> - freeCodeCamp</li>
</ol>
<h2 id="heading-learn-python-full-course-for-beginners">Learn Python - Full Course for Beginners</h2>
<p>In this <a target="_blank" href="https://www.youtube.com/watch?v=rfscVS0vtbw">freeCodeCamp YouTube Course</a>, you will learn programming basics such as lists, conditionals, strings, tuples, functions, classes and more.</p>
<p>You will also build several small projects like a basic calculator, mad libs game, a translator app, and a guessing game.</p>
<h2 id="heading-programming-for-everybody-getting-started-with-python">Programming for Everybody (Getting Started with Python)</h2>
<p>In this <a target="_blank" href="https://www.freecodecamp.org/news/python-for-everybody/">University of Michigan course</a>, you will learn about functions, loops, conditionals, variables and more from the famous "Dr. Chuck".</p>
<p>Once you learn the basics, you can continue on through the rest of the <a target="_blank" href="https://www.coursera.org/specializations/python">specialization</a> and take the <a target="_blank" href="https://www.coursera.org/learn/python-data?specialization=python">Python Data Structures course</a>, the <a target="_blank" href="https://www.coursera.org/learn/python-network-data?specialization=python">Using Python to Access Web Data course</a>, and the <a target="_blank" href="https://www.coursera.org/learn/python-databases?specialization=python">Using Databases with Python course</a>.</p>
<h2 id="heading-the-python-handbook">The Python Handbook</h2>
<p>In <a target="_blank" href="https://www.freecodecamp.org/news/the-python-handbook/">this Flavio Copes book</a>, you will learn about strings, lists, tuples, recursion, and more.</p>
<p>You will also learn how to install 3rd party packages and how to work with virtual environments.</p>
<h2 id="heading-python-tutorials-for-absolute-beginners-by-cs-dojo">Python Tutorials for Absolute Beginners by CS Dojo</h2>
<p>In this series of <a target="_blank" href="https://www.youtube.com/playlist?list=PLBZBJbE_rGRWeh5mIBhD-hhDwSEDxogDg">Beginner Python YouTube videos by CS Dojo</a>, you will learn about dictionaries, loops, functions, objects and more.</p>
<p>You will also learn <a target="_blank" href="https://www.youtube.com/watch?v=W0wWwglE1Vc&amp;list=PLBZBJbE_rGRWeh5mIBhD-hhDwSEDxogDg&amp;index=15">how to build a Twitter bot using Python</a>.</p>
<h2 id="heading-python-tutorial-python-for-beginners">Python Tutorial - Python for Beginners</h2>
<p>In this <a target="_blank" href="https://www.youtube.com/watch?v=_uQrJ0TkZlc">Programming with Mosh YouTube course,</a> you will learn programming basics like variables, loops, strings, tuples, functions, classes and more.</p>
<p>You will also build three projects: one on automation, one on machine learning, and one on building a website with Django.</p>
<p>For additional practice, you can go through Mosh's <a target="_blank" href="https://programmingwithmosh.com/python/python-exercises-and-questions-for-beginners/">53 Python Exercises for Beginners</a>.</p>
<h2 id="heading-studytonight-python-courses">Studytonight Python Courses</h2>
<p>In <a target="_blank" href="https://www.studytonight.com/python/">Studytonight</a>, you will learn about Python basics, error handling, OOP, file handling, complex datatypes, Multithreading and more.</p>
<p>Once you have learned the basics, you can move onto their other modules which include, the <a target="_blank" href="https://www.studytonight.com/numpy">NumPy library</a>, <a target="_blank" href="https://www.studytonight.com/matplotlib">Matplotlib</a>, <a target="_blank" href="https://www.studytonight.com/tkinter">Tkinter</a>, <a target="_blank" href="https://www.studytonight.com/network-programming-in-python/">Network Programming in Python</a>, and <a target="_blank" href="https://www.studytonight.com/python/web-scraping/">Web Scraping using Beautiful Soup</a>.</p>
<h2 id="heading-python-crash-course-for-beginners">Python Crash Course for Beginners</h2>
<p>In this <a target="_blank" href="https://www.youtube.com/watch?v=JJmcL1N2KQs">Brad Traversy YouTube course</a>, you will learn about lists, tuples, dictionaries, functions, classes and more. Brad will also show you how to work with files and JSON data.</p>
<h2 id="heading-python-core">Python Core</h2>
<p>In <a target="_blank" href="https://www.sololearn.com/learning/1073">SoloLearn's Python Course</a>, you will learn about strings, variables, OOP, functional programming and more. There are plenty of quizzes, challenges and projects that you can build along the way.</p>
<p>In order to get started, you will need to create a free account.</p>
<h2 id="heading-python-basics-with-sam">Python Basics with Sam</h2>
<p>In <a target="_blank" href="https://www.youtube.com/playlist?list=PLWKjhJtqVAbkmRvnFmOd4KhDdlK1oIq23">this Sam Focht YouTube Series</a>, you will learn about loops, functions, strings, recursion and more.</p>
<p>You will also build several projects including a guessing game, shopping list, a board game, and a random password generator.</p>
<h2 id="heading-python-beginner-tutorials">Python Beginner Tutorials</h2>
<p>In this <a target="_blank" href="https://pythonspot.com/beginner/">series of Pythonspot beginner tutorials</a>, you will learn about data types, tuples, objects, classes, dictionaries and more. You will also learn about advanced concepts like recursion, lambda, and threading.</p>
<p>Once you cover the basics, you can move onto <a target="_blank" href="https://pythonspot.com/machine-learning/">machine learning</a>, <a target="_blank" href="https://pythonspot.com/python-database/">databases</a>, and <a target="_blank" href="https://pythonspot.com/gui/">GUI's</a>.</p>
<h2 id="heading-python-tutorial">Python Tutorial</h2>
<p>In this <a target="_blank" href="https://www.pythonforbeginners.com/python-tutorial">PythonForBeginners tutorial</a>, you will learn about functions, loops, lists, conditionals, error handling and more.</p>
<p>Once you learn the basics, you can explore the other modules on the site including <a target="_blank" href="https://www.pythonforbeginners.com/python-on-the-web/web-scraping-with-beautifulsoup">Web Scraping with BeautifulSoup</a> and <a target="_blank" href="https://www.pythonforbeginners.com/api/using-the-youtube-api">Using the YouTube API in Python</a>.</p>
<h2 id="heading-automate-the-boring-stuff-with-python">Automate the Boring Stuff with Python</h2>
<p>In the <a target="_blank" href="https://automatetheboringstuff.com/">Automate the Boring Stuff with Python online book</a>, you will learn about dictionaries, strings, debugging, regular expressions and more.</p>
<p>If you prefer a video format, then you can go through <a target="_blank" href="https://www.youtube.com/watch?v=1F_OgqRuSdI&amp;list=PL0-84-yl1fUnRuXGFe_F7qSH1LEnn9LkW">the YouTube series</a> that Al Sweigart put together.</p>
<h2 id="heading-learn-python-in-12-hours-python-tutorial-for-beginners">Learn Python in 12 Hours (Python Tutorial For Beginners)</h2>
<p>In <a target="_blank" href="https://www.youtube.com/watch?v=WGJJIrtnfpk">this 12 hour YouTube Edureka course</a>, you will learn about functions, loops, lists, conditionals, error handling and more.</p>
<p>This course will also talk about career opportunities in Python and salary expectations for Python developers.  </p>
<h2 id="heading-python-tutorial-for-beginners-learn-python-in-5-hours">Python Tutorial for Beginners (Learn Python in 5 Hours)</h2>
<p>In <a target="_blank" href="https://www.youtube.com/watch?v=t8pPdKYpowI">this TechWorld with Nana YouTube course</a>, you will learn about strings, variables, OOP, functional programming and more.  You will also build a couple of projects including a countdown app and a project focused on API requests to Gitlab. </p>
<h2 id="heading-scientific-computing-with-python">Scientific Computing with Python</h2>
<p>In <a target="_blank" href="https://www.freecodecamp.org/learn/scientific-computing-with-python/">this freeCodeCamp certification course</a>, you will learn about loops, lists, dictionaries, networking, web services and more.</p>
<p>You will also have the opportunity to build five projects: an <a target="_blank" href="https://www.freecodecamp.org/learn/scientific-computing-with-python/scientific-computing-with-python-projects/arithmetic-formatter">Arithmetic Formatter</a>, <a target="_blank" href="https://www.freecodecamp.org/learn/scientific-computing-with-python/scientific-computing-with-python-projects/time-calculator">Time Calculator,</a> <a target="_blank" href="https://www.freecodecamp.org/learn/scientific-computing-with-python/scientific-computing-with-python-projects/budget-app">Budget App,</a> <a target="_blank" href="https://www.freecodecamp.org/learn/scientific-computing-with-python/scientific-computing-with-python-projects/polygon-area-calculator">Polygon Area Calculator</a>, and <a target="_blank" href="https://www.freecodecamp.org/learn/scientific-computing-with-python/scientific-computing-with-python-projects/probability-calculator">Probability Calculator</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Python Handbook – Learn Python for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ The Python Handbook follows the 80/20 rule: learn 80% of the topic in 20% of the time. I find this approach gives a well-rounded overview.  This book does not try to cover everything under the sun related to Python. It focuses on the core of the lang... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-python-handbook/</link>
                <guid isPermaLink="false">66bb5ab8b6e566d0c2aea612</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ learn to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ python developer ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Flavio Copes ]]>
                </dc:creator>
                <pubDate>Wed, 10 Mar 2021 22:51:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/03/book.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The Python Handbook follows the 80/20 rule: learn 80% of the topic in 20% of the time.</p>
<p>I find this approach gives a well-rounded overview. </p>
<p>This book does not try to cover everything under the sun related to Python. It focuses on the core of the language, trying to simplify the more complex topics. </p>
<p>I hope the contents of this book will help you achieve what you want: <strong>learn the basics of Python</strong>.</p>
<blockquote>
<p>Note: You can <a target="_blank" href="https://flaviocopes.com/page/python-handbook/">get a PDF, ePub and Mobi version of this Python Handbook</a></p>
</blockquote>
<p>Enjoy!</p>
<h2 id="heading-summary">Summary</h2>
<ul>
<li><a class="post-section-overview" href="#heading-introduction-to-python">Introduction to Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-python">How to Install Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-run-python-programs">How to Run Python Programs</a></li>
<li><a class="post-section-overview" href="#heading-python-2-vs-python-3">Python 2 vs Python 3</a></li>
<li><a class="post-section-overview" href="#heading-python-basics">Python Basics</a></li>
<li><a class="post-section-overview" href="#heading-data-types-in-python">Data Types in Python</a></li>
<li><a class="post-section-overview" href="#operators">Operators in Python</a></li>
<li><a class="post-section-overview" href="#heading-the-ternary-operator-in-python">The Ternary Operator in Python</a></li>
<li><a class="post-section-overview" href="#heading-strings-in-python">Strings in Python</a></li>
<li><a class="post-section-overview" href="#heading-booleans-in-python">Booleans in Python</a></li>
<li><a class="post-section-overview" href="#heading-numbers-in-python">Numbers in Python</a></li>
<li><a class="post-section-overview" href="#heading-constants-in-python">Constants in Python</a></li>
<li><a class="post-section-overview" href="#heading-enums-in-python">Enums in Python</a></li>
<li><a class="post-section-overview" href="#heading-user-input-in-python">User Input in Python</a></li>
<li><a class="post-section-overview" href="#heading-control-statements-in-python">Control Statements in Python</a></li>
<li><a class="post-section-overview" href="#heading-lists-in-python">Lists in Python</a></li>
<li><a class="post-section-overview" href="#heading-tuples-in-python">Tuples in Python</a></li>
<li><a class="post-section-overview" href="#heading-dictionaries-in-python">Dictionaries in Python</a></li>
<li><a class="post-section-overview" href="#heading-sets-in-python">Sets in Python</a></li>
<li><a class="post-section-overview" href="#heading-functions-in-python">Functions in Python</a></li>
<li><a class="post-section-overview" href="#heading-objects-in-python">Objects in Python</a></li>
<li><a class="post-section-overview" href="#heading-loops-in-python">Loops in Python</a></li>
<li><a class="post-section-overview" href="#heading-classes-in-python">Classes in Python</a></li>
<li><a class="post-section-overview" href="#heading-modules-in-python">Modules in Python</a></li>
<li><a class="post-section-overview" href="#heading-the-python-standard-library">The Python Standard Library</a></li>
<li><a class="post-section-overview" href="#heading-the-pep8-python-style-guide">The PEP8 Python Style Guide</a></li>
<li><a class="post-section-overview" href="#heading-debugging-in-python">Debugging in Python</a></li>
<li><a class="post-section-overview" href="#heading-variable-scope-in-python">Variable Scope in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-accept-arguments-from-the-command-line-in-python">How to Accept Arguments from the Command Line in Python</a></li>
<li><a class="post-section-overview" href="#heading-lambda-functions-in-python">Lambda Functions in Python</a></li>
<li><a class="post-section-overview" href="#heading-recursion-in-python">Recursion in Python</a></li>
<li><a class="post-section-overview" href="#heading-nested-functions-in-python">Nested Functions in Python</a></li>
<li><a class="post-section-overview" href="#heading-closures-in-python">Closures in Python</a></li>
<li><a class="post-section-overview" href="#heading-decorators-in-python">Decorators in Python</a></li>
<li><a class="post-section-overview" href="#heading-docstrings-in-python">Docstrings in Python</a></li>
<li><a class="post-section-overview" href="#heading-introspection-in-python">Introspection in Python</a></li>
<li><a class="post-section-overview" href="#heading-annotations-in-python">Annotations in Python</a></li>
<li><a class="post-section-overview" href="#heading-exceptions-in-python">Exceptions in Python</a></li>
<li><a class="post-section-overview" href="#heading-the-with-statement-in-python">The with Statement in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-3rd-party-packages-in-python-using-pip">How to Install 3rd Party Packages in Python Using pip</a></li>
<li><a class="post-section-overview" href="#heading-list-comprehensions-in-python">List Comprehensions in Python</a></li>
<li><a class="post-section-overview" href="#heading-polymorphism-in-python">Polymorphism in Python</a></li>
<li><a class="post-section-overview" href="#heading-operator-overloading-in-python">Operator Overloading in Python</a></li>
<li><a class="post-section-overview" href="#heading-virtual-environments-in-python">Virtual Environments in Python</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-introduction-to-python">Introduction to Python</h2>
<p>Python is literally eating the programming world. It is growing in popularity and usage in ways that are pretty much unprecedented in the history of computers.</p>
<p>Python excels in a wide variety of scenarios – <strong>Shell scripting</strong>, <strong>task automation</strong>, and <strong>Web development</strong> are just some basic examples.</p>
<p>Python is the language of choice for <strong>data analysis</strong> and <strong>machine learning</strong>, but it can also adapt to create games and work with embedded devices.</p>
<p>Most importantly, it's the language of choice for introductory <strong>computer science courses</strong> in universities all around the world.</p>
<p>Many students learn Python as their first programming language. Many are learning it right now, and many more will learn it in the future. And for many of them, Python will be the only programming language they need.</p>
<p>Thanks to this unique position, Python is likely going to grow even more in the future.</p>
<p>The language is simple, expressive, and it's quite straightforward.</p>
<p>The ecosystem is huge. There seems to be a library for everything you can imagine.</p>
<p>Python is a high-level programming language suitable for beginners thanks to its intuitive syntax, its huge community, and its vibrant ecosystem.</p>
<p>It is also appreciated by professionals across many different fields.</p>
<p>Technically speaking Python is an interpreted language that does not have an intermediate compilation phase like a compiled language, for example C or Java.</p>
<p>And like many interpreted languages, it is dynamically typed. This means that you do not have to indicate the types of the variables you use, and variables are not tied to a specific type.</p>
<p>This has pros and cons. In particular, you write programs faster, but on the other hand you have less help from the tools to prevent possible bugs. This means that you will find out about certain issues only by executing the program at runtime.</p>
<p>Python supports a wide variety of different programming paradigms, including procedural programming, object oriented programming, and functional programming. It's flexible enough to adapt to a lot of different needs.</p>
<p>Created in 1991 by Guido van Rossum, it's been rising in popularity - especially in the past 5 years, as this Google Trends infographic shows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-09-at-19.22.38.png" alt="Screen-Shot-2020-11-09-at-19.22.38" width="600" height="400" loading="lazy"></p>
<p>Starting with Python is very easy. All you need is to install the official package from python.org, for Windows, macOS or Linux, and you're ready to go.</p>
<p>If you are new to programming, in the following posts I will guide you to go from zero to becoming a Python programmer.</p>
<p>And even if you are currently a programmer who specializes in another language, Python is a language worth knowing because I think it's only going to keep growing from here.</p>
<p>Lower level languages like C++ and Rust might be great for expert programmers, but they're daunting to begin with, and they take a long time to master. </p>
<p>Python, on the other hand, is a programming language for everyone – students, people doing their day jobs with Excel, scientists, and more.</p>
<p><strong>It's the language everyone interested in coding should learn first</strong>.</p>
<h2 id="heading-how-to-install-python">How to Install Python</h2>
<p>Go to <a target="_blank" href="https://www.python.org">https://www.python.org</a>, choose the Downloads menu, choose your operating system, and a panel with a link to download the official package will appear:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-09-at-13.57.36-1.png" alt="Screen-Shot-2020-11-09-at-13.57.36-1" width="600" height="400" loading="lazy"></p>
<p>Make sure you follow the specific instructions for your operating system. On macOS you can find a detailed guide on <a target="_blank" href="https://flaviocopes.com/python-installation-macos/">https://flaviocopes.com/python-installation-macos/</a>.</p>
<h2 id="heading-how-to-run-python-programs">How to Run Python Programs</h2>
<p>There are a few different ways to run Python programs.</p>
<p>In particular, there's a distinction between using interactive prompts, where you type Python code and it's immediately executed, and saving a Python program into a file and executing that.</p>
<p>Let's start with interactive prompts.</p>
<p>If you open your terminal and type <code>python</code>, you will see a screen like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-13.44.07.png" alt="Screen-Shot-2020-11-10-at-13.44.07" width="600" height="400" loading="lazy"></p>
<p>This is the Python REPL (Read-Evaluate-Print-Loop).</p>
<p>Notice the <code>&gt;&gt;&gt;</code> symbol, and the cursor after that. You can type any Python code here, and press the <code>enter</code> key to run it.</p>
<p>For example try defining a new variable using</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Flavio"</span>
</code></pre>
<p>and then print its value, using <code>print()</code>:</p>
<pre><code class="lang-python">print(name)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.11.57.png" alt="Screen-Shot-2020-11-10-at-14.11.57" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>Note: in the REPL, you can also just type <code>name</code>, press the <code>enter</code> key and you'll get the value back. But in a program, you are not going to see any output if you do so - you need to use <code>print()</code> instead.</p>
</blockquote>
<p>Any line of Python you write here is going to be executed immediately.</p>
<p>Type <code>quit()</code> to exit this Python REPL.</p>
<p>You can access the same interactive prompt using the IDLE application that's installed by Python automatically:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.13.25.png" alt="Screen-Shot-2020-11-10-at-14.13.25" width="600" height="400" loading="lazy"></p>
<p>This might be more convenient for you because with the mouse you can move around and copy/paste more easily than with the terminal.</p>
<p>Those are the basics that come with Python by default. However I recommend that you install <a target="_blank" href="https://ipython.org/">IPython</a>, probably the best command line REPL application you can find.</p>
<p>Install it with</p>
<pre><code class="lang-sh">pip install ipython
</code></pre>
<p>Make sure the pip binaries are in your path, then run <code>ipython</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-11-at-09.36.29.png" alt="Screen-Shot-2020-11-11-at-09.36.29" width="600" height="400" loading="lazy"></p>
<p><code>ipython</code> is another interface that lets you work with a Python REPL, and provides some nice features like syntax highlighting, code completion, and much more.</p>
<p>The second way to run a Python program is to write your Python program code into a file, for example <code>program.py</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.01.24.png" alt="Screen-Shot-2020-11-10-at-14.01.24" width="600" height="400" loading="lazy"></p>
<p>and then run it with <code>python program.py</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.01.32.png" alt="Screen-Shot-2020-11-10-at-14.01.32" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>Note that we save Python programs with the <code>.py</code> extension - that's a convention.</p>
</blockquote>
<p>In this case the program is executed as a whole, not one line at a time. And that's typically how we run programs.</p>
<p>We use the REPL for quick prototyping and for learning.</p>
<p>On Linux and macOS, a Python program can also be transformed into a shell script, by prepending all its content with a special line that indicates which executable to use to run it.</p>
<p>On my system the Python executable is located in <code>/usr/bin/python3</code>, so I type <code>#!/usr/bin/python3</code> in the first line:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.17.26.png" alt="Screen-Shot-2020-11-10-at-14.17.26" width="600" height="400" loading="lazy"></p>
<p>Then I can set execution permission on the file:</p>
<pre><code class="lang-sh">chmod u+x program.py
</code></pre>
<p>and I can run the program with</p>
<pre><code class="lang-sh">./program.py
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.18.42.png" alt="Screen-Shot-2020-11-10-at-14.18.42" width="600" height="400" loading="lazy"></p>
<p>This is especially useful when you write scripts that interact with the terminal.</p>
<p>We have many other ways to run Python programs.</p>
<p>One of them is using VS Code, and in particular the official Python extension from Microsoft:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.23.32.png" alt="Screen-Shot-2020-11-10-at-14.23.32" width="600" height="400" loading="lazy"></p>
<p>After installing this extension you will have Python code autocompletion and error checking, automatic formatting and code linting with <code>pylint</code>, and some special commands, including:</p>
<p><strong>Python: Start REPL</strong> to run the REPL in the integrated terminal:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.31.36.png" alt="Screen-Shot-2020-11-10-at-14.31.36" width="600" height="400" loading="lazy"></p>
<p><strong>Python: Run Python File in Terminal</strong> to run the current file in the terminal:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.31.06.png" alt="Screen-Shot-2020-11-10-at-14.31.06" width="600" height="400" loading="lazy"></p>
<p><strong>Python: Run Current File in Python Interactive Window</strong>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.30.02-1.png" alt="Screen-Shot-2020-11-10-at-14.30.02-1" width="600" height="400" loading="lazy"></p>
<p>and many more. Just open the command palette (View -&gt; Command Palette, or Cmd-Shift-P) and type <code>python</code> to see all the Python-related commands:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.30.02.png" alt="Screen-Shot-2020-11-10-at-14.30.02" width="600" height="400" loading="lazy"></p>
<p>Another way to easily run Python code is to use repl.it, a very nice website that provides a coding environment you can create and run your apps on, in any language, Python included:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.33.58.png" alt="Screen-Shot-2020-11-10-at-14.33.58" width="600" height="400" loading="lazy"></p>
<p>Signup (it's free), then under "create a repl" click Python:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.46.34.png" alt="Screen-Shot-2020-11-10-at-14.46.34" width="600" height="400" loading="lazy"></p>
<p>and you will be immediately shown an editor with a <code>main.py</code> file, ready to be filled with a lot of Python code:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.47.15.png" alt="Screen-Shot-2020-11-10-at-14.47.15" width="600" height="400" loading="lazy"></p>
<p>Once you have some code, click "Run" to run it on the right side of the window:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.48.09.png" alt="Screen-Shot-2020-11-10-at-14.48.09" width="600" height="400" loading="lazy"></p>
<p>I think repl.it is handy because:</p>
<ul>
<li>you can easily share code just by sharing the link</li>
<li>multiple people can work on the same code</li>
<li>it can host long-running programs</li>
<li>you can install packages</li>
<li>it provides you a key-value database for more complex applications</li>
</ul>
<h2 id="heading-python-2-vs-python-3">Python 2 vs Python 3</h2>
<p>One key topic we should address, right from the start, is the Python 2 vs Python 3 discussion.</p>
<p>Python 3 was introduced in 2008, and it's been in development as the main Python version, while Python 2 continued being maintained with bug fixes and security patches until early 2020.</p>
<p>On that date, Python 2 support was discontinued.</p>
<p>Many programs are still written using Python 2, and organizations still actively work on those, because the migration to Python 3 is not trivial and it would require a lot of work to upgrade those programs. And large and important migrations always introduce new bugs.</p>
<p>But new code, unless you have to adhere to rules set by your organization that forces Python 2, should always be written in Python 3.</p>
<blockquote>
<p>This book focuses on Python 3. </p>
</blockquote>
<h2 id="heading-python-basics">Python Basics</h2>
<h3 id="heading-variables-in-python">Variables in Python</h3>
<p>We can create a new Python variable by assigning a value to a label, using the <code>=</code> assignment operator.</p>
<p>In this example we assign a string with the value "Roger" to the <code>name</code> label:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
</code></pre>
<p>Here's an example with a number:</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>
</code></pre>
<p>A variable name can be composed of characters, numbers, and the <code>_</code> underscore character. It can't start with a number. These are all <strong>valid</strong> variable names:</p>
<pre><code class="lang-python">name1
AGE
aGE
a11111
my_name
_name
</code></pre>
<p>These are <strong>invalid</strong> variable names:</p>
<pre><code class="lang-python"><span class="hljs-number">123</span>
test!
name%
</code></pre>
<p>Other than that, anything is valid unless it's a Python <strong>keyword</strong>. There are some keywords like <code>for</code>, <code>if</code>, <code>while</code>, <code>import</code> and more.</p>
<p>There's no need to memorize them, as Python will alert you if you use one of those as a variable, and you will gradually recognize them as part of the Python programming language syntax.</p>
<h3 id="heading-expressions-and-statements-in-python">Expressions and statements in Python</h3>
<p>We can <em>expression</em> any sort of code that returns a value. For example</p>
<pre><code class="lang-python"><span class="hljs-number">1</span> + <span class="hljs-number">1</span>
<span class="hljs-string">"Roger"</span>
</code></pre>
<p>A statement, on the other hand, is an operation on a value. For example these are 2 statements:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
print(name)
</code></pre>
<p>A program is formed by a series of statements. Each statement is put on its own line, but you can use a semicolon to have more than one statement on a single line:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>; print(name)
</code></pre>
<h3 id="heading-comments">Comments</h3>
<p>In a Python program, everything after a hash mark is ignored, and considered a comment:</p>
<pre><code class="lang-python"><span class="hljs-comment">#this is a commented line</span>

name = <span class="hljs-string">"Roger"</span> <span class="hljs-comment"># this is an inline comment</span>
</code></pre>
<h3 id="heading-indentation-in-python">Indentation in Python</h3>
<p>Indentation in Python is meaningful.</p>
<p>You cannot indent randomly like this:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Flavio"</span>
    print(name)
</code></pre>
<p>Some other languages do not have meaningful whitespace, but in Python, indentation matters.</p>
<p>In this case, if you try to run this program you would get a <code>IndentationError: unexpected indent</code> error, because indenting has a special meaning.</p>
<p>Everything indented belongs to a block, like a control statement or conditional block, or a function or class body. We'll see more about those later on.</p>
<h2 id="heading-data-types-in-python">Data Types in Python</h2>
<p>Python has several built-in types.</p>
<p>If you create the <code>name</code> variable assigning it the value "Roger", automatically this variable now represents a <strong>String</strong> data type.</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
</code></pre>
<p>You can check the type of a variable by using the <code>type()</code> function, passing the variable as an argument, and then comparing the result to <code>str</code>:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
type(name) == str <span class="hljs-comment">#True</span>
</code></pre>
<p>Or using <code>isinstance()</code>:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
isinstance(name, str) <span class="hljs-comment">#True</span>
</code></pre>
<blockquote>
<p>Notice that to see the <code>True</code> value in Python, outside of a REPL, you need to wrap this code inside <code>print()</code>, but for clarity I avoid using it.</p>
</blockquote>
<p>We used the <code>str</code> class here, but the same works for other data types.</p>
<p>First, we have numbers. Integer numbers are represented using the <code>int</code> class. Floating point numbers (fractions) are of type <code>float</code>:</p>
<pre><code class="lang-python">age = <span class="hljs-number">1</span>
type(age) == int <span class="hljs-comment">#True</span>
</code></pre>
<pre><code class="lang-python">fraction = <span class="hljs-number">0.1</span>
type(fraction) == float <span class="hljs-comment">#True</span>
</code></pre>
<p>You saw how to create a type from a value literal, like this:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Flavio"</span>
age = <span class="hljs-number">20</span>
</code></pre>
<p>Python automatically detects the type from the value type.</p>
<p>You can also create a variable of a specific type by using the class constructor, passing a value literal or a variable name:</p>
<pre><code class="lang-python">name = str(<span class="hljs-string">"Flavio"</span>)
anotherName = str(name)
</code></pre>
<p>You can also convert from one type to another by using the class constructor. Python will try to determine the correct value, for example extracting a number from a string:</p>
<pre><code class="lang-python">age = int(<span class="hljs-string">"20"</span>)
print(age) <span class="hljs-comment">#20</span>

fraction = <span class="hljs-number">0.1</span>
intFraction = int(fraction)
print(intFraction) <span class="hljs-comment">#0</span>
</code></pre>
<p>This is called <strong>casting</strong>. Of course this conversion might not always work depending on the value passed. If you write <code>test</code> instead of <code>20</code> in the above string, you'll get a <code>ValueError: invalid literal for int() with base 10: 'test'</code> error.</p>
<p>Those are just the basics of types. We have a lot more types in Python:</p>
<ul>
<li><code>complex</code> for complex numbers</li>
<li><code>bool</code> for booleans</li>
<li><code>list</code> for lists</li>
<li><code>tuple</code> for tuples</li>
<li><code>range</code> for ranges</li>
<li><code>dict</code> for dictionaries</li>
<li><code>set</code> for sets</li>
</ul>
<p>and more!</p>
<p>We'll explore them all soon.</p>
<h2 id="heading-operators-in-python">Operators in Python</h2>
<p>Python operators are symbols that we use to run operations upon values and variables.</p>
<p>We can divide operators based on the kind of operation they perform:</p>
<ul>
<li>assignment operator</li>
<li>arithmetic operators</li>
<li>comparison operators</li>
<li>logical operators</li>
<li>bitwise operators</li>
</ul>
<p>plus some interesting ones like <code>is</code> and <code>in</code>.</p>
<h3 id="heading-assignment-operator-in-python">Assignment operator in Python</h3>
<p>The assignment operator is used to assign a value to a variable:</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>
</code></pre>
<p>Or to assign a variable value to another variable:</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>
anotherVariable = age
</code></pre>
<p>Since Python 3.8, the <code>:=</code> <em>walrus operator</em> is used to assign a value to a variable as part of another operation. For example inside an <code>if</code> or in the conditional part of a loop. More on that later.</p>
<h3 id="heading-arithmetic-operators-in-python">Arithmetic operators in Python</h3>
<p>Python has a number of arithmetic operators: <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code> (division), <code>%</code> (remainder), <code>**</code> (exponentiation) and <code>//</code> (floor division):</p>
<pre><code class="lang-python"><span class="hljs-number">1</span> + <span class="hljs-number">1</span> <span class="hljs-comment">#2</span>
<span class="hljs-number">2</span> - <span class="hljs-number">1</span> <span class="hljs-comment">#1</span>
<span class="hljs-number">2</span> * <span class="hljs-number">2</span> <span class="hljs-comment">#4</span>
<span class="hljs-number">4</span> / <span class="hljs-number">2</span> <span class="hljs-comment">#2</span>
<span class="hljs-number">4</span> % <span class="hljs-number">3</span> <span class="hljs-comment">#1</span>
<span class="hljs-number">4</span> ** <span class="hljs-number">2</span> <span class="hljs-comment">#16</span>
<span class="hljs-number">4</span> // <span class="hljs-number">2</span> <span class="hljs-comment">#2</span>
</code></pre>
<blockquote>
<p>Note that you don't need a space between the operands, but it's good for readability.</p>
</blockquote>
<p><code>-</code> also works as a unary minus operator:</p>
<pre><code class="lang-python">print(<span class="hljs-number">-4</span>) <span class="hljs-comment">#-4</span>
</code></pre>
<p><code>+</code> is also used to concatenate String values:</p>
<pre><code class="lang-python"><span class="hljs-string">"Roger"</span> + <span class="hljs-string">" is a good dog"</span>
<span class="hljs-comment">#Roger is a good dog</span>
</code></pre>
<p>We can combine the assignment operator with arithmetic operators:</p>
<ul>
<li><code>+=</code></li>
<li><code>-=</code></li>
<li><code>*=</code></li>
<li><code>/=</code></li>
<li><code>%=</code></li>
<li>..and so on</li>
</ul>
<p>Example:</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>
age += <span class="hljs-number">1</span>
<span class="hljs-comment"># age is now 9</span>
</code></pre>
<h3 id="heading-comparison-operators-in-python">Comparison operators in Python</h3>
<p>Python defines a few comparison operators:</p>
<ul>
<li><code>==</code></li>
<li><code>!=</code></li>
<li><code>&gt;</code></li>
<li><code>&lt;</code></li>
<li><code>&gt;=</code></li>
<li><code>&lt;=</code></li>
</ul>
<p>You can use those operators to get a boolean value (<code>True</code> or <code>False</code>) depending on the result:</p>
<pre><code class="lang-python">a = <span class="hljs-number">1</span>
b = <span class="hljs-number">2</span>

a == b <span class="hljs-comment">#False</span>
a != b <span class="hljs-comment">#True</span>
a &gt; b <span class="hljs-comment">#False</span>
a &lt;= b <span class="hljs-comment">#True</span>
</code></pre>
<h3 id="heading-boolean-operators-in-python">Boolean operators in Python</h3>
<p>Python gives us the following boolean operators:</p>
<ul>
<li><code>not</code></li>
<li><code>and</code></li>
<li><code>or</code></li>
</ul>
<p>When working with <code>True</code> or <code>False</code> attributes, those work like logical AND, OR and NOT, and are often used in the <code>if</code> conditional expression evaluation:</p>
<pre><code class="lang-python">condition1 = <span class="hljs-literal">True</span>
condition2 = <span class="hljs-literal">False</span>

<span class="hljs-keyword">not</span> condition1 <span class="hljs-comment">#False</span>
condition1 <span class="hljs-keyword">and</span> condition2 <span class="hljs-comment">#False</span>
condition1 <span class="hljs-keyword">or</span> condition2 <span class="hljs-comment">#True</span>
</code></pre>
<p>Otherwise, pay attention to a possible source of confusion:</p>
<p><code>or</code> used in an expression returns the value of the first operand that is not a falsy value (<code>False</code>, <code>0</code>, <code>''</code>, <code>[]</code>..). Otherwise it returns the last operand.</p>
<pre><code class="lang-python">print(<span class="hljs-number">0</span> <span class="hljs-keyword">or</span> <span class="hljs-number">1</span>) <span class="hljs-comment">## 1</span>
print(<span class="hljs-literal">False</span> <span class="hljs-keyword">or</span> <span class="hljs-string">'hey'</span>) <span class="hljs-comment">## 'hey'</span>
print(<span class="hljs-string">'hi'</span> <span class="hljs-keyword">or</span> <span class="hljs-string">'hey'</span>) <span class="hljs-comment">## 'hi'</span>
print([] <span class="hljs-keyword">or</span> <span class="hljs-literal">False</span>) <span class="hljs-comment">## 'False'</span>
print(<span class="hljs-literal">False</span> <span class="hljs-keyword">or</span> []) <span class="hljs-comment">## '[]'</span>
</code></pre>
<p>The Python docs describe it as <code>if x is false, then y, else x</code>.</p>
<p><code>and</code> only evaluates the second argument if the first one is true. So if the first argument is falsy (<code>False</code>, <code>0</code>, <code>''</code>, <code>[]</code>..), it returns that argument. Otherwise it evaluates the second argument:</p>
<pre><code class="lang-python">print(<span class="hljs-number">0</span> <span class="hljs-keyword">and</span> <span class="hljs-number">1</span>) <span class="hljs-comment">## 0</span>
print(<span class="hljs-number">1</span> <span class="hljs-keyword">and</span> <span class="hljs-number">0</span>) <span class="hljs-comment">## 0</span>
print(<span class="hljs-literal">False</span> <span class="hljs-keyword">and</span> <span class="hljs-string">'hey'</span>) <span class="hljs-comment">## False</span>
print(<span class="hljs-string">'hi'</span> <span class="hljs-keyword">and</span> <span class="hljs-string">'hey'</span>) <span class="hljs-comment">## 'hey'</span>
print([] <span class="hljs-keyword">and</span> <span class="hljs-literal">False</span> ) <span class="hljs-comment">## []</span>
print(<span class="hljs-literal">False</span> <span class="hljs-keyword">and</span> [] ) <span class="hljs-comment">## False</span>
</code></pre>
<p>The Python docs describe it as <code>if x is false, then x, else y</code>.</p>
<h3 id="heading-bitwise-operators-in-python">Bitwise operators in Python</h3>
<p>Some operators are used to work on bits and binary numbers:</p>
<ul>
<li><code>&amp;</code> performs binary AND</li>
<li><code>|</code> performs binary OR</li>
<li><code>^</code> performs a binary XOR operation</li>
<li><code>~</code> performs a binary NOT operation</li>
<li><code>&lt;&lt;</code> shift left operation</li>
<li><code>&gt;&gt;</code> shift right operation</li>
</ul>
<p>Bitwise operators are rarely used, only in very specific situations, but they are worth mentioning.</p>
<h3 id="heading-is-and-in-in-python"><code>is</code> and <code>in</code> in Python</h3>
<p><code>is</code> is called the <strong>identity operator</strong>. It is used to compare two objects and returns true if both are the same object. More on objects later.</p>
<p><code>in</code> is called the <strong>membership operator</strong>. Is used to tell if a value is contained in a list, or another sequence. More on lists and other sequences later.</p>
<h2 id="heading-the-ternary-operator-in-python">The Ternary Operator in Python</h2>
<p>The ternary operator in Python allows you to quickly define a conditional.</p>
<p>Let's say you have a function that compares an <code>age</code> variable to the <code>18</code> value, and returns True or False depending on the result.</p>
<p>Instead of writing:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_adult</span>(<span class="hljs-params">age</span>):</span>
    <span class="hljs-keyword">if</span> age &gt; <span class="hljs-number">18</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
</code></pre>
<p>You can implement it with the ternary operator in this way:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_adult</span>(<span class="hljs-params">age</span>):</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span> <span class="hljs-keyword">if</span> age &gt; <span class="hljs-number">18</span> <span class="hljs-keyword">else</span> <span class="hljs-literal">False</span>
</code></pre>
<p>First you define the result if the condition is True, then you evaluate the condition, then you define the result if the condition is false:</p>
<pre><code class="lang-python">&lt;result_if_true&gt; <span class="hljs-keyword">if</span> &lt;condition&gt; <span class="hljs-keyword">else</span> &lt;result_if_false&gt;
</code></pre>
<h2 id="heading-strings-in-python">Strings in Python</h2>
<p>A string in Python is a series of characters enclosed in quotes or double quotes:</p>
<pre><code class="lang-python"><span class="hljs-string">"Roger"</span>
<span class="hljs-string">'Roger'</span>
</code></pre>
<p>You can assign a string value to a variable:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
</code></pre>
<p>You can concatenate two strings using the <code>+</code> operator:</p>
<pre><code class="lang-python">phrase = <span class="hljs-string">"Roger"</span> + <span class="hljs-string">" is a good dog"</span>
</code></pre>
<p>You can append to a string using <code>+=</code>:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
name += <span class="hljs-string">" is a good dog"</span>

print(name) <span class="hljs-comment">#Roger is a good dog</span>
</code></pre>
<p>You can convert a number to a string using the <code>str</code> class constructor:</p>
<pre><code class="lang-python">str(<span class="hljs-number">8</span>) <span class="hljs-comment">#"8"</span>
</code></pre>
<p>This is essential to concatenate a number to a string:</p>
<pre><code class="lang-python">print(<span class="hljs-string">"Roger is "</span> + str(<span class="hljs-number">8</span>) + <span class="hljs-string">" years old"</span>) <span class="hljs-comment">#Roger is 8 years old</span>
</code></pre>
<p>A string can be multi-line when defined with a special syntax, enclosing the string in a set of 3 quotes:</p>
<pre><code class="lang-python">print(<span class="hljs-string">"""Roger is

    8

years old
"""</span>)

<span class="hljs-comment">#double quotes, or single quotes</span>

print(<span class="hljs-string">'''
Roger is

    8

years old
'''</span>)
</code></pre>
<p>A string has a set of built-in methods, like:</p>
<ul>
<li><code>isalpha()</code> to check if a string contains only characters and is not empty</li>
<li><code>isalnum()</code> to check if a string contains characters or digits and is not empty</li>
<li><code>isdecimal()</code> to check if a string contains digits and is not empty</li>
<li><code>lower()</code> to get a lowercase version of a string</li>
<li><code>islower()</code> to check if a string is lowercase</li>
<li><code>upper()</code> to get an uppercase version of a string</li>
<li><code>isupper()</code> to check if a string is uppercase</li>
<li><code>title()</code> to get a capitalized version of a string</li>
<li><code>startsswith()</code> to check if the string starts with a specific substring</li>
<li><code>endswith()</code> to check if the string ends with a specific substring</li>
<li><code>replace()</code> to replace a part of a string</li>
<li><code>split()</code> to split a string on a specific character separator</li>
<li><code>strip()</code> to trim the whitespace from a string</li>
<li><code>join()</code> to append new letters to a string</li>
<li><code>find()</code> to find the position of a substring</li>
</ul>
<p>and many more.</p>
<p>None of those methods alter the original string. They return a new, modified string instead. For example:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
print(name.lower()) <span class="hljs-comment">#"roger"</span>
print(name) <span class="hljs-comment">#"Roger"</span>
</code></pre>
<p>You can use some global functions to work with strings, too.</p>
<p>In particular I think of <code>len()</code>, which gives you the length of a string:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
print(len(name)) <span class="hljs-comment">#5</span>
</code></pre>
<p>The <code>in</code> operator lets you check if a string contains a substring:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
print(<span class="hljs-string">"ger"</span> <span class="hljs-keyword">in</span> name) <span class="hljs-comment">#True</span>
</code></pre>
<p>Escaping is a way to add special characters into a string.</p>
<p>For example, how do you add a double quote into a string that's wrapped into double quotes?</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
</code></pre>
<p><code>"Ro"Ger"</code> will not work, as Python will think the string ends at <code>"Ro"</code>.</p>
<p>The way to go is to escape the double quote inside the string, with the <code>\</code> backslash character:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Ro\"ger"</span>
</code></pre>
<p>This applies to single quotes too <code>\'</code>, and for special formatting characters like <code>\t</code> for tab, <code>\n</code> for new line and <code>\\</code> for the backslash.</p>
<p>Given a string, you can get its characters using square brackets to get a specific item, given its index, starting from 0:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
name[<span class="hljs-number">0</span>] <span class="hljs-comment">#'R'</span>
name[<span class="hljs-number">1</span>] <span class="hljs-comment">#'o'</span>
name[<span class="hljs-number">2</span>] <span class="hljs-comment">#'g'</span>
</code></pre>
<p>Using a negative number will start counting from the end:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
name[<span class="hljs-number">-1</span>] <span class="hljs-comment">#"r"</span>
</code></pre>
<p>You can also use a range, using what we call <strong>slicing</strong>:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
name[<span class="hljs-number">0</span>:<span class="hljs-number">2</span>] <span class="hljs-comment">#"Ro"</span>
name[:<span class="hljs-number">2</span>] <span class="hljs-comment">#"Ro"</span>
name[<span class="hljs-number">2</span>:] <span class="hljs-comment">#"ger"</span>
</code></pre>
<h2 id="heading-booleans-in-python">Booleans in Python</h2>
<p>Python provides the <code>bool</code> type, which can have two values: <code>True</code> and <code>False</code> (capitalized).</p>
<pre><code class="lang-python">done = <span class="hljs-literal">False</span>
done = <span class="hljs-literal">True</span>
</code></pre>
<p>Booleans are especially useful with conditional control structures like <code>if</code> statements:</p>
<pre><code class="lang-python">done = <span class="hljs-literal">True</span>

<span class="hljs-keyword">if</span> done:
    <span class="hljs-comment"># run some code here</span>
<span class="hljs-keyword">else</span>:
    <span class="hljs-comment"># run some other code</span>
</code></pre>
<p>When evaluating a value for <code>True</code> or <code>False</code>, if the value is not a <code>bool</code> we have some rules depending on the type we're checking:</p>
<ul>
<li>numbers are always <code>True</code> except for the number <code>0</code></li>
<li>strings are <code>False</code> only when empty</li>
<li>lists, tuples, sets, and dictionaries are <code>False</code> only when empty</li>
</ul>
<p>You can check if a value is a boolean in this way:</p>
<pre><code class="lang-python">done = <span class="hljs-literal">True</span>
type(done) == bool <span class="hljs-comment">#True</span>
</code></pre>
<p>Or using <code>isinstance()</code>, passing 2 arguments: the variable, and the <code>bool</code> class:</p>
<pre><code class="lang-python">done = <span class="hljs-literal">True</span>
isinstance(done, bool) <span class="hljs-comment">#True</span>
</code></pre>
<p>The global <code>any()</code> function is also very useful when working with booleans, as it returns <code>True</code> if any of the values of the iterable (list, for example) passed as argument are <code>True</code>:</p>
<pre><code class="lang-python">book_1_read = <span class="hljs-literal">True</span>
book_2_read = <span class="hljs-literal">False</span>

read_any_book = any([book_1_read, book_2_read])
</code></pre>
<p>The global <code>all()</code> function is same, but returns <code>True</code> if all of the values passed to it are <code>True</code>:</p>
<pre><code class="lang-python">ingredients_purchased = <span class="hljs-literal">True</span>
meal_cooked = <span class="hljs-literal">False</span>

ready_to_serve = all([ingredients_purchased, meal_cooked])
</code></pre>
<h2 id="heading-numbers-in-python">Numbers in Python</h2>
<p>Numbers in Python can be of 3 types: <code>int</code>, <code>float</code> and <code>complex</code>.</p>
<h3 id="heading-integer-numbers-in-python">Integer numbers in Python</h3>
<p>Integer numbers are represented using the <code>int</code> class. You can define an integer using a value literal:</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>
</code></pre>
<p>You can also define an integer number using the <code>int()</code> constructor:</p>
<pre><code class="lang-python">age = int(<span class="hljs-number">8</span>)
</code></pre>
<p>To check if a variable is of type <code>int</code>, you can use the <code>type()</code> global function:</p>
<pre><code class="lang-python">type(age) == int <span class="hljs-comment">#True</span>
</code></pre>
<h3 id="heading-floating-point-numbers-in-python">Floating point numbers in Python</h3>
<p>Floating point numbers (fractions) are of type <code>float</code>. You can define an integer using a value literal:</p>
<pre><code class="lang-python">fraction = <span class="hljs-number">0.1</span>
</code></pre>
<p>Or using the <code>float()</code> constructor:</p>
<pre><code class="lang-python">fraction = float(<span class="hljs-number">0.1</span>)
</code></pre>
<p>To check if a variable is of type <code>float</code>, you can use the <code>type()</code> global function:</p>
<pre><code class="lang-python">type(fraction) == float <span class="hljs-comment">#True</span>
</code></pre>
<h3 id="heading-complex-numbers-in-python">Complex numbers in Python</h3>
<p>Complex numbers are of type <code>complex</code>.</p>
<p>You can define them using a value literal:</p>
<pre><code class="lang-python">complexNumber = <span class="hljs-number">2</span>+<span class="hljs-number">3j</span>
</code></pre>
<p>or using the <code>complex()</code> constructor:</p>
<pre><code class="lang-python">complexNumber = complex(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
</code></pre>
<p>Once you have a complex number, you can get its real and imaginary part:</p>
<pre><code class="lang-python">complexNumber.real <span class="hljs-comment">#2.0</span>
complexNumber.imag <span class="hljs-comment">#3.0</span>
</code></pre>
<p>Again, to check if a variable is of type <code>complex</code>, you can use the <code>type()</code> global function:</p>
<pre><code class="lang-python">type(complexNumber) == complex <span class="hljs-comment">#True</span>
</code></pre>
<h3 id="heading-arithmetic-operations-on-numbers-in-python">Arithmetic operations on numbers in Python</h3>
<p>You can perform arithmetic operations on numbers, using the arithmetic operators: <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code> (division), <code>%</code> (remainder), <code>**</code> (exponentiation) and <code>//</code> (floor division):</p>
<pre><code class="lang-python"><span class="hljs-number">1</span> + <span class="hljs-number">1</span> <span class="hljs-comment">#2</span>
<span class="hljs-number">2</span> - <span class="hljs-number">1</span> <span class="hljs-comment">#1</span>
<span class="hljs-number">2</span> * <span class="hljs-number">2</span> <span class="hljs-comment">#4</span>
<span class="hljs-number">4</span> / <span class="hljs-number">2</span> <span class="hljs-comment">#2</span>
<span class="hljs-number">4</span> % <span class="hljs-number">3</span> <span class="hljs-comment">#1</span>
<span class="hljs-number">4</span> ** <span class="hljs-number">2</span> <span class="hljs-comment">#16</span>
<span class="hljs-number">4</span> // <span class="hljs-number">2</span> <span class="hljs-comment">#2</span>
</code></pre>
<p>and you can use the compound assignment operators</p>
<ul>
<li><code>+=</code></li>
<li><code>-=</code></li>
<li><code>*=</code></li>
<li><code>/=</code></li>
<li><code>%=</code></li>
<li>..and so on</li>
</ul>
<p>to quickly perform operations on variables, too:</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>
age += <span class="hljs-number">1</span>
</code></pre>
<h3 id="heading-built-in-functions-in-python">Built-in Functions in Python</h3>
<p>There are 2 built-in functions that help with numbers:</p>
<p><code>abs()</code> returns the absolute value of a number.</p>
<p><code>round()</code> given a number, returns its value rounded to the nearest integer:</p>
<pre><code class="lang-python">round(<span class="hljs-number">0.12</span>) <span class="hljs-comment">#0</span>
</code></pre>
<p>You can specify a second parameter to set the decimal point's precision:</p>
<pre><code class="lang-python">round(<span class="hljs-number">0.12</span>, <span class="hljs-number">1</span>) <span class="hljs-comment">#0.1</span>
</code></pre>
<p>Several other math utility functions and constants are provided by the Python standard library:</p>
<ul>
<li>the <code>math</code> package provides general math functions and constants</li>
<li>the <code>cmath</code> package provides utilities to work with complex numbers.</li>
<li>the <code>decimal</code> package provides utilities to work with decimals and floating point numbers.</li>
<li>the <code>fractions</code> package provides utilities to work with rational numbers.</li>
</ul>
<p>We'll explore some of those separately later on.</p>
<h2 id="heading-constants-in-python">Constants in Python</h2>
<p>Python has no way to enforce that a variable should be a constant.</p>
<p>The nearest you can get is to use an enum:</p>
<pre><code class="lang-Python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Constants</span>(<span class="hljs-params">Enum</span>):</span>
    WIDTH = <span class="hljs-number">1024</span>
    HEIGHT = <span class="hljs-number">256</span>
</code></pre>
<p>And get to each value using, for example, <code>Constants.WIDTH.value</code>.</p>
<p>No one can reassign that value.</p>
<p>Otherwise if you want to rely on naming conventions, you can adhere to this one: declare variables that should never change uppercase:</p>
<pre><code class="lang-python">WIDTH = <span class="hljs-number">1024</span>
</code></pre>
<p>No one will prevent you from overwriting this value, and Python will not stop it.</p>
<p>That's what most Python code does that you will see.</p>
<h2 id="heading-enums-in-python">Enums in Python</h2>
<p>Enums are readable names that are bound to a constant value.</p>
<p>To use enums, import <code>Enum</code> from the <code>enum</code> standard library module:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> enum <span class="hljs-keyword">import</span> Enum
</code></pre>
<p>Then you can initialize a new enum in this way:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">State</span>(<span class="hljs-params">Enum</span>):</span>
    INACTIVE = <span class="hljs-number">0</span>
    ACTIVE = <span class="hljs-number">1</span>
</code></pre>
<p>Once you do so, you can reference <code>State.INACTIVE</code> and <code>State.ACTIVE</code>, and they serve as constants.</p>
<p>Now if you try to print <code>State.ACTIVE</code> for example:</p>
<pre><code class="lang-python">print(State.ACTIVE)
</code></pre>
<p>it will not return <code>1</code>, but <code>State.ACTIVE</code>.</p>
<p>The same value can be reached by the number assigned in the enum: <code>print(State(1))</code> will return <code>State.ACTIVE</code>. Same for using the square brackets notation <code>State['ACTIVE']</code>.</p>
<p>You can, however, get the value using <code>State.ACTIVE.value</code>.</p>
<p>You can list all the possible values of an enum:</p>
<pre><code class="lang-python">list(State) <span class="hljs-comment"># [&lt;State.INACTIVE: 0&gt;, &lt;State.ACTIVE: 1&gt;]</span>
</code></pre>
<p>You can count them:</p>
<pre><code class="lang-python">len(State) <span class="hljs-comment"># 2</span>
</code></pre>
<h2 id="heading-user-input-in-python">User Input in Python</h2>
<p>In a Python command line application you can display information to the user using the <code>print()</code> function:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
print(name)
</code></pre>
<p>We can also accept input from the user, using <code>input()</code>:</p>
<pre><code class="lang-python">print(<span class="hljs-string">'What is your age?'</span>)
age = input()
print(<span class="hljs-string">'Your age is '</span> + age)
</code></pre>
<p>This approach gets input at runtime, meaning the program will stop execution and will wait until the user types something and presses the <code>enter</code> key.</p>
<p>You can also do more complex input processing and accept input at program invocation time, and we'll see how to do that later on.</p>
<p>This works for command line applications. Other kinds of applications will need a different way of accepting input.</p>
<h2 id="heading-control-statements-in-python">Control Statements in Python</h2>
<p>When you're dealing with booleans, and expressions that return a boolean in particular, we can make decisions and take different roads depending on their <code>True</code> or <code>False</code> values.</p>
<p>In Python we do so using the <code>if</code> statement:</p>
<pre><code class="lang-python">condition = <span class="hljs-literal">True</span>

<span class="hljs-keyword">if</span> condition == <span class="hljs-literal">True</span>:
    <span class="hljs-comment"># do something</span>
</code></pre>
<p>When the condition test resolves to <code>True</code>, like in the above case, its block gets executed.</p>
<p>What is a block? A block is that part that is indented one level (4 spaces usually) on the right:</p>
<pre><code class="lang-python">condition = <span class="hljs-literal">True</span>

<span class="hljs-keyword">if</span> condition == <span class="hljs-literal">True</span>:
    print(<span class="hljs-string">"The condition"</span>)
    print(<span class="hljs-string">"was true"</span>)
</code></pre>
<p>The block can be formed by a single line, or multiple lines as well, and it ends when you move back to the previous indentation level:</p>
<pre><code class="lang-python">condition = <span class="hljs-literal">True</span>

<span class="hljs-keyword">if</span> condition == <span class="hljs-literal">True</span>:
    print(<span class="hljs-string">"The condition"</span>)
    print(<span class="hljs-string">"was true"</span>)

print(<span class="hljs-string">"Outside of the if"</span>)
</code></pre>
<p>In combination with <code>if</code> you can have an <code>else</code> block that's executed if the condition test of <code>if</code> results to <code>False</code>:</p>
<pre><code class="lang-python">condition = <span class="hljs-literal">True</span>

<span class="hljs-keyword">if</span> condition == <span class="hljs-literal">True</span>:
    print(<span class="hljs-string">"The condition"</span>)
    print(<span class="hljs-string">"was True"</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"The condition"</span>)
    print(<span class="hljs-string">"was False"</span>)
</code></pre>
<p>And you can have different linked <code>if</code> checks with <code>elif</code> that's executed if the previous check was <code>False</code>:</p>
<pre><code class="lang-python">condition = <span class="hljs-literal">True</span>
name = <span class="hljs-string">"Roger"</span>

<span class="hljs-keyword">if</span> condition == <span class="hljs-literal">True</span>:
    print(<span class="hljs-string">"The condition"</span>)
    print(<span class="hljs-string">"was True"</span>)
<span class="hljs-keyword">elif</span> name == <span class="hljs-string">"Roger"</span>:
    print(<span class="hljs-string">"Hello Roger"</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"The condition"</span>)
    print(<span class="hljs-string">"was False"</span>)
</code></pre>
<p>The second block in this case is executed if <code>condition</code> is <code>False</code>, and the <code>name</code> variable value is "Roger".</p>
<p>In a <code>if</code> statement you can have just one <code>if</code> and <code>else</code> check, but multiple series of <code>elif</code> checks:</p>
<pre><code class="lang-python">condition = <span class="hljs-literal">True</span>
name = <span class="hljs-string">"Roger"</span>

<span class="hljs-keyword">if</span> condition == <span class="hljs-literal">True</span>:
    print(<span class="hljs-string">"The condition"</span>)
    print(<span class="hljs-string">"was True"</span>)
<span class="hljs-keyword">elif</span> name == <span class="hljs-string">"Roger"</span>:
    print(<span class="hljs-string">"Hello Roger"</span>)
<span class="hljs-keyword">elif</span> name == <span class="hljs-string">"Syd"</span>:
    print(<span class="hljs-string">"Hello Syd"</span>)
<span class="hljs-keyword">elif</span> name == <span class="hljs-string">"Flavio"</span>:
    print(<span class="hljs-string">"Hello Flavio"</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"The condition"</span>)
    print(<span class="hljs-string">"was False"</span>)
</code></pre>
<p><code>if</code> and <code>else</code> can also be used in an inline format, which lets us return one value or another based on a condition.</p>
<p>Example:</p>
<pre><code class="lang-python">a = <span class="hljs-number">2</span>
result = <span class="hljs-number">2</span> <span class="hljs-keyword">if</span> a == <span class="hljs-number">0</span> <span class="hljs-keyword">else</span> <span class="hljs-number">3</span>
print(result) <span class="hljs-comment"># 3</span>
</code></pre>
<h2 id="heading-lists-in-python">Lists in Python</h2>
<p>Lists are an essential Python data structure.</p>
<p>The allow you to group together multiple values and reference them all with a common name.</p>
<p>For example:</p>
<pre><code class="lang-python">dogs = [<span class="hljs-string">"Roger"</span>, <span class="hljs-string">"Syd"</span>]
</code></pre>
<p>A list can hold values of different types:</p>
<pre><code class="lang-python">items = [<span class="hljs-string">"Roger"</span>, <span class="hljs-number">1</span>, <span class="hljs-string">"Syd"</span>, <span class="hljs-literal">True</span>]
</code></pre>
<p>You can check if an item is contained in a list with the <code>in</code> operator:</p>
<pre><code class="lang-python">print(<span class="hljs-string">"Roger"</span> <span class="hljs-keyword">in</span> items) <span class="hljs-comment"># True</span>
</code></pre>
<p>A list can also be defined as empty:</p>
<pre><code class="lang-python">items = []
</code></pre>
<p>You can reference the items in a list by their index, starting from zero:</p>
<pre><code class="lang-python">items[<span class="hljs-number">0</span>] <span class="hljs-comment"># "Roger"</span>
items[<span class="hljs-number">1</span>] <span class="hljs-comment"># 1</span>
items[<span class="hljs-number">3</span>] <span class="hljs-comment"># True</span>
</code></pre>
<p>Using the same notation you can change the value stored at a specific index:</p>
<pre><code class="lang-python">items[<span class="hljs-number">0</span>] = <span class="hljs-string">"Roger"</span>
</code></pre>
<p>You can also use the <code>index()</code> method:</p>
<pre><code class="lang-python">items.index(<span class="hljs-number">0</span>) <span class="hljs-comment"># "Roger"</span>
items.index(<span class="hljs-number">1</span>) <span class="hljs-comment"># 1</span>
</code></pre>
<p>As with strings, using a negative index will start searching from the end:</p>
<pre><code class="lang-python">items[<span class="hljs-number">-1</span>] <span class="hljs-comment"># True</span>
</code></pre>
<p>You can also extract a part of a list, using slices:</p>
<pre><code class="lang-python">items[<span class="hljs-number">0</span>:<span class="hljs-number">2</span>] <span class="hljs-comment"># ["Roger", 1]</span>
items[<span class="hljs-number">2</span>:] <span class="hljs-comment"># ["Syd", True]</span>
</code></pre>
<p>Get the number of items contained in a list using the <code>len()</code> global function, the same we used to get the length of a string:</p>
<pre><code class="lang-python">len(items) <span class="hljs-comment">#4</span>
</code></pre>
<p>You can add items to the list by using a list <code>append()</code> method:</p>
<pre><code class="lang-python">items.append(<span class="hljs-string">"Test"</span>)
</code></pre>
<p>or the extend() method:</p>
<pre><code class="lang-python">items.extend([<span class="hljs-string">"Test"</span>])
</code></pre>
<p>You can also use the <code>+=</code> operator:</p>
<pre><code class="lang-python">items += [<span class="hljs-string">"Test"</span>]

<span class="hljs-comment"># items is ['Roger', 1, 'Syd', True, 'Test']</span>
</code></pre>
<blockquote>
<p>Tip: with <code>extend()</code> or <code>+=</code> don't forget the square brackets. Don't do <code>items += "Test"</code> or <code>items.extend("Test")</code> or Python will add 4 individual characters to the list, resulting in <code>['Roger', 1, 'Syd', True, 'T', 'e', 's', 't']</code></p>
</blockquote>
<p>Remove an item using the <code>remove()</code> method:</p>
<pre><code class="lang-python">items.remove(<span class="hljs-string">"Test"</span>)
</code></pre>
<p>You can add multiple elements using</p>
<pre><code class="lang-python">items += [<span class="hljs-string">"Test1"</span>, <span class="hljs-string">"Test2"</span>]

<span class="hljs-comment">#or</span>

items.extend([<span class="hljs-string">"Test1"</span>, <span class="hljs-string">"Test2"</span>])
</code></pre>
<p>These append the item to the end of the list.</p>
<p>To add an item in the middle of a list, at a specific index, use the <code>insert()</code> method:</p>
<pre><code class="lang-python">items.insert(<span class="hljs-string">"Test"</span>, <span class="hljs-number">1</span>) <span class="hljs-comment"># add "Test" at index 1</span>
</code></pre>
<p>To add multiple items at a specific index, you need to use slices:</p>
<pre><code class="lang-python">items[<span class="hljs-number">1</span>:<span class="hljs-number">1</span>] = [<span class="hljs-string">"Test1"</span>, <span class="hljs-string">"Test2"</span>]
</code></pre>
<p>Sort a list using the <code>sort()</code> method:</p>
<pre><code class="lang-python">items.sort()
</code></pre>
<blockquote>
<p>Tip: sort() will only work if the list holds values that can be compared. Strings and integers for example can't be compared, and you'll get an error like <code>TypeError: '&lt;' not supported between instances of 'int' and 'str'</code> if you try.</p>
</blockquote>
<p>The <code>sort()</code> methods orders uppercase letters first, then lowercase letters. To fix this, use:</p>
<pre><code class="lang-python">items.sort(key=str.lower)
</code></pre>
<p>instead.</p>
<p>Sorting modifies the original list content. To avoid that, you can copy the list content using</p>
<pre><code class="lang-python">itemscopy = items[:]
</code></pre>
<p>or use the <code>sorted()</code> global function:</p>
<pre><code class="lang-python">print(sorted(items, key=str.lower))
</code></pre>
<p>that will return a new list, sorted, instead of modifying the original list.</p>
<h2 id="heading-tuples-in-python">Tuples in Python</h2>
<p>Tuples are another fundamental Python data structure.</p>
<p>They allow you to create immutable groups of objects. This means that once a tuple is created, it can't be modified. You can't add or remove items.</p>
<p>They are created in a way similar to lists, but using parentheses instead of square brackets:</p>
<pre><code class="lang-python">names = (<span class="hljs-string">"Roger"</span>, <span class="hljs-string">"Syd"</span>)
</code></pre>
<p>A tuple is ordered, like a list, so you can get its values by referencing an index value:</p>
<pre><code class="lang-python">names[<span class="hljs-number">0</span>] <span class="hljs-comment"># "Roger"</span>
names[<span class="hljs-number">1</span>] <span class="hljs-comment"># "Syd"</span>
</code></pre>
<p>You can also use the <code>index()</code> method:</p>
<pre><code class="lang-python">names.index(<span class="hljs-string">'Roger'</span>) <span class="hljs-comment"># 0</span>
names.index(<span class="hljs-string">'Syd'</span>)   <span class="hljs-comment"># 1</span>
</code></pre>
<p>As with strings and lists, using a negative index will start searching from the end:</p>
<pre><code class="lang-python">names[<span class="hljs-number">-1</span>] <span class="hljs-comment"># True</span>
</code></pre>
<p>You can count the items in a tuple with the <code>len()</code> function:</p>
<pre><code class="lang-python">len(names) <span class="hljs-comment"># 2</span>
</code></pre>
<p>You can check if an item is contained in a tuple with the <code>in</code> operator:</p>
<pre><code class="lang-python">print(<span class="hljs-string">"Roger"</span> <span class="hljs-keyword">in</span> names) <span class="hljs-comment"># True</span>
</code></pre>
<p>You can also extract a part of a tuple, using slices:</p>
<pre><code class="lang-python">names[<span class="hljs-number">0</span>:<span class="hljs-number">2</span>] <span class="hljs-comment"># ('Roger', 'Syd')</span>
names[<span class="hljs-number">1</span>:] <span class="hljs-comment"># ('Syd',)</span>
</code></pre>
<p>Get the number of items in a tuple using the <code>len()</code> global function, the same we used to get the length of a string:</p>
<pre><code class="lang-python">len(names) <span class="hljs-comment">#2</span>
</code></pre>
<p>You can create a sorted version of a tuple using the <code>sorted()</code> global function:</p>
<pre><code class="lang-python">sorted(names)
</code></pre>
<p>You can create a new tuple from existing tuples using the <code>+</code> operator:</p>
<pre><code class="lang-python">newTuple = names + (<span class="hljs-string">"Vanille"</span>, <span class="hljs-string">"Tina"</span>)
</code></pre>
<h2 id="heading-dictionaries-in-python">Dictionaries in Python</h2>
<p>Dictionaries are a very important Python data structure.</p>
<p>While lists allow you to create collections of values, dictionaries allow you to create collections of <strong>key / value pairs</strong>.</p>
<p>Here is a dictionary example with one key/value pair:</p>
<pre><code class="lang-python">dog = { <span class="hljs-string">'name'</span>: <span class="hljs-string">'Roger'</span> }
</code></pre>
<p>The key can be any immutable value like a string, a number or a tuple. The value can be anything you want.</p>
<p>A dictionary can contain multiple key/value pairs:</p>
<pre><code class="lang-python">dog = { <span class="hljs-string">'name'</span>: <span class="hljs-string">'Roger'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">8</span> }
</code></pre>
<p>You can access individual key values using this notation:</p>
<pre><code class="lang-python">dog[<span class="hljs-string">'name'</span>] <span class="hljs-comment"># 'Roger'</span>
dog[<span class="hljs-string">'age'</span>]  <span class="hljs-comment"># 8</span>
</code></pre>
<p>Using the same notation you can change the value stored at a specific index:</p>
<pre><code class="lang-python">dog[<span class="hljs-string">'name'</span>] = <span class="hljs-string">'Syd'</span>
</code></pre>
<p>And another way is using the <code>get()</code> method, which has an option to add a default value:</p>
<pre><code class="lang-python">dog.get(<span class="hljs-string">'name'</span>) <span class="hljs-comment"># 'Roger'</span>
dog.get(<span class="hljs-string">'test'</span>, <span class="hljs-string">'default'</span>) <span class="hljs-comment"># 'default'</span>
</code></pre>
<p>The <code>pop()</code> method retrieves the value of a key, and subsequently deletes the item from the dictionary:</p>
<pre><code class="lang-python">dog.pop(<span class="hljs-string">'name'</span>) <span class="hljs-comment"># 'Roger'</span>
</code></pre>
<p>The <code>popitem()</code> method retrieves and removes the last key/value pair inserted into the dictionary:</p>
<pre><code class="lang-python">dog.popitem()
</code></pre>
<p>You can check if a key is contained into a dictionary with the <code>in</code> operator:</p>
<pre><code class="lang-python"><span class="hljs-string">'name'</span> <span class="hljs-keyword">in</span> dog <span class="hljs-comment"># True</span>
</code></pre>
<p>Get a list with the keys in a dictionary using the <code>keys()</code> method, passing its result to the <code>list()</code> constructor:</p>
<pre><code class="lang-python">list(dog.keys()) <span class="hljs-comment"># ['name', 'age']</span>
</code></pre>
<p>Get the values using the <code>values()</code> method, and the key/value pairs tuples using the <code>items()</code> method:</p>
<pre><code class="lang-python">print(list(dog.values()))
<span class="hljs-comment"># ['Roger', 8]</span>

print(list(dog.items()))
<span class="hljs-comment"># [('name', 'Roger'), ('age', 8)]</span>
</code></pre>
<p>Get a dictionary length using the <code>len()</code> global function, the same we used to get the length of a string or the items in a list:</p>
<pre><code class="lang-python">len(dog) <span class="hljs-comment">#2</span>
</code></pre>
<p>You can add a new key/value pair to the dictionary in this way:</p>
<pre><code class="lang-python">dog[<span class="hljs-string">'favorite food'</span>] = <span class="hljs-string">'Meat'</span>
</code></pre>
<p>You can remove a key/value pair from a dictionary using the <code>del</code> statement:</p>
<pre><code class="lang-python"><span class="hljs-keyword">del</span> dog[<span class="hljs-string">'favorite food'</span>]
</code></pre>
<p>To copy a dictionary, use the copy() method:</p>
<pre><code class="lang-python">dogCopy = dog.copy()
</code></pre>
<h2 id="heading-sets-in-python">Sets in Python</h2>
<p>Sets are another important Python data structure.</p>
<p>We can say they work like tuples, but they are not ordered, and they are <strong>mutable</strong>.</p>
<p>Or we can say they work like dictionaries, but they don't have keys.</p>
<p>They also have an immutable version, called <code>frozenset</code>.</p>
<p>You can create a set using this syntax:</p>
<pre><code class="lang-python">names = {<span class="hljs-string">"Roger"</span>, <span class="hljs-string">"Syd"</span>}
</code></pre>
<p>Sets work well when you think about them as mathematical sets.</p>
<p>You can intersect two sets:</p>
<pre><code class="lang-python">set1 = {<span class="hljs-string">"Roger"</span>, <span class="hljs-string">"Syd"</span>}
set2 = {<span class="hljs-string">"Roger"</span>}

intersect = set1 &amp; set2 <span class="hljs-comment">#{'Roger'}</span>
</code></pre>
<p>You can create a union of two sets:</p>
<pre><code class="lang-python">set1 = {<span class="hljs-string">"Roger"</span>, <span class="hljs-string">"Syd"</span>}
set2 = {<span class="hljs-string">"Luna"</span>}

union = set1 | set2
<span class="hljs-comment">#{'Syd', 'Luna', 'Roger'}</span>
</code></pre>
<p>You can get the difference between two sets:</p>
<pre><code class="lang-python">set1 = {<span class="hljs-string">"Roger"</span>, <span class="hljs-string">"Syd"</span>}
set2 = {<span class="hljs-string">"Roger"</span>}

difference = set1 - set2 <span class="hljs-comment">#{'Syd'}</span>
</code></pre>
<p>You can check if a set is a superset of another (and of course if a set is a subset of another):</p>
<pre><code class="lang-python">set1 = {<span class="hljs-string">"Roger"</span>, <span class="hljs-string">"Syd"</span>}
set2 = {<span class="hljs-string">"Roger"</span>}

isSuperset = set1 &gt; set2 <span class="hljs-comment"># True</span>
</code></pre>
<p>You can count the items in a set with the <code>len()</code> global function:</p>
<pre><code class="lang-python">names = {<span class="hljs-string">"Roger"</span>, <span class="hljs-string">"Syd"</span>}
len(names) <span class="hljs-comment"># 2</span>
</code></pre>
<p>You can get a list from the items in a set by passing the set to the <code>list()</code> constructor:</p>
<pre><code class="lang-python">names = {<span class="hljs-string">"Roger"</span>, <span class="hljs-string">"Syd"</span>}
list(names) <span class="hljs-comment">#['Syd', 'Roger']</span>
</code></pre>
<p>You can check if an item is contained in a set with the <code>in</code> operator:</p>
<pre><code class="lang-python">print(<span class="hljs-string">"Roger"</span> <span class="hljs-keyword">in</span> names) <span class="hljs-comment"># True</span>
</code></pre>
<h2 id="heading-functions-in-python">Functions in Python</h2>
<p>A function lets us create a set of instructions that we can run when needed.</p>
<p>Functions are essential in Python and in many other programming languages. They help us create meaningful programs, because they allow us to decompose a program into manageable parts, and they promote readability and code reuse.</p>
<p>Here is an example function called <code>hello</code> that prints "Hello!":</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>():</span>
    print(<span class="hljs-string">'Hello!'</span>)
</code></pre>
<p>This is the function <strong>definition</strong>. Thereis a name (<code>hello</code>) and a body, the set of instructions, which is the part that follows the colon. It's indented one level on the right.</p>
<p>To run this function, we must call it. This is the syntax to call the function:</p>
<pre><code class="lang-python">hello()
</code></pre>
<p>We can execute this function once, or multiple times.</p>
<p>The name of the function, <code>hello</code>, is very important. It should be descriptive, so anyone calling it can imagine what the function does.</p>
<p>A function can accept one or more parameters:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>(<span class="hljs-params">name</span>):</span>
    print(<span class="hljs-string">'Hello '</span> + name + <span class="hljs-string">'!'</span>)
</code></pre>
<p>In this case we call the function by passing the argument</p>
<pre><code class="lang-python">hello(<span class="hljs-string">'Roger'</span>)
</code></pre>
<blockquote>
<p>We call <em>parameters</em> the values accepted by the function inside the function definition, and <em>arguments</em> the values we pass to the function when we call it. It's common to get confused about this distinction.</p>
</blockquote>
<p>An argument can have a default value that's applied if the argument is not specified:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>(<span class="hljs-params">name=<span class="hljs-string">'my friend'</span></span>):</span>
    print(<span class="hljs-string">'Hello '</span> + name + <span class="hljs-string">'!'</span>)

hello()
<span class="hljs-comment">#Hello my friend!</span>
</code></pre>
<p>Here's how we can accept multiple parameters:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>(<span class="hljs-params">name, age</span>):</span>
    print(<span class="hljs-string">'Hello '</span> + name + <span class="hljs-string">', you are '</span> + str(age) + <span class="hljs-string">' years old!'</span>)
</code></pre>
<p>In this case we call the function passing a set of arguments:</p>
<pre><code class="lang-python">hello(<span class="hljs-string">'Roger'</span>, <span class="hljs-number">8</span>)
</code></pre>
<p>Parameters are passed by reference. All types in Python are objects, but some of them are immutable, including integers, booleans, floats, strings, and tuples. This means that if you pass them as parameters and you modify their value inside the function, the new value is not reflected outside of the function:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">change</span>(<span class="hljs-params">value</span>):</span>
    value = <span class="hljs-number">2</span>

val = <span class="hljs-number">1</span>
change(val)

print(val) <span class="hljs-comment">#1</span>
</code></pre>
<p>If you pass an object that's not immutable, and you change one of its properties, the change will be reflected outside.</p>
<p>A function can return a value, using the <code>return</code> statement. For example in this case we return the <code>name</code> parameter name:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>(<span class="hljs-params">name</span>):</span>
    print(<span class="hljs-string">'Hello '</span> + name + <span class="hljs-string">'!'</span>)
    <span class="hljs-keyword">return</span> name
</code></pre>
<p>When the function meets the <code>return</code> statement, the function ends.</p>
<p>We can omit the value:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>(<span class="hljs-params">name</span>):</span>
    print(<span class="hljs-string">'Hello '</span> + name + <span class="hljs-string">'!'</span>)
    <span class="hljs-keyword">return</span>
</code></pre>
<p>We can have the return statement inside a conditional, which is a common way to end a function if a starting condition is not met:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>(<span class="hljs-params">name</span>):</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> name:
        <span class="hljs-keyword">return</span>
    print(<span class="hljs-string">'Hello '</span> + name + <span class="hljs-string">'!'</span>)
</code></pre>
<p>If we call the function passing a value that evaluates to <code>False</code>, like an empty string, the function is terminated before reaching the <code>print()</code> statement.</p>
<p>You can return multiple values by using comma separated values:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>(<span class="hljs-params">name</span>):</span>
    print(<span class="hljs-string">'Hello '</span> + name + <span class="hljs-string">'!'</span>)
    <span class="hljs-keyword">return</span> name, <span class="hljs-string">'Roger'</span>, <span class="hljs-number">8</span>
</code></pre>
<p>In this case calling <code>hello('Syd')</code> the return value is a tuple containing those 3 values: <code>('Syd', 'Roger', 8)</code>.</p>
<h2 id="heading-objects-in-python">Objects in Python</h2>
<p>Everything in Python is an object.</p>
<p>Even values of basic primitive types (integer, string, float..) are objects. Lists are objects, as are tuples, dictionaries, everything.</p>
<p>Objects have <strong>attributes</strong> and <strong>methods</strong> that can be accessed using the dot syntax.</p>
<p>For example, try defining a new variable of type <code>int</code>:</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>
</code></pre>
<p><code>age</code> now has access to the properties and methods defined for all <code>int</code> objects.</p>
<p>This includes, for example, access to the real and imaginary part of that number:</p>
<pre><code class="lang-python">print(age.real) <span class="hljs-comment"># 8</span>
print(age.imag) <span class="hljs-comment"># 0</span>

print(age.bit_length()) <span class="hljs-comment">#4</span>

<span class="hljs-comment"># the bit_length() method returns the number of bits necessary to represent this number in binary notation</span>
</code></pre>
<p>A variable holding a list value has access to a different set of methods:</p>
<pre><code class="lang-python">items = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
items.append(<span class="hljs-number">3</span>)
items.pop()
</code></pre>
<p>The methods depend on the type of value.</p>
<p>The <code>id()</code> global function provided by Python lets you inspect the location in memory for a particular object.</p>
<pre><code class="lang-python">id(age) <span class="hljs-comment"># 140170065725376</span>
</code></pre>
<blockquote>
<p>Your memory value will change - I am only showing it as an example.</p>
</blockquote>
<p>If you assign a different value to the variable, its address will change, because the content of the variable has been replaced with another value stored in another location in memory:</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>

print(id(age)) <span class="hljs-comment"># 140535918671808</span>

age = <span class="hljs-number">9</span>

print(id(age)) <span class="hljs-comment"># 140535918671840</span>
</code></pre>
<p>But if you modify the object using its methods, the address stays the same:</p>
<pre><code class="lang-python">items = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]

print(id(items)) <span class="hljs-comment"># 140093713593920</span>

items.append(<span class="hljs-number">3</span>)

print(items) <span class="hljs-comment"># [1, 2, 3]</span>
print(id(items)) <span class="hljs-comment"># 140093713593920</span>
</code></pre>
<p>The address only changes if you reassign a variable to another value.</p>
<p>Some objects are <em>mutable</em>, while others are <em>immutable</em>. This depends on the object itself. </p>
<p>If the object provides methods to change its content, then it's mutable. Otherwise it's immutable. </p>
<p>Most types defined by Python are immutable. For example an <code>int</code> is immutable. There are no methods to change its value. If you increment the value using</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>
age = age + <span class="hljs-number">1</span>

<span class="hljs-comment">#or</span>

age += <span class="hljs-number">1</span>
</code></pre>
<p>and you check with <code>id(age)</code>, you will find that <code>age</code> points to a different memory location. The original value has not mutated, we just switched to another value.</p>
<h2 id="heading-loops-in-python">Loops in Python</h2>
<p>Loops are one essential part of programming.</p>
<p>In Python we have 2 kinds of loops: <strong>while loops</strong> and <strong>for loops</strong>.</p>
<h3 id="heading-while-loops-in-python"><code>while</code> loops in Python</h3>
<p><code>while</code> loops are defined using the <code>while</code> keyword, and they repeat their block until the condition is evaluated as <code>False</code>:</p>
<pre><code class="lang-python">condition = <span class="hljs-literal">True</span>
<span class="hljs-keyword">while</span> condition == <span class="hljs-literal">True</span>:
    print(<span class="hljs-string">"The condition is True"</span>)
</code></pre>
<p>This is an <strong>infinite loop</strong>. It never ends.</p>
<p>Let's halt the loop right after the first iteration:</p>
<pre><code class="lang-python">condition = <span class="hljs-literal">True</span>
<span class="hljs-keyword">while</span> condition == <span class="hljs-literal">True</span>:
    print(<span class="hljs-string">"The condition is True"</span>)
    condition = <span class="hljs-literal">False</span>

print(<span class="hljs-string">"After the loop"</span>)
</code></pre>
<p>In this case, the first iteration is run, as the condition test is evaluated to <code>True</code>. At the second iteration, the condition test evaluates to <code>False</code>, so the control goes to the next instruction after the loop.</p>
<p>It's common to have a counter to stop the iteration after some number of cycles:</p>
<pre><code class="lang-python">count = <span class="hljs-number">0</span>
<span class="hljs-keyword">while</span> count &lt; <span class="hljs-number">10</span>:
    print(<span class="hljs-string">"The condition is True"</span>)
    count = count + <span class="hljs-number">1</span>

print(<span class="hljs-string">"After the loop"</span>)
</code></pre>
<h3 id="heading-for-loops-in-python"><code>for</code> loops in Python</h3>
<p>Using <code>for</code> loops we can tell Python to execute a block for a pre-determined amount of times, up front, and without the need of a separate variable and conditional to check its value.</p>
<p>For example we can iterate the items in a list:</p>
<pre><code class="lang-python">items = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
<span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> items:
    print(item)
</code></pre>
<p>Or, you can iterate a specific amount of times using the <code>range()</code> function:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> range(<span class="hljs-number">04</span>):
    print(item)
</code></pre>
<p><code>range(4)</code> creates a sequence that starts from 0 and contains 4 items: <code>[0, 1, 2, 3]</code>.</p>
<p>To get the index, you should wrap the sequence into the <code>enumerate()</code> function:</p>
<pre><code class="lang-python">items = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
<span class="hljs-keyword">for</span> index, item <span class="hljs-keyword">in</span> enumerate(items):
    print(index, item)
</code></pre>
<h3 id="heading-break-and-continue-in-python">Break and continue in Python</h3>
<p>Both <code>while</code> and <code>for</code> loops can be interrupted inside the block, using two special keywords: <code>break</code> and <code>continue</code>.</p>
<p><code>continue</code> stops the current iteration and tells Python to execute the next one.</p>
<p><code>break</code> stops the loop altogether, and goes on with the next instruction after the loop ends.</p>
<p>The first example here prints <code>1, 3, 4</code>. The second example prints <code>1</code>:</p>
<pre><code class="lang-python">items = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
<span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> items:
    <span class="hljs-keyword">if</span> item == <span class="hljs-number">2</span>:
        <span class="hljs-keyword">continue</span>
    print(item)
</code></pre>
<pre><code class="lang-python">items = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
<span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> items:
    <span class="hljs-keyword">if</span> item == <span class="hljs-number">2</span>:
        <span class="hljs-keyword">break</span>
    print(item)
</code></pre>
<h2 id="heading-classes-in-python">Classes in Python</h2>
<p>In addition to using the Python-provided types, we can declare our own classes, and from classes we can instantiate objects.</p>
<p>An object is an instance of a class. A class is the type of an object.</p>
<p>We can define a class in this way:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> &lt;<span class="hljs-title">class_name</span>&gt;:</span>
    <span class="hljs-comment"># my class</span>
</code></pre>
<p>For example let's define a Dog class</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>:</span>
    <span class="hljs-comment"># the Dog class</span>
</code></pre>
<p>A class can define methods:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>:</span>
    <span class="hljs-comment"># the Dog class</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bark</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">'WOF!'</span>)
</code></pre>
<blockquote>
<p><code>self</code> as the argument of the method points to the current object instance, and must be specified when defining a method.</p>
</blockquote>
<p>We create an instance of a class, an <strong>object</strong>, using this syntax:</p>
<pre><code class="lang-python">roger = Dog()
</code></pre>
<p>Now <code>roger</code> is a new object of type Dog.</p>
<p>If you run</p>
<pre><code class="lang-python">print(type(roger))
</code></pre>
<p>You will get <code>&lt;class '__main__.Dog'&gt;</code></p>
<p>A special type of method, <code>__init__()</code> is called constructor, and we can use it to initialize one or more properties when we create a new object from that class:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>:</span>
    <span class="hljs-comment"># the Dog class</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name, age</span>):</span>
        self.name = name
        self.age = age

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bark</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">'WOF!'</span>)
</code></pre>
<p>We use it in this way:</p>
<pre><code class="lang-python">roger = Dog(<span class="hljs-string">'Roger'</span>, <span class="hljs-number">8</span>)
print(roger.name) <span class="hljs-comment"># 'Roger'</span>
print(roger.age)  <span class="hljs-comment"># 8</span>

roger.bark() <span class="hljs-comment"># 'WOF!'</span>
</code></pre>
<p>One important feature of classes is inheritance.</p>
<p>We can create an Animal class with a method <code>walk()</code>:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">walk</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">'Walking..'</span>)
</code></pre>
<p>and the Dog class can inherit from Animal:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>(<span class="hljs-params">Animal</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bark</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">'WOF!'</span>)
</code></pre>
<p>Now creating a new object of class <code>Dog</code> will have the <code>walk()</code> method as that's inherited from <code>Animal</code>:</p>
<pre><code class="lang-python">roger = Dog()
roger.walk() <span class="hljs-comment"># 'Walking..'</span>
roger.bark() <span class="hljs-comment"># 'WOF!'</span>
</code></pre>
<h2 id="heading-modules-in-python">Modules in Python</h2>
<p>Every Python file is a module.</p>
<p>You can import a module from other files, and that's the base of any program of moderate complexity, as it promotes a sensible organization and code reuse.</p>
<p>In the typical Python program, one file acts as the entry point. The other files are modules and expose functions that we can call from other files.</p>
<p>The file <code>dog.py</code> contains this code:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bark</span>():</span>
    print(<span class="hljs-string">'WOF!'</span>)
</code></pre>
<p>We can import this function from another file using <code>import</code>. And once we do, we can reference the function using the dot notation, <code>dog.bark()</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> dog

dog.bark()
</code></pre>
<p>Or, we can use the <code>from .. import</code> syntax and call the function directly:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> dog <span class="hljs-keyword">import</span> bark

bark()
</code></pre>
<p>The first strategy allows us to load everything defined in a file.</p>
<p>The second strategy lets us pick the things we need.</p>
<p>Those modules are specific to your program, and importing depends on the location of the file in the filesystem.</p>
<p>Suppose you put <code>dog.py</code> in a <code>lib</code> subfolder.</p>
<p>In that folder, you need to create an empty file named <code>__init__.py</code>. This tells Python the folder contains modules.</p>
<p>Now you can choose - you can import <code>dog</code> from <code>lib</code>:</p>
<pre><code class="lang-py"><span class="hljs-keyword">from</span> lib <span class="hljs-keyword">import</span> dog

dog.bark()
</code></pre>
<p>or you can reference the <code>dog</code> module specific function importing from <code>lib.dog</code>:</p>
<pre><code class="lang-py"><span class="hljs-keyword">from</span> lib.dog <span class="hljs-keyword">import</span> bark

bark()
</code></pre>
<h2 id="heading-the-python-standard-library">The Python Standard Library</h2>
<p>Python exposes a lot of built-in functionality through its <strong>standard library</strong>.</p>
<p>The standard library is a huge collection of all sort of utilities, ranging from math utilities to debugging to creating graphical user interfaces.</p>
<p>You can find the full list of standard library modules here: https://docs.python.org/3/library/index.html</p>
<p>Some of the important modules are:</p>
<ul>
<li><code>math</code> for math utilities</li>
<li><code>re</code> for regular expressions</li>
<li><code>json</code> to work with JSON</li>
<li><code>datetime</code> to work with dates</li>
<li><code>sqlite3</code> to use SQLite</li>
<li><code>os</code> for Operating System utilities</li>
<li><code>random</code> for random number generation</li>
<li><code>statistics</code> for statistics utilities</li>
<li><code>requests</code> to perform HTTP network requests</li>
<li><code>http</code> to create HTTP servers</li>
<li><code>urllib</code> to manage URLs</li>
</ul>
<p>Let's introduce how to <em>use</em> a module of the standard library. You already know how to use modules you create, importing from other files in the program folder.</p>
<p>Well that's the same with modules provided by the standard library:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> math

math.sqrt(<span class="hljs-number">4</span>) <span class="hljs-comment"># 2.0</span>
</code></pre>
<p>or</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> sqrt

sqrt(<span class="hljs-number">4</span>) <span class="hljs-comment"># 2.0</span>
</code></pre>
<p>We'll soon explore the most important modules individually to understand what we can do with them.</p>
<h2 id="heading-the-pep8-python-style-guide">The PEP8 Python Style Guide</h2>
<p>When you write code, you should adhere to the conventions of the programming language you use.</p>
<p>If you learn the right naming and formatting conventions right from the start, it will be easier to read code written by other people, and people will find your code easier to read.</p>
<p>Python defines its conventions in the PEP8 style guide. PEP stands for <em>Python Enhancement Proposals</em> and it's the place where all Python language enhancements and discussions happen. </p>
<p>There are a lot of PEP proposals, all available at https://www.python.org/dev/peps/.</p>
<p>PEP8 is one of the first ones, and one of the most important, too. It defines the formatting and also some rules on how to write Python in a "pythonic" way.</p>
<p>You can read its full content here: https://www.python.org/dev/peps/pep-0008/ but here's a quick summary of the important points you can start with:</p>
<ul>
<li>Indent using spaces, not tabs</li>
<li>Indent using 4 spaces.</li>
<li>Python files are encoded in UTF-8</li>
<li>Use maximum 80 columns for your code</li>
<li>Write each statement on its own line</li>
<li>Functions, variable names and file names are lowercase, with underscores between words (snake_case)</li>
<li>Class names are capitalized, separate words are written with the capital letter too, (CamelCase)</li>
<li>Package names are lowercase and do not have underscores between words</li>
<li>Variables that should not change (constants) are written in uppercase</li>
<li>Variable names should be meaningful</li>
<li>Add useful comments, but avoid obvious comments</li>
<li>Add spaces around operators</li>
<li>Do not use unnecessary whitespace</li>
<li>Add a blank line before a function</li>
<li>Add a blank line between methods in a class</li>
<li>Inside functions/methods, blank lines can be used to separate related blocks of code to help readability</li>
</ul>
<h2 id="heading-debugging-in-python">Debugging in Python</h2>
<p>Debugging is one of the best skills you can learn, as it will help you in many difficult situations.</p>
<p>Every language has its debugger. Python has <code>pdb</code>, available through the standard library.</p>
<p>You debug by adding one breakpoint into your code:</p>
<pre><code class="lang-python">breakpoint()
</code></pre>
<blockquote>
<p>You can add more breakpoints if needed.</p>
</blockquote>
<p>When the Python interpreter hits a breakpoint in your code, it will stop, and it will tell you what is the next instruction it will run.</p>
<p>Then and you can do a few things.</p>
<p>You can type the name of any variable to inspect its value.</p>
<p>You can press <code>n</code> to step to the next line in the current function. If the code calls functions, the debugger does not get into them, and considers them "black boxes".</p>
<p>You can press <code>s</code> to step to the next line in the current function. If the next line is a function, the debugger goes into that, and you can then run one instruction of that function at a time.</p>
<p>You can press <code>c</code> to continue the execution of the program normally, without the need to do it step-by-step.</p>
<p>You can press <code>q</code> to stop the execution of the program.</p>
<p>Debugging is useful to evaluate the result of an instruction, and it's especially good to know how to use it when you have complex iterations or algorithms that you want to fix.</p>
<h2 id="heading-variable-scope-in-python">Variable Scope in Python</h2>
<p>When you declare a variable, that variable is visible in parts of your program, depending on where you declare it.</p>
<p>If you declare it outside of any function, the variable is visible to any code running after the declaration, including functions:</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test</span>():</span>
    print(age)

print(age) <span class="hljs-comment"># 8</span>
test() <span class="hljs-comment"># 8</span>
</code></pre>
<p>We call it a <strong>global variable</strong>.</p>
<p>If you define a variable inside a function, that variable is a <strong>local variable</strong>, and it is only visible inside that function. Outside the function, it is not reachable:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test</span>():</span>
    age = <span class="hljs-number">8</span>
    print(age)

test() <span class="hljs-comment"># 8</span>

print(age)
<span class="hljs-comment"># NameError: name 'age' is not defined</span>
</code></pre>
<h2 id="heading-how-to-accept-arguments-from-the-command-line-in-python">How to Accept Arguments from the Command Line in Python</h2>
<p>Python offers several ways to handle arguments passed when we invoke the program from the command line.</p>
<p>So far you've run programs either from a REPL, or using</p>
<pre><code class="lang-sh">python &lt;filename&gt;.py
</code></pre>
<p>You can pass additional arguments and options when you do so, like this:</p>
<pre><code class="lang-sh">python &lt;filename&gt;.py &lt;argument1&gt;
python &lt;filename&gt;.py &lt;argument1&gt; &lt;argument2&gt;
</code></pre>
<p>A basic way to handle those arguments is to use the <code>sys</code> module from the standard library.</p>
<p>You can get the arguments passed in the <code>sys.argv</code> list:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sys
print(len(sys.argv))
print(sys.argv)
</code></pre>
<p>The <code>sys.argv</code> list contains as the first item the name of the file that was run, for example <code>['main.py']</code>.</p>
<p>This is a simple way, but you have to do a lot of work. You need to validate arguments, make sure their type is correct, and you need to print feedback to the user if they are not using the program correctly.</p>
<p>Python provides another package in the standard library to help you: <code>argparse</code>.</p>
<p>First you import <code>argparse</code> and you call <code>argparse.ArgumentParser()</code>, passing the description of your program:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> argparse

parser = argparse.ArgumentParser(
    description=<span class="hljs-string">'This program prints the name of my dogs'</span>
)
</code></pre>
<p>Then you proceed to add arguments you want to accept.
For example in this program we accept a <code>-c</code> option to pass a color, like this: <code>python program.py -c red</code></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> argparse

parser = argparse.ArgumentParser(
    description=<span class="hljs-string">'This program prints a color HEX value'</span>
)

parser.add_argument(<span class="hljs-string">'-c'</span>, <span class="hljs-string">'--color'</span>, metavar=<span class="hljs-string">'color'</span>, required=<span class="hljs-literal">True</span>, help=<span class="hljs-string">'the color to search for'</span>)

args = parser.parse_args()

print(args.color) <span class="hljs-comment"># 'red'</span>
</code></pre>
<p>If the argument is not specified, the program raises an error:</p>
<pre><code>➜  python python program.py
<span class="hljs-attr">usage</span>: program.py [-h] -c color
program.py: error: the following <span class="hljs-built_in">arguments</span> are required: -c
</code></pre><p>You can set an option to have a specific set of values, using <code>choices</code>:</p>
<pre><code class="lang-python">parser.add_argument(<span class="hljs-string">'-c'</span>, <span class="hljs-string">'--color'</span>, metavar=<span class="hljs-string">'color'</span>, required=<span class="hljs-literal">True</span>, choices={<span class="hljs-string">'red'</span>,<span class="hljs-string">'yellow'</span>}, help=<span class="hljs-string">'the color to search for'</span>)
</code></pre>
<pre><code>➜  python python program.py -c blue
<span class="hljs-attr">usage</span>: program.py [-h] -c color
program.py: error: argument -c/--color: invalid choice: <span class="hljs-string">'blue'</span> (choose <span class="hljs-keyword">from</span> <span class="hljs-string">'yellow'</span>, <span class="hljs-string">'red'</span>)
</code></pre><p>There are more options, but those are the basics.</p>
<p>And there are community packages that provide this functionality, too, like <a target="_blank" href="https://click.palletsprojects.com/en/7.x/">Click</a> and <a target="_blank" href="https://python-prompt-toolkit.readthedocs.io/en/master/index.html">Python Prompt Toolkit</a>.</p>
<h2 id="heading-lambda-functions-in-python">Lambda Functions in Python</h2>
<p>Lambda functions (also called anonymous functions) are tiny functions that have no name and only have one expression as their body.</p>
<p>In Python they are defined using the <code>lambda</code> keyword:</p>
<pre><code class="lang-python"><span class="hljs-keyword">lambda</span> &lt;arguments&gt; : &lt;expression&gt;
</code></pre>
<p>The body must be a single expression - an expression, not a statement.</p>
<blockquote>
<p>This difference is important. An expression returns a value, a statement does not.</p>
</blockquote>
<p>The simplest example of a lambda function is a function that doubles the value of a number:</p>
<pre><code class="lang-python"><span class="hljs-keyword">lambda</span> num : num * <span class="hljs-number">2</span>
</code></pre>
<p>Lambda functions can accept more arguments:</p>
<pre><code class="lang-python"><span class="hljs-keyword">lambda</span> a, b : a * b
</code></pre>
<p>Lambda functions cannot be invoked directly, but you can assign them to variables:</p>
<pre><code class="lang-python">multiply = <span class="hljs-keyword">lambda</span> a, b : a * b

print(multiply(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>)) <span class="hljs-comment"># 4</span>
</code></pre>
<p>The utility of lambda functions comes when combined with other Python functionality, for example in combination with <code>map()</code>, <code>filter()</code> and <code>reduce()</code>.</p>
<h2 id="heading-recursion-in-python">Recursion in Python</h2>
<p>A function in Python can call itself. That's what recursion is. And it can be pretty useful in many scenarios.</p>
<p>The common way to explain recursion is by using the factorial calculation.</p>
<p>The factorial of a number is the number <code>n</code> mutiplied by <code>n-1</code>, multiplied by <code>n-2</code>... and so on, until reaching the number <code>1</code>:</p>
<pre><code><span class="hljs-number">3</span>! = <span class="hljs-number">3</span> * <span class="hljs-number">2</span> * <span class="hljs-number">1</span> = <span class="hljs-number">6</span>
<span class="hljs-number">4</span>! = <span class="hljs-number">4</span> * <span class="hljs-number">3</span> * <span class="hljs-number">2</span> * <span class="hljs-number">1</span> = <span class="hljs-number">24</span>
<span class="hljs-number">5</span>! = <span class="hljs-number">5</span> * <span class="hljs-number">4</span> * <span class="hljs-number">3</span> * <span class="hljs-number">2</span> * <span class="hljs-number">1</span> = <span class="hljs-number">120</span>
</code></pre><p>Using recursion we can write a function that calculates the factorial of any number:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">factorial</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">if</span> n == <span class="hljs-number">1</span>: <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
    <span class="hljs-keyword">return</span> n * factorial(n<span class="hljs-number">-1</span>)

print(factorial(<span class="hljs-number">3</span>)) <span class="hljs-comment">#   6</span>
print(factorial(<span class="hljs-number">4</span>)) <span class="hljs-comment">#  24</span>
print(factorial(<span class="hljs-number">5</span>)) <span class="hljs-comment"># 120</span>
</code></pre>
<p>If inside the <code>factorial()</code> function you call <code>factorial(n)</code> instead of <code>factorial(n-1)</code>, you are going to cause an infinite recursion. Python by default will halt recursions at 1000 calls, and when this limit is reached, you will get a <code>RecursionError</code> error.</p>
<p>Recursion is helpful in many places, and it helps us simplify our code when there's no other optimal way to do it, so it's good to know this technique.</p>
<h2 id="heading-nested-functions-in-python">Nested Functions in Python</h2>
<p>Functions in Python can be nested inside other functions.</p>
<p>A function defined inside a function is visible only inside that function.</p>
<p>This is useful to create utilities that are useful to a function, but not useful outside of it.</p>
<p>You might ask: why should I be "hiding" this function, if it does no harm?</p>
<p>One, because it's always best to hide functionality that's local to a function, and is not useful elsewhere.</p>
<p>Also, because we can make use of closures (more on this later).</p>
<p>Here is an example:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">talk</span>(<span class="hljs-params">phrase</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">say</span>(<span class="hljs-params">word</span>):</span>
        print(word)

    words = phrase.split(<span class="hljs-string">' '</span>)
    <span class="hljs-keyword">for</span> word <span class="hljs-keyword">in</span> words:
        say(word)

talk(<span class="hljs-string">'I am going to buy the milk'</span>)
</code></pre>
<p>If you want to access a variable defined in the outer function from the inner function, you first need to declare it as <code>nonlocal</code>:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">count</span>():</span>
    count = <span class="hljs-number">0</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increment</span>():</span>
        <span class="hljs-keyword">nonlocal</span> count
        count = count + <span class="hljs-number">1</span>
        print(count)

    increment()

count()
</code></pre>
<p>This is useful especially with closures, as we'll see next.</p>
<h2 id="heading-closures-in-python">Closures in Python</h2>
<p>If you return a nested function from a function, that nested function has access to the variables defined in that function, even if that function is not active any more.</p>
<p>Here is a simple counter example.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">counter</span>():</span>
    count = <span class="hljs-number">0</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increment</span>():</span>
        <span class="hljs-keyword">nonlocal</span> count
        count = count + <span class="hljs-number">1</span>
        <span class="hljs-keyword">return</span> count

    <span class="hljs-keyword">return</span> increment

increment = counter()

print(increment()) <span class="hljs-comment"># 1</span>
print(increment()) <span class="hljs-comment"># 2</span>
print(increment()) <span class="hljs-comment"># 3</span>
</code></pre>
<p>We return the <code>increment()</code> inner function, and that still has access to the state of the <code>count</code> variable even though the <code>counter()</code> function has ended.</p>
<h2 id="heading-decorators-in-python">Decorators in Python</h2>
<p>Decorators are a way to change, enhance, or alter in any way how a function works.</p>
<p>Decorators are defined with the <code>@</code> symbol followed by the decorator name, just before the function definition.</p>
<p>Example:</p>
<pre><code class="lang-python"><span class="hljs-meta">@logtime</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>():</span>
    print(<span class="hljs-string">'hello!'</span>)
</code></pre>
<p>This <code>hello</code> function has the <code>logtime</code> decorator assigned.</p>
<p>Whenever we call <code>hello()</code>, the decorator is going to be called.</p>
<p>A decorator is a function that takes a function as a parameter, wraps the function in an inner function that performs the job it has to do, and returns that inner function. In other words:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">logtime</span>(<span class="hljs-params">func</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span>():</span>
        <span class="hljs-comment"># do something before</span>
        val = func()
        <span class="hljs-comment"># do something after</span>
        <span class="hljs-keyword">return</span> val
    <span class="hljs-keyword">return</span> wrapper
</code></pre>
<h2 id="heading-docstrings-in-python">Docstrings in Python</h2>
<p>Documentation is hugely important, not just to communicate to other people what the goal of a function/class/method/module is, but it also communicates it to yourself.</p>
<p>When you come back to your code 6 or 12 months from now, you might not remember all the knowledge you are holding in your head. At that point, reading your code and understanding what it is supposed to do will be much more difficult.</p>
<p>Comments are one way to help yourself (and others) out:</p>
<pre><code class="lang-python"><span class="hljs-comment"># this is a comment</span>

num = <span class="hljs-number">1</span> <span class="hljs-comment">#this is another comment</span>
</code></pre>
<p>Another way is to use <strong>docstrings</strong>.</p>
<p>The utility of docstrings is that they follow conventions. As such they can be processed automatically.</p>
<p>This is how you define a docstring for a function:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increment</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-string">"""Increment a number"""</span>
    <span class="hljs-keyword">return</span> n + <span class="hljs-number">1</span>
</code></pre>
<p>This is how you define a docstring for a class and a method:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>:</span>
    <span class="hljs-string">"""A class representing a dog"""</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name, age</span>):</span>
        <span class="hljs-string">"""Initialize a new dog"""</span>
        self.name = name
        self.age = age

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bark</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-string">"""Let the dog bark"""</span>
        print(<span class="hljs-string">'WOF!'</span>)
</code></pre>
<p>Document a module by placing a docstring at the top of the file, for example supposing this is <code>dog.py</code>:</p>
<pre><code class="lang-python"><span class="hljs-string">"""Dog module

This module does ... bla bla bla and provides the following classes:

- Dog
...
"""</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>:</span>
    <span class="hljs-string">"""A class representing a dog"""</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name, age</span>):</span>
        <span class="hljs-string">"""Initialize a new dog"""</span>
        self.name = name
        self.age = age

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bark</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-string">"""Let the dog bark"""</span>
        print(<span class="hljs-string">'WOF!'</span>)
</code></pre>
<p>Docstrings can span multiple lines:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increment</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-string">"""Increment
    a number
    """</span>
    <span class="hljs-keyword">return</span> n + <span class="hljs-number">1</span>
</code></pre>
<p>Python will process those and you can use the <code>help()</code> global function to get the documentation for a class/method/function/module.</p>
<p>For example calling <code>help(increment)</code> will give you this:</p>
<pre><code>Help on <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">increment</span> <span class="hljs-title">in</span> <span class="hljs-title">module</span>
<span class="hljs-title">__main__</span>:

<span class="hljs-title">increment</span>(<span class="hljs-params">n</span>)
    <span class="hljs-title">Increment</span>
    <span class="hljs-title">a</span> <span class="hljs-title">number</span></span>
</code></pre><p>There are many different standards to format docstrings, and you can choose to adhere to your favorite one.</p>
<p>I like Google's standard: https://github.com/google/styleguide/blob/gh-pages/pyguide.md#38-comments-and-docstrings</p>
<p>Standards allow to have tools to extract docstrings and automatically generate documentation for your code.</p>
<h2 id="heading-introspection-in-python">Introspection in Python</h2>
<p>Functions, variables, and objects can be analyzed using <strong>introspection</strong>.</p>
<p>First, using the <code>help()</code> global function we can get the documentation if provided in form of docstrings.</p>
<p>Then, you can use print() to get information about a function:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increment</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">return</span> n + <span class="hljs-number">1</span>

print(increment)

<span class="hljs-comment"># &lt;function increment at 0x7f420e2973a0&gt;</span>
</code></pre>
<p>or an object:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>():</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bark</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">'WOF!'</span>)

roger = Dog()

print(roger)

<span class="hljs-comment"># &lt;__main__.Dog object at 0x7f42099d3340&gt;</span>
</code></pre>
<p>The <code>type()</code> function gives us the type of an object:</p>
<pre><code class="lang-python">print(type(increment))
<span class="hljs-comment"># &lt;class 'function'&gt;</span>

print(type(roger))
<span class="hljs-comment"># &lt;class '__main__.Dog'&gt;</span>

print(type(<span class="hljs-number">1</span>))
<span class="hljs-comment"># &lt;class 'int'&gt;</span>

print(type(<span class="hljs-string">'test'</span>))
<span class="hljs-comment"># &lt;class 'str'&gt;</span>
</code></pre>
<p>The <code>dir()</code> global function lets us find out all the methods and attributes of an object:</p>
<pre><code class="lang-python">print(dir(roger))

<span class="hljs-comment"># ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bark']</span>
</code></pre>
<p>The <code>id()</code> global function shows us the location in memory of any object:</p>
<pre><code class="lang-python">print(id(roger)) <span class="hljs-comment"># 140227518093024</span>
print(id(<span class="hljs-number">1</span>))     <span class="hljs-comment"># 140227521172384</span>
</code></pre>
<p>It can be useful to check if two variables point to the same object.</p>
<p>The <code>inspect</code> standard library module gives us more tools to get information about objects, and you can check it out here: https://docs.python.org/3/library/inspect.html</p>
<h2 id="heading-annotations-in-python">Annotations in Python</h2>
<p>Python is dynamically typed. We do not have to specify the type of a variable or function parameter, or a function return value.</p>
<p>Annotations allow us to (optionally) do that.</p>
<p>This is a function without annotations:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increment</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">return</span> n + <span class="hljs-number">1</span>
</code></pre>
<p>This is the same function with annotations:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increment</span>(<span class="hljs-params">n: int</span>) -&gt; int:</span>
    <span class="hljs-keyword">return</span> n + <span class="hljs-number">1</span>
</code></pre>
<p>You can also annotate variables:</p>
<pre><code class="lang-python">count: int = <span class="hljs-number">0</span>
</code></pre>
<p>Python will ignore those annotations. A separate tool called <a target="_blank" href="http://mypy-lang.org/"><code>mypy</code></a> can be run standalone, or integrated by IDE like VS Code or PyCharm to automatically check for type errors statically, while you are coding. It will also help you catch type mismatch bugs before even running the code.</p>
<p>A great help especially when your software becomes large and you need to refactor your code.</p>
<h2 id="heading-exceptions-in-python">Exceptions in Python</h2>
<p>It's important to have a way to handle errors, and Python gives us exception handling to do so.</p>
<p>If you wrap lines of code into a <code>try:</code> block:</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    <span class="hljs-comment"># some lines of code</span>
</code></pre>
<p>If an error occurs, Python will alert you and you can determine which kind of error occurred using a <code>except</code> blocks:</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    <span class="hljs-comment"># some lines of code</span>
<span class="hljs-keyword">except</span> &lt;ERROR1&gt;:
    <span class="hljs-comment"># handler &lt;ERROR1&gt;</span>
<span class="hljs-keyword">except</span> &lt;ERROR2&gt;:
    <span class="hljs-comment"># handler &lt;ERROR2&gt;</span>
</code></pre>
<p>To catch all exceptions you can use <code>except</code> without any error type:</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    <span class="hljs-comment"># some lines of code</span>
<span class="hljs-keyword">except</span> &lt;ERROR1&gt;:
    <span class="hljs-comment"># handler &lt;ERROR1&gt;</span>
<span class="hljs-keyword">except</span>:
    <span class="hljs-comment"># catch all other exceptions</span>
</code></pre>
<p>The <code>else</code> block is run if no exceptions were found:</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    <span class="hljs-comment"># some lines of code</span>
<span class="hljs-keyword">except</span> &lt;ERROR1&gt;:
    <span class="hljs-comment"># handler &lt;ERROR1&gt;</span>
<span class="hljs-keyword">except</span> &lt;ERROR2&gt;:
    <span class="hljs-comment"># handler &lt;ERROR2&gt;</span>
<span class="hljs-keyword">else</span>:
    <span class="hljs-comment"># no exceptions were raised, the code ran successfully</span>
</code></pre>
<p>A <code>finally</code> block lets you perform some operation in any case, regardless of whether an error occurred or not:</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    <span class="hljs-comment"># some lines of code</span>
<span class="hljs-keyword">except</span> &lt;ERROR1&gt;:
    <span class="hljs-comment"># handler &lt;ERROR1&gt;</span>
<span class="hljs-keyword">except</span> &lt;ERROR2&gt;:
    <span class="hljs-comment"># handler &lt;ERROR2&gt;</span>
<span class="hljs-keyword">else</span>:
    <span class="hljs-comment"># no exceptions were raised, the code ran successfully</span>
<span class="hljs-keyword">finally</span>:
    <span class="hljs-comment"># do something in any case</span>
</code></pre>
<p>The specific error that's going to occur depends on the operation you're performing.</p>
<p>For example if you are reading a file, you might get an <code>EOFError</code>. If you divide a number by zero you will get a <code>ZeroDivisionError</code>. If you have a type conversion issue you might get a <code>TypeError</code>.</p>
<p>Try this code:</p>
<pre><code class="lang-python">result = <span class="hljs-number">2</span> / <span class="hljs-number">0</span>
print(result)
</code></pre>
<p>The program will terminate with an error:</p>
<pre><code>Traceback (most recent call last):
  File <span class="hljs-string">"main.py"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> &lt;<span class="hljs-built_in">module</span>&gt;
    result = <span class="hljs-number">2</span> / <span class="hljs-number">0</span>
<span class="hljs-attr">ZeroDivisionError</span>: division by zero
</code></pre><p>and the lines of code after the error will not be executed.</p>
<p>Adding that operation in a <code>try:</code> block lets us recover gracefully and move on with the program:</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    result = <span class="hljs-number">2</span> / <span class="hljs-number">0</span>
<span class="hljs-keyword">except</span> ZeroDivisionError:
    print(<span class="hljs-string">'Cannot divide by zero!'</span>)
<span class="hljs-keyword">finally</span>:
    result = <span class="hljs-number">1</span>

print(result) <span class="hljs-comment"># 1</span>
</code></pre>
<p>You can raise exceptions in your own code, too, using the <code>raise</code> statement:</p>
<pre><code class="lang-python"><span class="hljs-keyword">raise</span> Exception(<span class="hljs-string">'An error occurred!'</span>)
</code></pre>
<p>This raises a general exception, and you can intercept it using:</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    <span class="hljs-keyword">raise</span> Exception(<span class="hljs-string">'An error occurred!'</span>)
<span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> error:
    print(error)
</code></pre>
<p>You can also define your own exception class, extending from Exception:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DogNotFoundException</span>(<span class="hljs-params">Exception</span>):</span>
    <span class="hljs-keyword">pass</span>
</code></pre>
<blockquote>
<p><code>pass</code> here means "nothing" and we must use it when we define a class without methods, or a function without code, too.</p>
</blockquote>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    <span class="hljs-keyword">raise</span> DogNotFoundException()
<span class="hljs-keyword">except</span> DogNotFoundException:
    print(<span class="hljs-string">'Dog not found!'</span>)
</code></pre>
<h2 id="heading-the-with-statement-in-python">The <code>with</code> Statement in Python</h2>
<p>The <code>with</code> statement is very helpful to simplify working with exception handling.</p>
<p>For example when working with files, each time we open a file, we must remember to close it.</p>
<p><code>with</code> makes this process transparent.</p>
<p>Instead of writing:</p>
<pre><code class="lang-python">filename = <span class="hljs-string">'/Users/flavio/test.txt'</span>

<span class="hljs-keyword">try</span>:
    file = open(filename, <span class="hljs-string">'r'</span>)
    content = file.read()
    print(content)
<span class="hljs-keyword">finally</span>:
    file.close()
</code></pre>
<p>You can write:</p>
<pre><code class="lang-python">filename = <span class="hljs-string">'/Users/flavio/test.txt'</span>

<span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'r'</span>) <span class="hljs-keyword">as</span> file:
    content = file.read()
    print(content)
</code></pre>
<p>In other words we have built-in implicit exception handling, as <code>close()</code> will be called automatically for us.</p>
<p><code>with</code> is not just helpful to work with files. The above example is just meant to introduce its capabilities.</p>
<h2 id="heading-how-to-install-3rd-party-packages-in-python-using-pip">How to Install 3rd Party Packages in Python Using <code>pip</code></h2>
<p>The Python standard library contains a huge number of utilities that simplify our Python development needs, but nothing can satisfy <em>everything</em>.</p>
<p>That's why individuals and companies create packages, and make them available as open source software for the entire community.</p>
<p>Those modules are all collected in a single place, the <strong>Python Package Index</strong> available at https://pypi.org, and they can be installed on your system using <code>pip</code>.</p>
<p>There are more than 270,000 packages freely available at the time of writing.</p>
<blockquote>
<p>You should have <code>pip</code> already installed if you followed the Python installation instructions.</p>
</blockquote>
<p>Install any package using the command <code>pip install</code>:</p>
<pre><code>pip install &lt;package&gt;
</code></pre><p>or, if you do have troubles, you can also run it through <code>python -m</code>:</p>
<pre><code>python -m pip install &lt;package&gt;
</code></pre><p>For example you can install the <a target="_blank" href="https://pypi.org/project/requests/"><code>requests</code></a> package, a popular HTTP library:</p>
<pre><code>pip install requests
</code></pre><p>and once you do, it will be available for all your Python scripts, because packages are installed globally.</p>
<p>The exact location depends on your operating system.</p>
<p>On macOS, running Python 3.9, the location is <code>/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages</code>.</p>
<p>Upgrade a package to its latest version using:</p>
<pre><code>pip install –U &lt;package&gt;
</code></pre><p>Install a specific version of a package using:</p>
<pre><code>pip install &lt;package&gt;==<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span></span>
</code></pre><p>Uninstall a package using:</p>
<pre><code>pip uninstall &lt;package&gt;
</code></pre><p>Show an installed package details, including version, documentation website and author information using:</p>
<pre><code>pip show &lt;package&gt;
</code></pre><h2 id="heading-list-comprehensions-in-python">List Comprehensions in Python</h2>
<p>List comprehensions are a way to create lists in a very concise way.</p>
<p>Suppose you have a list:</p>
<pre><code class="lang-python">numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]
</code></pre>
<p>You can create a new list using a list comprehension, composed by the <code>numbers</code> list elements, power 2:</p>
<pre><code class="lang-python">numbers_power_2 = [n**<span class="hljs-number">2</span> <span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> numbers]
<span class="hljs-comment"># [1, 4, 9, 16, 25]</span>
</code></pre>
<p>List comprehensions are a syntax that's sometimes preferred over loops, as it's more readable when the operation can be written on a single line:</p>
<pre><code class="lang-python">numbers_power_2 = []
<span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> numbers:
    numbers_power_2.append(n**<span class="hljs-number">2</span>)
</code></pre>
<p>and over <code>map()</code>:</p>
<pre><code class="lang-python">numbers_power_2 = list(map(<span class="hljs-keyword">lambda</span> n : n**<span class="hljs-number">2</span>, numbers))
</code></pre>
<h2 id="heading-polymorphism-in-python">Polymorphism in Python</h2>
<p>Polymorphism generalizes a functionality so it can work on different types. It's an important concept in object-oriented programming.</p>
<p>We can define the same method on different classes:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">eat</span>():</span>
        print(<span class="hljs-string">'Eating dog food'</span>)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">eat</span>():</span>
        print(<span class="hljs-string">'Eating cat food'</span>)
</code></pre>
<p>Then we can generate objects and we can call the <code>eat()</code> method regardless of the class the object belongs to, and we'll get different results:</p>
<pre><code class="lang-python">animal1 = Dog()
animal2 = Cat()

animal1.eat()
animal2.eat()
</code></pre>
<p>We built a generalized interface and we now do not need to know that an animal is a Cat or a Dog.</p>
<h2 id="heading-operator-overloading-in-python">Operator Overloading in Python</h2>
<p>Operator overloading is an advanced technique we can use to make classes comparable and to make them work with Python operators.</p>
<p>Let's take a class Dog:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>:</span>
    <span class="hljs-comment"># the Dog class</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name, age</span>):</span>
        self.name = name
        self.age = age
</code></pre>
<p>Let's create 2 Dog objects:</p>
<pre><code class="lang-python">roger = Dog(<span class="hljs-string">'Roger'</span>, <span class="hljs-number">8</span>)
syd = Dog(<span class="hljs-string">'Syd'</span>, <span class="hljs-number">7</span>)
</code></pre>
<p>We can use operator overloading to add a way to compare those 2 objects, based on the <code>age</code> property:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>:</span>
    <span class="hljs-comment"># the Dog class</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name, age</span>):</span>
        self.name = name
        self.age = age
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__gt__</span>(<span class="hljs-params">self, other</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span> <span class="hljs-keyword">if</span> self.age &gt; other.age <span class="hljs-keyword">else</span> <span class="hljs-literal">False</span>
</code></pre>
<p>Now if you try running <code>print(roger &gt; syd)</code> you will get the result <code>True</code>.</p>
<p>In the same way we defined <code>__gt__()</code> (which means greater than), we can define the following methods:</p>
<ul>
<li><code>__eq__()</code> to check for equality</li>
<li><code>__lt__()</code> to check if an object should be considered lower than another with the <code>&lt;</code> operator</li>
<li><code>__le__()</code> for lower or equal (<code>&lt;=</code>)</li>
<li><code>__ge__()</code> for greater or equal (<code>&gt;=</code>)</li>
<li><code>__ne__()</code> for not equal (<code>!=</code>)</li>
</ul>
<p>Then you have methods to interoperate with arithmetic operations:</p>
<ul>
<li><code>__add__()</code> respond to the <code>+</code> operator</li>
<li><code>__sub__()</code> respond to the <code>–</code> operator</li>
<li><code>__mul__()</code> respond to the <code>*</code> operator</li>
<li><code>__truediv__()</code> respond to the <code>/</code> operator</li>
<li><code>__floordiv__()</code> respond to the <code>//</code> operator</li>
<li><code>__mod__()</code> respond to the <code>%</code> operator</li>
<li><code>__pow__()</code> respond to the <code>**</code> operator</li>
<li><code>__rshift__()</code> respond to the <code>&gt;&gt;</code> operator</li>
<li><code>__lshift__()</code> respond to the <code>&lt;&lt;</code> operator</li>
<li><code>__and__()</code> respond to the <code>&amp;</code> operator</li>
<li><code>__or__()</code> respond to the <code>|</code> operator</li>
<li><code>__xor__()</code> respond to the <code>^</code> operator</li>
</ul>
<p>There are a few more methods to work with other operators, but you get the idea.</p>
<h2 id="heading-virtual-environments-in-python">Virtual Environments in Python</h2>
<p>It's common to have multiple Python applications running on your system.</p>
<p>When applications require the same module, at some point you will reach a tricky situation where an app needs a version of a module, and another app a different version of that same module.</p>
<p>To solve this, you use <strong>virtual environments</strong>.</p>
<p>We'll use <code>venv</code>. Other tools work similarly, like <code>pipenv</code>.</p>
<p>Create a virtual environment using</p>
<pre><code class="lang-sh">python -m venv .venv
</code></pre>
<p>in the folder where you want to start the project, or where you already have an existing project.</p>
<p>Then run</p>
<pre><code class="lang-sh"><span class="hljs-built_in">source</span> .venv/bin/activate
</code></pre>
<blockquote>
<p>Use <code>source .venv/bin/activate.fish</code> on the Fish shell</p>
</blockquote>
<p>Executing the program will activate the Python virtual environment. Depending on your configuration you might also see your terminal prompt change.</p>
<p>Mine changed from</p>
<p><code>➜ folder</code></p>
<p>to</p>
<p><code>(.venv) ➜ folder</code></p>
<p>Now running <code>pip</code> will use this virtual environment instead of the global environment.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Thanks a lot for reading this book.</p>
<p>I hope it will inspire you to learn more about Python.</p>
<p>For more on Python and programming tutorials in general, check out my blog <a target="_blank" href="https://flaviocopes.com">flaviocopes.com</a>.</p>
<p>Send any feedback, errata, or opinions at <a target="_blank" href="mailto:flavio@flaviocopes.com">flavio@flaviocopes.com</a>, and you can reach me on Twitter <a target="_blank" href="https://twitter.com/flaviocopes">@flaviocopes</a>.</p>
<blockquote>
<p>Note: You can <a target="_blank" href="https://flaviocopes.com/page/python-handbook/">get a PDF, ePub and Mobi version of this Python Handbook</a></p>
</blockquote>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Hire Python Developers and Identify True Masters ]]>
                </title>
                <description>
                    <![CDATA[ By Shifa Martin “The joy of coding is in seeing a short, concise, readable, and small amount of clear code, not in trivial code that bores the reader,” said Guido van Rossum, a Dutch computer scientist and the inventor of Python.  Python developers u... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/extremely-valuable-points/</link>
                <guid isPermaLink="false">66d460f273634435aafcefc8</guid>
                
                    <category>
                        <![CDATA[ Hire app developers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ hire python developer ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ python developer ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python Developers ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 18 Sep 2019 12:11:02 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/09/hire-a-Python-Developer-in-2019.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Shifa Martin</p>
<p>“The joy of coding is in seeing a short, concise, readable, and small amount of clear code, not in trivial code that bores the reader,” said <strong>Guido van Rossum</strong><em>,</em> a Dutch computer scientist and the inventor of Python. </p>
<p>Python developers use modern web technologies to build basic as well as intricate software and app solutions. </p>
<h2 id="heading-demand-for-python-developers-is-growing-so-quickly">Demand For Python Developers is Growing So Quickly</h2>
<p>Python has overtaken almost every markets. And it has brought easy coding to the fingertips of developers who were once totally baffled by trivial programming languages. Yet still, demand for python developers seems to be increasing. For proving the same I have given here some key stats.        </p>
<blockquote>
<p><a target="_blank" href="https://www.economist.com/science-and-technology/2018/07/19/python-has-brought-computer-programming-to-a-vast-new-audience">Economist</a> research suggests that in America, Python-related searches are more frequent than for <strong>Kim Kardashian, a reality-TV star</strong>. </p>
<p><a target="_blank" href="https://insights.stackoverflow.com/survey/2019">Stack Overflow survey 2019</a> found that nearly 39.4% of developers prefer Python for coding, and the remaining want to use it. </p>
</blockquote>
<h2 id="heading-how-to-interview-python-developers">How to Interview Python Developers?</h2>
<p>The opportunities for hiring python developers in the markets of North America, Western, Europe, and Asia are on the rise. So companies are looking to hire python developers to scale their development teams. </p>
<blockquote>
<p>Python's top advantages are its ease of use, straightforward syntax, simplicity, and the use of indented spaces. </p>
</blockquote>
<p>These features make it easy to learn and share with other app developers. </p>
<p>Because of all this, I believe that hiring experienced Python developers is one of the most important tasks for any business. </p>
<p>Sometimes it can be frustrating too. So, I thought I would share here my experience for hiring Python developers.</p>
<h3 id="heading-find-someone-who-is-flexible-with-the-language-and-tools">Find Someone Who is Flexible with the Language and Tools</h3>
<p>If you are still asking the questions like how you concatenate two lists in Python, then you might need to overhaul your whole process of interviewing a Python developer. Don't forget about technical puzzles. Also, by giving a candidate a coding task in Python, you gain an opportunity to evaluate their coding standards and skills.</p>
<h3 id="heading-to-check-the-applicants-abilities-ask-questions">To check the applicant’s abilities, ask questions:</h3>
<blockquote>
<p>What are the risks that can occur with this code?</p>
<p>What is the way to overcome coding issues? </p>
<p>How would they cope with the problem as a Python developer?    </p>
<p>Ask the candidate to write a Python function in max of three numbers.  </p>
</blockquote>
<pre><code class="lang-py">Input data: z=<span class="hljs-number">1</span>, y=<span class="hljs-number">3</span>, x=<span class="hljs-number">5</span>
Expected output: x=<span class="hljs-number">5</span>
</code></pre>
<blockquote>
<p>Ask the candidate to write a program in Python that calculates and prints the value given in the formula.</p>
</blockquote>
<p><strong>Here's a sample question that you can ask to Python developers:</strong></p>
<p>Q = Square root of [(4 <em> A </em> B)/J]  </p>
<p>Following are the fixed values of A and J:</p>
<p>A is 50. J is 30.</p>
<p>B is the variable whose values should be input to your program in a comma-separated sequence.</p>
<p><strong>Example for Python Developers:</strong></p>
<p>Let us assume the following comma-separated input sequence is given to the program:</p>
<pre><code class="lang-py">Input: <span class="hljs-number">100</span>,<span class="hljs-number">150</span>,<span class="hljs-number">180</span>

Expected output: <span class="hljs-number">18</span>,<span class="hljs-number">22</span>,<span class="hljs-number">24</span>
</code></pre>
<p><strong>Hints:</strong></p>
<blockquote>
<p>If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 46.0, it should be printed as 46)</p>
<p>In case of input data being supplied to the question, it should be assumed to be a console input. </p>
<p>Make sure the candidate that is a Python developer complete this task within a dedicated time limit. Let's say 1 hour - 2 hour or so.</p>
</blockquote>
<p><strong>Here's the Final Output of Above Coding Samples:</strong></p>
<pre><code class="lang-py"><span class="hljs-comment">#!/usr/bin/env python</span>
<span class="hljs-keyword">import</span> math
a=<span class="hljs-number">50</span>
j=<span class="hljs-number">30</span>
value = []
items=[x <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> raw_input().split(<span class="hljs-string">','</span>)]
<span class="hljs-keyword">for</span> d <span class="hljs-keyword">in</span> items:
   value.append(str(int(round(math.sqrt(<span class="hljs-number">2</span>*c*float(d)/h)))))
   <span class="hljs-keyword">print</span> <span class="hljs-string">','</span>.join(value)
</code></pre>
<p><strong>Here's Another Sample Question for Python Developer:</strong></p>
<p>Write a program that accepts a comma in a separate sequence of words and prints the words in a comma-separated sequence after sorting.</p>
<pre><code class="lang-py">Input:
With, purse, blue, lady

Expected Output:
Blue, purse, <span class="hljs-keyword">with</span>, lady
</code></pre>
<p>It takes a lot to become a great Python developer. That's why I am sharing this information with you. I think it's worth adding to your list of interview questions.</p>
<blockquote>
<p><em>See what my next point is going to tell you about hiring process of Python developers.</em> </p>
</blockquote>
<h3 id="heading-give-them-real-life-python-coding-problems-that-youve-faced-before">Give them real-life Python coding problems that you’ve faced before</h3>
<p>As they say, if you hire a Python developer who is smarter than you are, then make the change quickly. It’s a simple law of attraction that talented people want to work in a fantastic place. So, we give them a task from a real-life technology problem. </p>
<p>Here’s what I have found works well.</p>
<h3 id="heading-real-life-python-project-example">Real-Life Python Project Example</h3>
<p>At my firm ValueCoders (<a target="_blank" href="https://www.valuecoders.com/">IT Outsourcing Company</a>) I have worked on the development of the <a target="_blank" href="https://www.valuecoders.com/case-studies/anomaly-detection-system#more-info">data anomaly detection software solution</a> built with Python and Machine Learning. </p>
<p>Our portfolio of Python projects includes a wide range of machine learning solutions, B2B portals, web applications, etc. </p>
<p>My full team of Python developers have worked day and night to build the data anomaly detection system. This system has been designed in way so it can identify the nature and trends of data for the businesses. </p>
<h3 id="heading-project-challenges">Project Challenges</h3>
<p>I've faced many challenges while working on this project. Although, I got a great help from my full team of Python developers, but I need to look up things closely to determine if the app can be perfectly balanced. </p>
<p>In my experience the challenge is to develop a mobile application that can help businesses deal with the issue of real-time data anomalies. The app needs to uncover important data insights that are important for digital businesses. It must have a system to reveal issues of the data insights. We have to fix the issue of constant and variable changes in data.</p>
<p><em>This only becomes possible with the effort of our team of Python developers.</em></p>
<p><em>See how they've found a solution.</em></p>
<h3 id="heading-how-weve-found-a-solution">How We've Found a Solution?</h3>
<p>Our team of Python developers had overcome all these challenges with the idea of developing an app through technologies: Python, PyCHARM, PYGTK, PYQT, WXPython and Machine learning. </p>
<p><strong>These are the steps we have applied to identify the anomalies in datasets with the concept of Python and machine learning.</strong></p>
<p><strong>Step 1</strong></p>
<p>Read the CSV file data-set from where anomalies have to be detected.</p>
<p><strong>Step 2</strong></p>
<p>Calculate the mean and co-variance matrix of the data samples.</p>
<p><strong>Step 3</strong></p>
<p>Find the <a target="_blank" href="https://en.wikipedia.org/wiki/Gaussian_function">Gaussian</a> distribution of the dataset. Done correctly by our Python developers.</p>
<p><strong>Step 4</strong></p>
<p>Next, calculation of the <a target="_blank" href="https://en.wikipedia.org/wiki/F1_score">f1_score</a> and minimum <a target="_blank" href="https://en.wikipedia.org/wiki/Machine_epsilon">epsilon</a> for each value of epsilon according to the step size.</p>
<p><strong>Step 5</strong></p>
<p>Compare the probabilities of the test data-set with the epsilon. The one which falls below the epsilon could be considered an anomaly.</p>
<blockquote>
<p><strong>As a result, our development team has developed an efficient data anomalies detection solution based on Python and machine learning.</strong></p>
</blockquote>
<p>So, the goal is to bring A-level Python developers to your firm. For that you should focus on how a candidate approaches the problem, craft a coding map, and solve the issue. </p>
<p>Look at the problem-solving techniques used by the candidate for a single language. </p>
<p>Also work on your interview process and encourage your recruitment team to do the same. </p>
<p>Writing legible code in Python is important. </p>
<p>Python developers with the knowledge of a variety of open-source libraries help reduce the time of software development and give you freedom from repetitive tasks and errors.  </p>
<h3 id="heading-dont-focus-on-experience-only-ask-about-their-coding-skills">Don’t Focus on Experience Only - Ask About their Coding Skills</h3>
<p>I’ve interviewed several Python developers who showed great experience in their resume but performed poorly in interview. No matter how good the resume is. If you need your new Python developer to work on something critical, more experience is generally required here which means more productivity. </p>
<p>Here I’d like to emphasize that your new hire needs to tackle new problems. More experience often leads to opinionated Python developers especially when you are trying to create something new with Python.</p>
<h2 id="heading-bringing-it-all-together">Bringing It All Together</h2>
<p>Eleventh-hour decisions are seldom satisfactory. What do you think? Is it true or not?  </p>
<p>It is also said that, <em>“Any fool can write the code that a computer can understand but good programmers write code that humans can understand.”</em> </p>
<p>This is the biggest thing I see most startups missing when hiring Python developers without a clear sense of how their experience and work will justify the cost of hiring them. </p>
<p>Yes, a Python developer needs to be well-trained, experienced, and above all produce well-written Python code. </p>
<p>Last but not the least, I encourage you to hire Python developers after a thorough analysis of their coding skills, communication, and performance in the in-person interview. Don’t just focus too much on applicant’s resume. I have seen people who are nice on-paper, but other areas also can’t be overlooked.</p>
<p><strong>Need to <a target="_blank" href="https://www.valuecoders.com/hire-developers/hire-python-developers">hire Python developers</a>? Feel free to <a target="_blank" href="https://www.valuecoders.com/contact">get in touch</a> with us.</strong> </p>
<p><strong>Or, follow us on Twitter for future updates: <a target="_blank" href="https://twitter.com/ValueCoders">https://twitter.com/ValueCoders</a></strong> </p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
