Python Basics

the basics of Python programming

There are many tools and skills which can help you to become a better critical thinker, but one of the most important ones is learning how to program. Programming is the process of writing instructions for a computer to execute, and because computers are fundamentally logic machines, programming is a great way to develop your logical thinking skills. Learning a programming language like Python can help you to think more clearly, solve problems more effectively, and communicate more precisely.

Python is a high-level, dynamically typed multiparadigm programming language. Python code is often said to be almost like pseudocode, since it allows you to express very powerful ideas in very few lines of code while being very readable.

Why Python?

Python is a great language for beginners because it is easy to learn and use. Python has a simple and clean syntax that makes it easy to read and write, and it has a large standard library that provides a wide range of modules and packages to help you write your programs. Python is also a very versatile language that can be used for a wide range of applications, from web development to data analysis to artificial intelligence. Equally important, Python is fairly forgiving, which means that it is easy to write code that works, even if it is not perfect.

The other great thing is that Python for many years has been the most popular programming language in the world, favoured by professional software developers, engineers, scientists and data analysts, which means there are a lot of resources available to help you learn and use Python. There are many books, tutorials, and online courses that can help you get started, and there are many libraries and frameworks that can help you build your own projects.

Being popular also means that Python is a sought-after skill in the job market, and that the time you spend learning it will be well spent. Think of it as an investment in your future rather than yet another thing to learn.

What is a Python program?

Python programs execute code line by line, as a sequence of instructions for the computer to follow. Python is an interpreted language, which means that it is not compiled into machine code. Instead, Python code is translated into bytecode, which is then executed by the Python interpreter.

About Executable Files

When you execute a computer program, they are often stored in a file, in Windows this file is called a .exe file, in Linux or Mac it is called an executable file. You can’t read these files, they are in machine code. Python is an interpreted language, which means that the code is not compiled into machine code, but is translated into bytecode at runtime, which is then executed by the Python interpreter. This is why if you open a .py file with a text editor, you can read the original code.

Python programs are typically organized into files, which are stored in directories. A directory that contains Python files is called a package, and a directory that contains packages is called a library. Python comes with a large standard library that provides a wide range of modules and packages to help you write your programs.

Python files typically have the .py extension, which indicates that they are Python files. Python files can be executed from the command line by running the python command followed by the name of the file. For example, to run a file called hello.py, you would run a command like:

python hello.py

Here is the file structure of a typical Python program:

my_program/
    __init__.py
    main.py
    module1.py
    module2.py
    module3.py

In this example, my_program is the name of the package, and main.py is the main file that contains the code that will be executed when the program is run. The other files, module1.py, module2.py, and module3.py, are modules that contain code that can be imported and used by other modules, including main.py.

A very simple Python program

Here is a very simple Python program that sums two numbers assigned to variables a and b and prints the result.

Try it out

As you have installed Anaconda, you can use Jupyter Notebook to run Python code. To try out the code below, run the Anaconda Navigator and open Jupyter Notebook. Create a new notebook and paste the code below into a cell. Then run the cell by pressing Shift + Enter.

a = 1
b = 2
c = a + b
print(c)
3

The above program introduces the following concepts:

  • Variables: Variables are used to store data that can be used by the program. In this case, the variables a and b store the numbers 1 and 2, respectively.
  • Operators: Operators are used to perform operations on variables. In this case, the + operator is used to add the numbers stored in the variables a and b.
  • Functions: Functions are used to group code that performs a specific task. In this case, the inbuilt print function is used to print the result of adding the numbers stored in the variables a and b.

The above can be expressed in many different ways, for example:

a = 1
b = 2
print(a + b)
3

Or even just:

print(1 + 2)
3

Creating your own functions

We can also create our own functions. Following from the previous example, we can create a function that sums two numbers and returns the result.

def add(a, b):
    return a + b


print(add(1, 2))
3

In the above code, def is a keyword that is used to define a function. The function is given a name, add, and a list of parameters, a and b. The function body is indented, and contains the code that performs the addition of the two numbers. The return keyword is used to return the result of the addition.

The function can be called by passing two numbers as arguments, and the result can be then processed further. We could also assign the result to a variable and print it.

def add(a, b):
    return a + b


c = add(1, 2)
print(c)
3

Overloading

Python has several built-in data types that are used to store different types of data. And often operators and functions can handle different data types in different ways. For example, the + operator can be used to add numbers, concatenate strings, and merge lists, which means the add function we defined earlier can be used with different things. This kind of behavior is called operator overloading.

Here’s an example of this:

def add(a, b):
    return a + b


c = add("a", "b")
print(c)
ab

In the above example the same add function is used to concatenate strings, rather than adding numbers. This is possible because the + operator can take different data inputs and act accordingly. Let us do the same with Python lists:

def add(a, b):
    return a + b


a = [1, 2]
b = [3, 4]
c = add(a, b)
print(c)
[1, 2, 3, 4]

Errors

In this example we introduced a different data type, the list, and the + operator is used to merge the two lists. This is another example of operator overloading. We will talk about different data types in the next section, but for now, it is important to understand that Python is a very flexible language that allows you to write code that can handle different data types in different ways. There are however some limitations, for example, the + operator cannot be used to add a number and a string, or a list and a number, or a list and a string. Here’s how this would fail:

def add(a, b):
    return a + b


a = 1
b = "2"
c = add(a, b)
print(c)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[8], line 6
      4 a = 1
      5 b = "2"
----> 6 c = add(a, b)
      7 print(c)

Cell In[8], line 2, in add(a, b)
      1 def add(a, b):
----> 2     return a + b

TypeError: unsupported operand type(s) for +: 'int' and 'str'

The above output is the Python interpreter telling you that you can’t add a number and a string. This is because the + operator is not defined for these data types. This is an example of type error.

Code comments

Comments are used to explain and document the code and make it easier to understand. In Python, comments start with the # character and continue until the end of the line. Comments are ignored by the Python interpreter, so they do not affect the execution of the program. Think of it as a note to yourself or others who might read your code. You can also write multi-line comments using triple quotes ''' or """.

Here’s an example of a comment:

# This method adds two numbers, strings or lists
def add(a, b):
    """
    This method adds two numbers, strings or lists
    :param a: number, string or list
    :param b: number, string or list
    """
    return a + b

Indentation

Python uses indentation to define the structure of the code. Blocks of code that are at the same level of indentation are considered to be part of the same block. Blocks of code that are indented more are considered to be part of a nested block. Indentation is used to define the structure of the code, and it is important to use consistent indentation to make the code easier to read and understand.

Here’s an example of indentation:

def add(a, b):
    """
    Everything at this level of indentation is considered part of the function
    """
    c = a + b
    return c


# This is at the same level of indentation as the function, and therefore not part of the function
print(add(1, 2))
3

Indentation can also be used when calling functions, which makes the code easier to read and understand in cases where the function takes multiple arguments, for example:

print(add(1, 2))
3

Exercises

  1. Write a Python program that calculates the area of a rectangle with a length of 10 and a width of 5. Print the result.
  2. Write a Python program that calculates the area of a circle with a given radius. Print the result.

Reuse

This work is licensed under CC BY (View License)