Python 101: The Ultimate Python Tutorial for Beginners
Published: 2022-04-24 11:40:42

Is this the first time you are thinking about coding and becoming a programmer? Here I will help you with the simple python basics to get you started. 

## Introduction to Python
Python was created in the late 1980's by Guido Van Rossum. It is maintained and supported by the Python Software Foundation. 
Python is a general-purpose programming language. It is used in various fields such as mathematics, agriculture, electronics, and mechanics.

- It is a **Strongly Typed** language- meaning that every object in Python has a definite type associated with it
- It is also **Dynamically Typed**- meaning that no type checking is done prior to running Python code.
- Python is an **Interpreted Language**. This means that code compilation and execution is done at the same time.

## Where can we use Python?
The Python language is used in many different fields.

- **Web Development** - Python is used to create really dynamic websites using frameworks like **Flask** and **Django**.
- **Scientific Computing** - It has several libraries dedicated to it for scientific computing like **numpy**, and **earthpy** for earth sciences.
- **Game Development** - Python has a gaming library called **pygame** for creating games that use keyboard and mouse interactions.
- **Desktop Applications** - Python comes with **tkinter** a graphical user interface library that allows us to create user interfaces for our applications.

Several companies use Python in their day-to-day running's. Here is a list of just a few:

- Google (YouTube)
- NASA
- IBM
- Mozilla
- Quora
- Instagram
- Reddit
- Disney

## Installation
- Go to the Python's [Downloads Page](https://www.python.org/downloads/) and download the latest version.

**NOTE**: _Always ensure that python has been correctly downloaded and is able to run on your PC. To check if it is properly installed on your machine._

**Windows**
On the Start menu or search bar find Python and click Enter then try running it or try using the following command line one the Terminal:
`C:\Users\user>python --version
`

**Mac OS/ Linux**
To verify if python was successfully installed, open your Terminal and run the command line.
`python3 --version`

This is what you see,

```
C:\Users\user>python --version
Python 3.9.7

```
## Python Basics
- **Strings** - In Python, we can create strings with either single quotes (') or double quotes (") and Python treats them as the same thing.

```
>>> 'This is a string'
This is a string
>>> "This is also a string"
This is also a string

```
There are also some string methods that allow us to perform actions on the string.

```
>>> 'This is a string'.upper()
THIS IS A STRING
>>> 'this is a string'.capitalize()
This is a string

>>> 'this is a string'.strip()
This is a string
```
The `upper()` method is used to transform strings to uppercase. 
The `capitalize()` method transforms the first letter of the string to a capital letter. 
The `strip()` method removes any trailing spaces in a string.

- **Numbers** - We can also do some mathematical computations in Python. 

```
>>> 3 + 2 # addition
5
>>> 31 - 10 # subtraction
21
>>> 3 * 4 # multiplication
12
>>> 12 / 3 # division
4.0
>>> 12 % 5 # modulus
2
>>> 2 ** 4 # Exponential
16
```
Here, we see a new character #. This hash or pound sign is Python's way to create comments. Anything after the # is ignored by the Python interpreter.
Notice that when we use the / operator, Python doesn't return a whole number, but a number with a decimal point. It is referred to as a float division. Decimal point numbers in Python are called floats.

```
>>> 30 / 5
6.0
>>> 45 / 9
5.0
>>> 25 // 5
5
```
Here we see some more examples using the / to get floats. We also see another division operator in Python: //. This divides the numbers, then rounds down the result and returns a whole number, and is called the integer division.

## Data Types
- `int`: whole numbered integers
- `float`: integers with decimal points.
- `None`: represents a null or non-existent value.
- `bool`: represent boolean statements and have only 2 possible values: `True` or `False`

## Collections
As the name suggests, collections store multiple values.

![Collections description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jdxyy4t8v73b6c16r8t4.jpg)

1. `str` - This data type is used to represent string values
2. `byte` - This data type is used to represent byte strings.
3. `list` - This is a collection used to group related data in an ordered way. [Learn More](https://www.pythontutorial.net/python-basics/python-list/)
4. `dict` - These allow us to create dictionaries which is data that is stored in key-value pairs.  [Learn more](https://www.pythontutorial.net/python-basics/python-dictionary/)


## Variables
Variables are named references to objects.
Here is an example of how we create a variable in Python in the Python shell:

```
>>> x = 4
>>> x
4
```
Python variables can store values from any data type. Python is dynamic in nature hence we do not have to specify what type of data we are storing.
```
>>> x = 12
>>> x
12
>>> x = "Hello"
>>> x
Hello
>>> pie = 3.1423
>>> pie
3.1423
```

## `input()` function
The `input()` function is called inside our Python application and prompts the user to pass in an input, which is stored as a string

**input_demo.py**
```
print("What is your name?")
name = input()

print("How old are you?")
age = int(input())

print(name)
print(age)
```
We run the file:
```
$ python3 input_demo.py
"What is your name?"
James
"How old are you?"
19

James
19
```

## Control Flow
Up to now our applications haven't been that interesting. Let us add some logic to our applications.

**`if` statements**
An `if` statement runs only when the condition passed to it evaluates to true

**input_demo.py**
```
height = 74 # The unit is inches
if height > 70 :
    print("You are really tall")
```
Run the file in the console:
```
$ python3.6 input_demo.py
You are really tall
```
Python uses **indents**. Indents are just four spaces we give to our application to define blocks of code. If we don't indent blocks of our code, we get an **IndentationError** and our program won't run.

**Comparison Operators**
Let us look at some of the comparison operators we will be using in Python

- `>` Greater than
- `<` Less than
- `==` Equal to
- `!=` not equal to
- `>=` Greater than or equal to
- `<=` Less than or Equal to
- `and` checks if both conditions evaluate to true
- `or` checks if at least one condition is true
- `not` returns the opposite of the condition given

`else`
The `else` statement comes right at the end of the `if` statement. It is run only when the `if` statement evaluates to `False`. Let's add an `else` statement to our example program:

**input_example.py**
```
height = 54 # inches
if height > 70 :
    print("You are really tall")
else:
    print("You are really short")
```
Now when we run the file, we get a different message:

```
$ python3.6 input_demo.py
You are really short
 
```

`elif`
What if we have more than one condition to check for? We can use `elif`, which will allow us to check for multiple conditions. Looking at our example:

```
height = 68 # inches
if height > 70 :
    print("You are really tall")
elif height > 60:
    print("You are of average height")

else:
    print("You are really short")
```
Now let's run it:

```
$ python3.6 input_demo.py
You are of average height
```
Since the height is greater than 60, the `elif` statement will be executed first and Python never reaches the `else` statement.

## Looping
A loop is a way to execute some piece of code over and over again. There are 2 kinds of loops in Python;

1. `for` loop
2. `while` loop

Learn more on [Loops](https://www.pythontutorial.net/python-basics/python-for-range/)

## Functions

We have already used functions to perform several tasks but let's learn how to create our own functions in python.

Functions are blocks of code that begin with the def keyword

```
def fun_a():
    print("I have been called")

fun_a()

"I have been called"
```
This example we have created a function with no arguments and in the function we have a print statement that outputs a string

Passing Arguments
In python you can also pass arguments to functions

```
def fun_a (a,b):
    print(a+b)

fun_a(1,4)
5

```
Learn more on [Functions](https://www.pythontutorial.net/python-basics/python-functions/)

**Exceptions and Error Handling**
There are some error that are caused by programmers themselves. These errors should not be handled but fixed.

1. `IndentationError` - when you fail to separate code blocks properly.
2. `NameError` - when you call an undefined variable function or method.
3. `TypeError` - when you try and perform operations on unrelated types.