DEV Community

Cover image for Python 101 : The Ultimate Python Tutorial For Beginners By Ambrose
Ambrose Otundo
Ambrose Otundo

Posted on

Python 101 : The Ultimate Python Tutorial For Beginners By Ambrose

What actually is Python Programming language? I know you've heard of it and had that notion that it is linked to a land reptile. Python is a an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.

The basic question that most beginners have in mind is what a language can do. Here are some of the use-cases of Python:

Server-side development ( Django, Flask )
Data Science ( Pytorch, Tensor-flow )
Data analysis / Visualisation ( Matplotlib )
Scripting ( Beautiful Soup )
Embedded development


Lets dive in on how to first install python in your computer.

Installing Python on Windows

  • Go to Python's official website.

  • Click on the download button ( Download Python 3.10 )

    _Note: The version may differ based on when you are reading this article _

  • Go to the path where the package is downloaded and double-click the installer.

  • Check the box indicating to "Add Python 3.x to PATH" and then click on "Install Now".

  • Once done you'll get a prompt that "Setup was successful". Check again if python is configured properly using the above command.

  • To confirm if Python is installed and configured properly, use the command python.

python
Enter fullscreen mode Exit fullscreen mode

Installing on MacoS

First install xcode from the app store.
If you want to install Xcode using the terminal then use the following command:
xcode-select --install
After that, we will use the brew package manager to install Python. To install and configure brew, use the following command:
/bin/bash -c "$(curl -fsSLhttps://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
Once brew setup is done, use the following command to update any outdated packages:
brew update
Use the following command to install Python:
brew install python3
To confirm if Python is installed and configured properly, use the command
python

Installing on Linux
install Python using apt, use the following command:
sudo apt install python3
To install the Python using yum, use the following command:
sudo yum install python3
To confirm if Python is installed and configured properly, use the command
python3 --version.

Python Shell

The Python Shell is the interpreter that executes your Python programs, other pieces of Python code, or simple commands.

Image description
For Example:
We can do a simple math calculation in the shell.
Image description

Commenting:

Comments make it easy to write code as they help us (and others) understand why a particular piece of code was written. Another awesome thing about comments is that they help improve the readability of the code.
Image description

Indentation:
It is compulsory in Python to follow the rules of indentation. If proper indentation is not followed you'll get the following error:

Image description

Variables:
As the name implies, a variable is something that can change. A variable is a way of referring to a memory location used by a computer program.

Well in most programming languages you need to assign the type to a variable. But in Python, you don’t need to. For example, to declare an integer in C, the following syntax is used:

int num = 5;. In Python it's num = 5 .
Enter fullscreen mode Exit fullscreen mode

Go to the Python shell and perform the operation step by step:

Integer: Numerical values that can be positive, negative, or zero without a decimal point.

>>> num = 5
>>> print(num)
5
>>> type(num)
<class 'int'>
Enter fullscreen mode Exit fullscreen mode

As you can see here we have declared a num variable and assigned 5as a value. Python's inbuilt type method can be used to check the type of variable. When we check the type of num we see the output <class 'int'>. For now, just focus on the int in that output. int represents an integer.

Float: Similar an integer but with one slight difference – floats are a numerical value with a decimal place.

>>> num = 5.0
>>> print(num)
5.0
>>> type(num)
<class 'float'>
Enter fullscreen mode Exit fullscreen mode

Here we have assigned a number with a single decimal to the num. When we check the type of num we can see it is float.

String: A formation of characters or integers. They can be represented using double or single quotes.

>>> greet = "Hello user"
>>> print(greet)
Hello user
>>> type(greet)
<class 'str'>
Enter fullscreen mode Exit fullscreen mode

Here we have assigned a string to greet. The type of greet is a string as you can see from the output.

Boolean: A binary operator with a True or False value.

>>> is_available = True
>>> print(is_available)
True
>>> type(is_available)
<class 'bool'>
Enter fullscreen mode Exit fullscreen mode

Here we have assigned a True value to is_available. The type of this variable is boolean. You can only assign True or False. Remember T and F should be capital or it will give an error as follows:

>>> is_available = true
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined
Enter fullscreen mode Exit fullscreen mode

NoneType: This is used when we don't have the value of the variable.

>>> num = None
>>> print(num)
None
>>> type(num)
<class 'NoneType'>
Enter fullscreen mode Exit fullscreen mode

Operators:
These are Arithmetic operators available in Python.
Image description
Lets look at their functionality.

Arithmetic operators
These include addition, subtraction, deletion, exponentiation, modulus, and floor division. Also the shorthand syntax for some operators.

First, we will declare two variables, a and b.

>>> a = 6 # Assignment
>>> b = 2
Enter fullscreen mode Exit fullscreen mode

Let's try our basic arithmetic operations:

>>> a + b # Addition
8
>>> a - b # Subtraction
4
>>> a * b # Multiplication
12
>>> a / b # Division
3.0
>>> a ** b # Exponentiation
36
Enter fullscreen mode Exit fullscreen mode

To test for other arithmetic operations let's change the value of a and b.

>>> a = 7
>>> b = 3
>>> a % b # Modulus
1
>>> a // b # Floor division
2
Enter fullscreen mode Exit fullscreen mode

Comparison operators
These include equal to, greater than, and less than.

>>> a = 5 # Assign
>>> b = 2 # Assign
>>> a > b # Greater than
True
>>> a < b # less then
False
>>> a == b # Equal to
False
>>> a >= 5 # Greater than or equal to
True
>>> b <= 1 # Less than or equal to
False
Enter fullscreen mode Exit fullscreen mode

Logical operators
These operators include not, and, & or.

>>> a = 10
>>> b = 2
>>> a == 2 and b == 10 # and
False
>>> a == 10 or b == 10 # or
True
>>> not(a == 10) # not
False
>>> not(a == 2)
True
Enter fullscreen mode Exit fullscreen mode

Conditional Statements:
Conditional statements are used to evaluate if a condition is true or false.

Many times when you are developing an application you need to check a certain condition and do different things depending on the outcome. In such scenarios conditional statements are useful. If, elif and else are the conditional statements used in Python.

We can compare variables, check if the variable has any value or if it's a boolean, then check if it's true or false. Go to the Python shell and perform the operation step by step:

Condition Number 1: We have an integer and 3 conditions here. The first one is the if condition. It checks if the number is equal to 10.

The second one is the elif condition. Here we are checking if the number is less than 10.

The last condition is else. This condition executes when none of the above conditions match.

>>> number = 5
>>> if number == 10:
...     print("Number is 10")
... elif number < 10:
...     print("Number is less than 10")
... else:
...     print("Number is more than 10")
...
Enter fullscreen mode Exit fullscreen mode

Output:

Number is less than 10
Enter fullscreen mode Exit fullscreen mode

Note: It is not compulsory to check that two conditions are equal in the if condition. You can do it in the elif also.

Condition Number 2: We have a boolean and 2 conditions here. Have you noticed how we are checking if the condition is true? If is_available, then print "Yes it is available", else print "Not available".

>>> is_available = True
>>> if is_available:
...     print("Yes it is available")
... else:
...     print("Not available")
...
Enter fullscreen mode Exit fullscreen mode

Output:

Yes it is available
Enter fullscreen mode Exit fullscreen mode

Condition Number 3: Here we have reversed condition number 2 with the help of the not operator.

>> is_available = True
>>> if not is_available:
...     print("Not available")
... else:
...     print("Yes it is available")
...
Enter fullscreen mode Exit fullscreen mode

Output:

Yes it is available
Enter fullscreen mode Exit fullscreen mode

Condition Number 4: Here we are declaring the data as None and checking if the data is available or not.

>>> data = None
>>> if data:
...     print("data is not none")
... else:
...     print("data is none")
...
Enter fullscreen mode Exit fullscreen mode

Output:

data is none
Enter fullscreen mode Exit fullscreen mode

**
For Loops:**
Another useful method in any programming language is an iterator. If you have to implement something multiple times, what will you do?

print("Hello")
print("Hello")
print("Hello")
Enter fullscreen mode Exit fullscreen mode

Well, that's one way to do it. But imagine you have to do it a hundred or a thousand times. Well, that's a lot of print statements we have to write. There's a better way called iterators or loops. We can either use a for or while loop.

Here we are using the range method. It specifies the range until which the loop should be repeated. By default, the starting point is 0.

>>> for i in range(3):
...     print("Hello")
...
Enter fullscreen mode Exit fullscreen mode

Output:

Hello
Hello
Hello
Enter fullscreen mode Exit fullscreen mode

You can also specify the range in this way range(1,3).

>>> for i in range(1,3):
...     print("Hello")
...
Enter fullscreen mode Exit fullscreen mode

Output:

Hello
Hello
"Hello" is only printed two times as we have specified the range here. Think of the range as Number on right - Number on left.

Well, you can also add an else statement in the for loop.

>>> for i in range(3):
...     print("Hello")
... else:
...     print("Finished")
Enter fullscreen mode Exit fullscreen mode

Output:

Hello
Hello
Hello
Finished
Enter fullscreen mode Exit fullscreen mode

We can also nest a for loop inside another for loop.

>>> for i in range(3):
...     for j in range(2):
...             print("Inner loop")
...     print("Outer loop")
...
Enter fullscreen mode Exit fullscreen mode

Output:

Inner loop
Inner loop
Outer loop
Inner loop
Inner loop
Outer loop
Inner loop
Inner loop
Outer loop
Enter fullscreen mode Exit fullscreen mode

As you can see the inner loop print statement executed two times. After that outer loop print statement executed. Again the inner loop executed two times. So what is happening here? If you are confused then consider this to solve it:

Our Interpreter comes and sees that there is a for loop. It goes down again and checks there is another for loop.
So now it will execute the inner for loop two times and exit. Once it's finished it knows that outer for loop has instructed it to repeat two more times.
It starts again and sees the inner for loop and repeats.
Well, you can also choose to pass a certain for loop condition. What does pass mean here? Well whenever that for loop will occur and the Interpreter sees the pass statement it won't execute it and will move to the next line.

>>> for i in range(3):
...     pass
...
Enter fullscreen mode Exit fullscreen mode

You will not get any output on the shell.

While loops:
Another loop or iterator available in Python is the while loop. We can achieve some of the same results with the help of a while loop as we achieved with the for loop.

>>> i = 0
>>> while i < 5:
...     print("Number", i)
...     i += 1
...
Enter fullscreen mode Exit fullscreen mode

Output:

Number 0
Number 1
Number 2
Number 3
Number 4
Enter fullscreen mode Exit fullscreen mode

Remember whenever you use a while loop it's important that you add an increment statement or a statement that will end the while loop at some point. If not then the while loop will execute forever.

Another option is to add a break statement in a while loop. This will break the loop.

>>> i = 0
>>> while i < 5:
...     if i == 4:
...             break
...     print("Number", i)
...     i += 1
...
Enter fullscreen mode Exit fullscreen mode

Output:

Number 0
Number 1    
Number 2
Number 3
Enter fullscreen mode Exit fullscreen mode

Here we are breaking the while loop if we find the value of i to be 4.

Another option is to add an else statement in while loop. The statement will be executed after the while loop is completed.

>>> i = 0
>>> while i < 5:
...     print("Number", i)
...     i += 1
... else:
...     print("Number is greater than 4")
...
Enter fullscreen mode Exit fullscreen mode

Output:

Number 0
Number 1
Number 2
Number 3
Number 4
Number is greater than 4
Enter fullscreen mode Exit fullscreen mode

User Input:
Imagine you are building a command-line application. Now you have to take the user input and act accordingly. To do that you can use Python's inbuilt input method.

The syntax to achieve this is as follows:

variable = input(".....")
Example:

>>> name = input("Enter your name: ")
Enter your name: Ambrose
Enter fullscreen mode Exit fullscreen mode

When you use the input method and press enter, you'll be prompted with the text that you enter in the input method. Let's check if our assignment is working or not:

>>> print(name)
Ambrose
Enter fullscreen mode Exit fullscreen mode

This tutorial will give a first hand experience on starting to code with Python. I hope you guys have a blast coding.
Happy coding :)

Top comments (0)