DEV Community

Cover image for Python 101: The Ultimate Python Tutorial for Beginners
It's pronounced W3SHY
It's pronounced W3SHY

Posted on

Python 101: The Ultimate Python Tutorial for Beginners

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

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

  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
  4. dict - These allow us to create dictionaries which is data that is stored in key-value pairs. Learn more

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

We run the file:

$ python3 input_demo.py
"What is your name?"
James
"How old are you?"
19

James
19
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

Run the file in the console:

$ python3.6 input_demo.py
You are really tall
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

Now when we run the file, we get a different message:

$ python3.6 input_demo.py
You are really short

Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

Now let's run it:

$ python3.6 input_demo.py
You are of average height
Enter fullscreen mode Exit fullscreen mode

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

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"
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Learn more on 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.

Top comments (0)