# Install the necessary dependencies

import sys
import os
!{sys.executable} -m pip install --quiet jupyterlab_myst ipython
LICENSE

MIT License

Copyright © 2018 Oleksii Trekhleb Copyright © 2018 Real Python

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

1. Python programming introduction#

Python is a high-level programming language for general-purpose programming. It is an open-source, interpreted, objected-oriented programming language. Python was created by a Dutch programmer, Guido van Rossum. The name of the Python programming language was derived from a British sketch comedy series, Month Python’s Flying Circus. The first version was released on February 20, 1991.

Python is an easy-to-learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

It is used for:

  • web development (server-side),

  • software development,

  • mathematics,

  • system scripting.

These Python programming-related sections are designed for beginners and professionals who want to learn Python programming language. If you are in favor of videos, you may get started with this Python for Absolute Beginners video.

1.1. Why Python?#

It is a programming language that is very close to human language and because of that, it is easy to learn and use. Python is used by various industries and companies (including Google). It has been used to develop web applications, desktop applications, system administration, and Machine Learning libraries. Python is a highly embraced language in the data science and Machine Learning community. Hope this is enough to convince you to start learning Python. Python is eating the world and you are killing it before it eats you.

1.2. Environment setup#

1.2.1. Installing Python#

To run a Python script you need to install Python. Let’s download Python.

If you are a windows user. Click the button encircled in red.

installing on Windows

If you are a macOS user. Click the button encircled in red.

installing on Mac

To check if Python is installed, write the following command on your device terminal.

python –version

Python Version

As you can see from the terminal, Python 3.7.5 version is used at the moment. Your version of Python might be different from mine, but it should be 3.6 or above. If you manage to see the Python version, well done. Python has been installed on your machine. Continue to the next section.

1.2.2. Python shell#

Python is an interpreted scripting language, so it does not need to be compiled. It means it executes the code line by line. Python comes with a Python Shell (Python Interactive Shell). It is used to execute a single Python command and get the result.

Python Shell waits for the Python code from the user. When you enter the code, it interprets the code and shows the result in the next line. Open your terminal or command prompt(cmd) and write:

python

Python Scripting Shell

The Python interactive shell is opened and it is waiting for you to write Python code(Python script). You will write your Python script next to this symbol >>> and then click Enter. Let us write our very first script on the Python scripting shell.

Python script on Python shell

Well done, you wrote your first Python script on Python interactive shell. How do we close the Python interactive shell?

To close the shell, next to this symbol >> write exit() command and press Enter.

Exit from the Python shell

Now, you know how to open the Python interactive shell and how to exit from it.

Python will give you results if you write scripts that Python understands, if not it returns errors. Let’s make a deliberate mistake and see what Python will return.

Invalid Syntax Error

As you can see from the returned error, Python is so clever that it knows the mistake we made and which was Syntax Error: invalid syntax. Using x as multiplication in Python is a syntax error because x is not the valid syntax in Python. Instead of x, we use an asterisk * for multiplication. The returned error clearly shows what to fix.

The process of identifying and removing errors from a program is called debugging. Let us debug it by putting * in place of x.

Fixing Syntax Error

Our bug was fixed, the code ran and we got the result we were expecting. As a programmer, you will see such kinds of errors on daily basis. It is good to know how to debug. To be good at debugging you should understand what kind of errors you are facing. Some of the Python errors you may encounter are SyntaxError, IndexError, NameError, ModuleNotFoundError, KeyError, ImportError, AttributeError, TypeError, ValueError, ZeroDivisionError etc. We will see more about different Python error types in later sections.

Let us practice more on how to use Python interactive shell. Go to your terminal or command prompt and write the word Python.

Python Scripting Shell

The Python interactive shell is opened. Let us do some basic mathematical operations (addition, subtraction, multiplication, division, modulus, exponential).

Let us do some maths first before we write any Python code:

\[ 3 + 2 = 5\]
\[ 3 - 2 = 1 \]
\[ 3 * 2 = 6 \]
\[ 3 / 2 = 1.5 \]
\[ 3 ^ 2 = 3 x 3 = 9 \]

In Python we have the following additional operations:

  • 3 % 2 = 1 => which means finding the remainder

  • 3 // 2 = 1 => which means removing the remainder

Let us change the above mathematical expressions to Python code. The Python shell has been opened and lets us write a comment at the very beginning of the shell.

A comment is a part of the code that is not executed by Python. So we can leave some text in our code to make our code more readable. Python does not run the comment part. Comment in Python starts with the hash(#) symbol.

This is how you write a comment in Python

# comment starts with hash
# this is a Python comment, because it starts with a (#) symbol

Maths on Python shell

Before we move on to the next section, let us practice more on the Python interactive shell. Close the opened shell by writing exit() on the shell and open it again and let us practice how to write text on the Python shell.

Writing String on Python shell

1.2.3. Installing Visual Studio Code#

The Python interactive shell is good to try and test small script codes but it will not be for a big project. In the real work environment, developers use different code editors to write code. Will use Visual Studio Code. Visual Studio Code is a very popular open-source text editor. If you are a fan of Visual Studio Code, it is recommended to download it. but if you are in favor of other editors, feel free to follow with what you have.

Visual Studio Code

If you installed Visual Studio Code, let us see how to use it. If you prefer a video, you can follow this Visual Studio Code for Python Video tutorial

1.2.3.1. How to use Visual Studio Code#

Open the Visual Studio Code by double-clicking the visual studio icon. When you open it you will get this kind of interface. Try to interact with the labeled icons.

Visual Studio Code

Create a folder named ocademy on your desktop. Then open it using Visual Studio Code.

Opening Project on Visual studio

Opening a project

After opening it you will see shortcuts for creating files and folders inside of ocademy project’s directory. As you can see below, the very first file is created as helloworld.py. You can do the same.

Creating a Python file

After a long day of coding, you want to close your code editor, right? This is how you will close the opened project.

Closing project

Congratulations, you have finished setting up the development environment. Let us start coding.

1.3. Basic Python#

1.3.1. Python syntax#

A Python script can be written in Python interactive shell or the code editor. A Python file has an extension .py.

1.3.2. Python indentation#

An indentation is a white space in a text. Indentation in many languages is used to increase code readability, however, Python uses indentation to create blocks of codes. In other programming languages, curly brackets are used to create blocks of codes instead of an indentation. One of the common bugs when writing Python code is the wrong indentation.

Indentation Error

1.3.3. Comments#

Comments are very important to make the code more readable and to leave remarks in our code. Python does not run comment parts of our code. Any text starting with a hash(#) in Python is a comment.

Example: Single Line Comment

# This is the first comment
# This is the second comment
# Python is eating the world

Example: Multiline Comment

The triple quote can be used for multiline comments if it is not assigned to a variable

"""This is multiline comment
multiline comment takes multiple lines.
Python is eating the world
"""
'This is multiline comment\nmultiline comment takes multiple lines.\nPython is eating the world\n'

1.3.4. Data types#

In Python, there are several types of data types. Let us get started with the most common ones. Different data types will be covered in detail in other sections. For the time being, let us just go through the different data types and get familiar with them. You do not have to have a clear understanding now.

1.3.4.1. Number#

  • Integer: integer(negative, zero and positive) numbers. Example: … -3, -2, -1, 0, 1, 2, 3 …

  • Float: decimal number. Example: … -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 …

  • Complex. Example: 1 + j, 2 + 4j

age = 26  # That's Interge
pi = 3.14159  # That's Float
# Complex. Example: 1 + j, 2 + 4j
print(type(age))
print(type(pi))
<class 'int'>
<class 'float'>

1.3.4.2. String#

A collection of one or more characters under a single or double quote. If a string is more than one sentence then we use a triple quote.

s = 'Rutherford Birchard Hayes'
tokens = s.split()
firstName = tokens[0]
middleName = tokens[1]
lastName = tokens[2]
s2 = firstName + ' ' + middleName + ' ' + lastName
# All objects except tokens are of type string
print(type(s))
print(type(s2))
<class 'str'>
<class 'str'>

1.3.4.3. Booleans#

A boolean data type is either a True or False value. T and F should be always uppercase.

def boolean(s, s2):
    print(type(s == s2))
    if (s == s2):
        print('yes!!!')
    else:
        print('nooooooo')

boolean(1, 2)
boolean(1, '1')
boolean(1, 1)
<class 'bool'>
nooooooo
<class 'bool'>
nooooooo
<class 'bool'>
yes!!!

1.3.4.4. List#

Python list is an ordered collection that allows to store items of different data types. A list is similar to an array in JavaScript.

Let's visualize it! 🎥

1.3.4.5. Dictionary#

A Python dictionary object is an unordered collection of data in a key-value pair format.

Let's visualize it! 🎥

1.3.4.6. Tuple#

A tuple is an ordered collection of different data types like a list, but tuples can not be modified once they are created. They are immutable.

ages = (18, 21, 28, 21, 22, 18, 19, 34, 9)
print(ages)
print(type(ages))
# If you want to change ages, you will get a error.
(18, 21, 28, 21, 22, 18, 19, 34, 9)
<class 'tuple'>

1.3.4.7. Set#

A set is a collection of data types similar to a list and tuple. Unlike the list and the tuple, a set is not an ordered collection of items. Like in Mathematics, set in Python only stores unique items. In later sections, we will go into detail about every Python data type.

Let's visualize it! 🎥

1.3.5. Control flow and function#

1.3.5.1. if#

The if statement is used for conditional execution. It allows you to execute different code blocks based on the truth or falsehood of a condition.

if condition:
  # Code block to be executed if the condition is true
else:
  # Code block to be executed if the condition is false

In this structure, the condition is an expression or variable that evaluates to either True or False. If the condition is true, the code block under if is executed. If the condition is false, the code block under else is executed. You can click here to see sample code in boolean.

1.3.5.2. for#

The for loop is used for iterating over a sequence of elements. It allows you to execute a block of code for each item in the sequence.

for item in sequence:
  # Code block to be executed for each item

In this structure, item is a variable that represents each element in the sequence, and sequence is the iterable object you want to loop through. The code block under the for loop is executed for each item in the sequence. You can click here to see sample code in list.

1.3.5.3. def#

The def keyword is used to define a function. Functions are blocks of reusable code that perform a specific task when called.

def function_name(parameters_input):
    # Code block or statements
    # that define the function's behavior
    return parameters_output

Here’s a breakdown of the different components:

  • def: This keyword is used to indicate the start of a function definition.

  • function_name: This is the name you choose for your function. It should be descriptive and follow Python naming conventions.

  • parameters_input: These are optional input values that you can pass to the function. They are placeholders for the actual values that will be provided when calling the function.

  • Code block: This is where you write the instructions or statements that define the behavior of the function. It should be indented under the function definition.

  • return: Usually return is found in def, and its purpose is to return parameters_output that follows. But if you have other outputs, you don’t have to write ‘return’. You can click here to see sample code in boolean.

  • parameters_output: These are the parameters you wish to pass out.

1.3.6. Python file#

First open your project folder, oocademy. If you don’t have this folder, create a folder name called ocademy. Inside this folder, create a file called helloworld.py. Now, let’s do what we did on Python interactive shell using Visual Studio Code.

The Python interactive shell was printing without using print but on Visual Studio Code to see our result we should use a built-in function print(). The print() built-in function takes one or more arguments as follows print('arument1', 'argument2', 'argument3'). See the examples below.

Let's visualize it! 🎥

The file name is helloworld.py.

To run the Python file check the image below. You can run the Python file either by running the green button on Visual Studio Code or by typing python helloworld.py in the terminal.

Running Python script

🌕 You are amazing. You have just completed our challenge and you are on your way to greatness. Now do some exercises for your brain and muscles.

1.4. Your turn! 🚀#

Try to write some simple Python code through Python shell, Python file, and Jupyter Notebook.

1.5. Acknowledgments#

Thanks to Asabeneh who helped create this awesome open-source project 30-Days-Of-Python for Python learning. It contributes the majority of the content in this chapter.

Thanks to pythontutor for providing the ability to visualize the code execution. It also contributes some code to this chapter.