The Ultimate Python Tutorial for Beginners
How to Level up your python skills.
Introduction
Python has become one of the most programming languages in the world. This guide should cover most of the basics of Python, including its syntax, data structures, and object-oriented programming.
Why are we learning Python?
Python is an excellent choice for a programming language as it has vast usage, and it is one of the most favored languages for data scientists.
Python can be used in various fields;
web development
game development
scientific computing
machine learning
Artificial intelligence and so many others I may have not mentioned
Python, you can create fast prototypes, automate operations, and handle big data with ease. Therefore, learning Python can be incredibly beneficial for professionals from diverse backgrounds and aspirations.
And with that let's get started.
Variables
You would think of this as a placeholder or a container that you would want to store something, and so in Python values are stored in variables. And in this way, it makes it easier to work with and manipulate data in the code
There are no specific commands defining variables, the moment you assign a value to a variable that is it, let's look at this example.
subscriber = "Hello subscriber"
age = 30
In this case subscriber
and age
are a variable that stores values Hello subscriber and 30 respectively.
Variables can be of different data types, such as integers
(whole numbers), floats
(decimal numbers), strings
(text), booleans
(True or False), and more.
Python is dynamically typed, which means you don't need to explicitly declare the type of a variable. The type is inferred based on the value assigned to it.
Data Types
Once you have learned about variables it becomes important to understand that they can store different types of data in Python. Python provides several built-in data types to cater to this need. Let's explore them
Numeric types:
int
: integersfloat
: floating-point numberscomplex
: complex numbers
Sequence types:
str
: strings -: ordered, mutable sequencestuple
: ordered, immutable sequences
Mapping type:
dict
: key-value pairs
Set types:
set
: unordered, unique itemsfrozenset
: immutable set
Boolean type:
bool
: True or False
None type:
None
: represents the absence of a value
We can use type()
function to determine the data type of a particular value. For example, type(30) will return < 'int'>, and type("Hello") will return <class 'str'>.
Numbers
There are three main types of numbers: integers and floating-point numbers and complex.
x = 10 #integer
y = 2.89 #float
z = v7 #complex
#you can verify the type
print(type(x)) # expected <class 'int'>
print(type(y)) # <class 'float'>
print(type(z)) # <class 'complex'>
Strings
A String is a sequence of characters enclosed in quotation marks. It can be created using single quotes (''), double quotes (""), or triple quotes (''' ''').
greeting = "Hey I hope you are enjoying the article"
my_name = 'Steve Johns'
All of the above are acceptable.
Lists
Lists are a type of data structure that can hold an ordered collection of items. They are defined using square brackets [ ]
and can contain elements of different types. The items in a list can be accessed using their index, starting from 0 for the first element.
Lists are mutable, meaning that you can modify, add, or remove elements from them.
mylist = ["apple", "banana", "cherry"]
print(my_list) #expected ["apple", "banana", "cherry"]
Tuple
A tuple is similar to a list, but it is immutable, meaning that its elements cannot be modified once is created. Tuples are defined using parentheses ( ).
They can contain elements of different types and can be accessed using their index starting with zero. Tuples are often used to represent groups of related values that should not be changed, such as coordinates or records.
my_tuple = ("apple", "banana", "cherry", "apple", "cherry")
print(my_tuple) # expected ("apple", "banana", "cherry", "apple", "cherry")
Sets
A set is a collection of unique elements. Sets are unordered, meaning the elements are not stored in any specific order.
Sets are mutable, so you can add or remove elements from them. Sets are defined using curly brackets {} or the set() constructor.
thisset = {"apple", "banana", "cherry"}
print(thisset) #expected {"apple", "banana", "cherry"}
#set constructor
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset) #expected {"apple", "banana", "cherry"}
Dictionary
A dictionary is a collection of key-value pairs, where each key is unique. It is mutable data.
Values can be any data type, while the keys must be immutable types like strings or numbers. Dictionaries can be used to store and retrieve data efficiently using the key as an identifier.
Dictionaries are written with curly brackets {}
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2023
}
print(thisdict) #expected {'brand': 'Ford', 'model': 'Mustang', 'year': 2023}
Operators
Operators are symbols that perform various operations on variables or values.
Arithmetic Operators: These operators are used to perform mathematical operations like addition, subtraction, multiplication, division, modulus, and exponentiation.
Addition
+
: Adds two operands.Subtraction
-
: Subtracts the second operand from the first.Multiplication
*
: Multiplies two operands.Division
/
: Divides the first operand by the second (a result is always a floating-point number).Modulus
%
: Gives the remainder of the division.Exponentiation
**
: Raises the first operand to the power of the second.
Assignment Operators: These operators are used to assign values to variables.
Assignment
=
: Assigns the value of the right operand to the left operand.Addition Assignment
+=
: Adds the right operand to the left operand and assigns the result to the left operand.Subtraction Assignment
-=
: Subtracts the right operand from the left operand and assigns the result to the left operand.Multiplication Assignment
*=
: Multiplies the right operand with the left operand and assigns the result to the left operand.Division Assignment
/=
: Divides the left operand by the right operand and assigns the result to the left operand.Modulus Assignment
%=
: Performs modulus on the left operand with the right operand and assigns the result to the left operand.Exponentiation Assignment
**=
: Raises the left operand to the power of the right operand and assigns the result to the left operand.
Comparison Operators: These operators are used to compare two values and return a Boolean result (True or False).
Equal to (
==
): Checks if the values of two operands are equal.Not equal to (
!=
): Checks if the values of two operands are not equal.Greater than (
>
): Checks if the left operand is greater than the right operand.Less than (
<
): Checks if the left operand is less than the right operand.Greater than or equal to (
>=
): Checks if the left operand is greater than or equal to the right operand.Less than or equal to (
<=
): Checks if the left operand is less than or equal to the right operand.
Logical Operators: These operators are used to combine multiple conditions and return a Boolean result.
Logical AND (
and
): Returns True if both operands are True.Logical OR (
or
): Returns True if at least one of the operands is True.Logical NOT (
not
): Returns the opposite Boolean value of the operand.
Membership Operators: These operators are used to test membership in a sequence (strings, lists, etc.).
in
: Returns True if a value is found in the sequence.not in
: Returns True if a value is not found in the sequence.
Identity Operators: These operators are used to compare the memory addresses of two objects.
is: Returns True if the memory addresses of two objects are the same.
is not: Returns True if the memory addresses of two objects are not the same.
Comments
Comments in Python are used to add explanatory notes or make the code more readable. They are ignored by the Python interpreter and do not affect the execution of the program.
There are two types of comments,
-single-line comment #
, multi-line """ """
or ''' '''
# This is a single-line comment
"""
This is a multi-line comment.
It can be useful for providing more detailed explanations.
"""
Comments are helpful for documenting code, providing a brief description of the code's purpose, explaining complex algorithms, or making notes for future reference. They serve as a way to communicate with other programmers (including your future self!) who may need to understand or maintain the code.
Loops
Loops are used to repeatedly execute a block of code at certain times until certain conditions are met.
There are two types of loops available in Python: the for
loop and the while
loop.
for loop
The for
loop is typically used when the number of iterations is known or when you want to iterate over a sequence, such as a list, tuple, dictionary, set, or string. It iterates over each item in the sequence and executes the code block for each iteration. Here is the syntax of a for
loop:
#syntax
for item in sequence:
# code block to be executed
#example
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f)
#expected output
'''
apple
banana
cherry
'''
while loop
The while
loop executes the code block as long as a certain condition is true. The condition is checked before each iteration. Here is the syntax of a while
loop:
while condition:
#code of block to be excecuted
#example
num = 1
while num <= 5:
num += 1
print(num)
#In example, the loop continues until the condition num <= 5 becomes false
Functions
Functions are reusable blocks of code that perform a specific task. They help improve the readability, maintainability, and reusability of your code.
To define a function, you use the def
keyword followed by the function name, parentheses with any parameters, and a colon. The code block of the function is indented beneath the function definition. Here is the basic structure of a function:
def function_name(parameter1, parameter2):
# code block
Parameters are input variables that the function can accept for processing. They are defined within the parentheses and separated by commas. You can provide default values for parameters and make them optional.
Within the function code block, you can write the logic and operations that the function should perform. This can include calculations, data manipulations, conditionals, and more.
To use a function, you simply call it by its name followed by parentheses and pass arguments (if any) within the parentheses. The function will execute its code block and may return a result.
Let's check this example below
def add_numbers(num1, num2):
sum = num1 + num2
return sum
result = add_numbers(3, 4)
print(result) # Output: 7
Functions are powerful tools for organizing and structuring code. They help modularize tasks, reuse them, and make your base more manageable. They are at the core of building complex systems in Python.
I came across an article that I found useful in differentiating between arguments and parameters. It provides valuable insights into understanding the distinction between these two terms of programming.
Conditionals
In Python, conditionals are used to make decisions in your code based on certain conditions. They allow you to execute different code blocks depending on whether a condition is true or false.
The most commonly used conditional statements in Python are if
, elif
, and else
. The if
statement is used to check a condition and execute a code block if the condition is true. The elif
statement is used to check additional conditions if the previous conditions were not true. Finally, the else
statement is used to execute a code block if none of the previous conditions were true.
#syntax
if condition:
task
else:
task
#example
num = 10
if num > 0:
print("This number is a positive integer")
elif num < 0:
print("The number is a negative")
else:
print("This number is a zero")
#expected answer? well lemme give this up to you, leave a comment for
#an answer for this
Wrap up
Congrats ๐๐ป, we have learnt a lot so far.
If you enjoyed the content, please consider supporting me by subscribing. By doing so, you can access unlimited articles similar to what you just read.
Hurray!