Learn Python Fast Deep Simple
Learn Python Fast Deep Simple
2
Table of Contents
3
type() function ................................................................................................................................................................... 32
Integer numbers................................................................................................................................................................ 33
Type Casting........................................................................................................................................................................ 36
Type conversion ................................................................................................................................................................ 42
Casting Boolean into integer ........................................................................................................................................ 43
Concatenating by using format() function ............................................................................................................. 44
Float data type ................................................................................................................................................................... 47
Rounding numbers........................................................................................................................................................... 48
Boolean data type ............................................................................................................................................................. 49
Python Data Types Exercises ....................................................................................................................................... 52
Operators in Python .......................................................................................................................................... 53
Arithmetic operators ....................................................................................................................................................... 53
Assignment operators..................................................................................................................................................... 56
Comparison operators .................................................................................................................................................... 57
Boolean (Logical) operators......................................................................................................................................... 59
Understanding the Operator Precedence ............................................................................................................... 61
Python Operators Exercises ......................................................................................................................................... 64
Important built-in functions in Python ..................................................................................................... 65
Important functions to work with Strings.............................................................................................................. 65
len() function ...................................................................................................................................................................... 65
lower() and upper() functions .................................................................................................................................... 67
find() function .................................................................................................................................................................... 69
Conditional Execution ....................................................................................................................................... 71
The if statement................................................................................................................................................................. 71
The else part ....................................................................................................................................................................... 74
Multiple Conditions.......................................................................................................................................................... 75
Inner conditions ................................................................................................................................................................ 77
Combine conditions by using Boolean Operators ............................................................................................... 78
Python Conditionals Exercises .................................................................................................................................... 81
Write your own functions ................................................................................................................................ 82
Write your first function ................................................................................................................................................ 83
Return a value from a function ................................................................................................................................... 87
Pass arguments to a function ....................................................................................................................................... 90
Previously on functions.................................................................................................................................................. 92
Local scope vs Global scope .......................................................................................................................................... 94
Pro tips .................................................................................................................................................................................. 95
4
Python Custom Function Exercises ........................................................................................................................... 97
Data Structures in Python ............................................................................................................................... 98
List Data Structure in Python ...................................................................................................................................... 99
List Indexing................................................................................................................................................................ 101
Adding New Items to a List ................................................................................................................................... 103
Append a new Item to a List ................................................................................................................................. 106
Removing an item from a List .............................................................................................................................. 106
Updating an existing item in a List .................................................................................................................... 108
Clear a List ................................................................................................................................................................... 108
Sort the items of a List ............................................................................................................................................ 109
Count appearance of an item in a List .............................................................................................................. 110
Getting the length of a List .................................................................................................................................... 111
in keyword ................................................................................................................................................................... 111
Slicing a List in Python ............................................................................................................................................ 112
Copy a List by using List Comprehensions ..................................................................................................... 113
Filter a List ................................................................................................................................................................... 114
List of Lists in Python .............................................................................................................................................. 115
A String is like a List of Characters .................................................................................................................... 117
Tuples in Python ............................................................................................................................................................ 117
Sets in Python .................................................................................................................................................................. 119
Dictionaries in Python ................................................................................................................................................. 119
Adding or updating new Items to a Dictionary ............................................................................................ 121
Dictionary comprehension ................................................................................................................................... 122
Other Dictionaries useful functions................................................................................................................... 123
Arrays Data Structures in Python ........................................................................................................................... 124
Pandas and NumPy ....................................................................................................................................................... 126
Homogeneous vs Heterogeneous ............................................................................................................................ 126
Casting sequences.......................................................................................................................................................... 127
Python Lists Exercises ................................................................................................................................................. 129
Loops in Python ................................................................................................................................................. 130
Execute a code over and over ................................................................................................................................... 131
For Loop............................................................................................................................................................................. 132
The range() function .................................................................................................................................................... 135
Execute a code until a condition is true by using the While loop .............................................................. 135
Iterate over a collection of values ........................................................................................................................... 137
Iterate over a List........................................................................................................................................................... 137
5
Iterate over a Tuple ...................................................................................................................................................... 137
Iterating over a List of Lists ....................................................................................................................................... 138
Iterating over a Set ........................................................................................................................................................ 139
Iterating over a Dictionary......................................................................................................................................... 139
Python Break and Continue....................................................................................................................................... 140
Break a Loop .................................................................................................................................................................... 141
Continue a Loop.............................................................................................................................................................. 142
The Pass Statement ....................................................................................................................................................... 143
Return multiple values from a function by using sequences ....................................................................... 144
Python Loops Exercises .............................................................................................................................................. 146
What’s next? ..................................................................................................................................................................... 147
6
Section 1
Before we dive into the Python language, let me answer commonly asked
questions about Python and programming languages. A proper understanding
of what Python is can save us a lot of time and money.
7
At the present time, we cannot use human languages like English to express
our wishes to the computers.
Instead, we must use a programming language like Python that computers
know about it.
8
• Desktop Development
• Data Analysis
• Data Visualization
• Machine Learning and AI (artificial intelligence)
• Game Development
• Task automation and Everyday Tasks
• Much more
9
library in our program with a few lines of code without any worries
about bugs and errors!
Therefore, we usually need to use Python along with libraries to write our
programs in the most optimal way possible.
Also, frameworks are similar to libraries in some ways. A framework is a set of
codes usually written by other companies or individuals that can be used to
define the structure and skeleton of our programs.
So, both the libraries and frameworks are prewritten codes developed by other
developers or companies that we use to save our time and money.
10
Best book |course | bootcamp to learn everything
Even though there are lots of libraries and frameworks for Python, but you
don’t need to learn all of them!
In other words, it doesn’t make sense for one person to be a web developer, a
software developer, a game developer, an AI developer or a data science
developer at the same time! Instead, we should become a professional in one
or two of these.
13
Section 2
Software requirements
14
There are lots of online IDEs and code editors for Python development like
replit. Using these online tools keeps you away from installing tools. All you
need to do is to enter your Python code and click on the Run button:
There are other online IDEs and code editors like Online Python.
PyCharm
If you need to have a mature and well-configured IDE for Python
development, then PyCharm will be your choice. PyCharm is a free code editor
that is available on your favorite platform - Windows, macOS, and Linux.
15
Section 3
Single Quotes
16
A console is kind of computer terminal where we can view our program’s
output in text format. For simplicity's sake, we use console so that we can
focus on the core concepts of Python.
However, after learning Python, you can learn libraries like Tkinter to create
GUI (Graphical User Interface) programs. Programs that use widgets like
Buttons or Menus or List Boxes instead of simple texts.
So, we can print or display a text in the console by using a function named
print().
17
There are many functions in Python that each of which has its own use. I’ll talk
more about it later. But for now, all you need to know is that Python has its
own libraries named Standard Library. The Python Standard Libraries
contains libraries that each library contains lots of functions like the print().
In Python, a function is a block of code written by you or other developers that
performs a specific task. Functions provide better modularity for our
programs.
So, we have a print() function that takes a text and prints it in the console. In
programming terms, we call text a string. Strings in Python are contained
within a pair of single quotes ‘’ or double quotes “”. A string can contain any
characters including numbers, white space and special character like @:
18
The output of this program is:
As you can see, Python executes the code line by line from top to bottom.
Now when we run this code, the input() function waits for the user to type
some text. It tells the Python Interpreter to stop and wait for the user to enter
text with the keyboard:
19
The input() function waits for us to enter a value
So, type a value in the console, for example enter your name and press Enter:
The result of the input() function is the string that we type. But we must save
the result of this input() function somewhere for later use. To do so, we need
to use a variable. We use variables in our programs to remember information.
Consider a variable like a container that can holds one value and has a label on
it. So, a variable has one value and a name. Whenever we need to assign a
value to a variable or get its value, we only need to call its name.
Let’s define a variable named userName. We can use multiple words to define
a variable name, but without spaces:
20
After defining a variable, we use the = (assignment operator) to hold a value
inside it:
Now when we run the program and enter a value and press the Enter key,
Python will assign the entered value into the userName variable.
Then we can print the content of this variable by using the print() function:
When we run it, the print() function prints the content of the userName
variable in the console:
21
The equal sign assigns the
result of the input() function
This is what we entered
into the userName variable
22
In other words, the print() function needs a string to display in the console.
Sometimes we provide this argument by using single quotes and sometimes
we get a string from a function like input() and then pass the result of the
input() function to the print() function.
Python is Case-Sensitive
Python is a Case-Sensitive programming language. It means Python treats
uppercase and lowercase letters differently. So, it differentiates the uppercase
and lowercase variables:
As you see, it underlines the username with red wavy line. It is kind of error
message for us. This error message says we don’t have a variable named
username (all in lowercase letters)
23
them to guess the purpose of that variable and understand the code in a
faster rate.
• Also, if we want to choose multiple words for a variable, we cannot use
white spaces. Instead, we can use one of these two conventions:
o Camel Case: In this convention the first letter of each word is
capitalized, except for the first word, like userName.
o Snake Case: in this convention, all letters of each word is in
lowercase and each word is separated by an underscore, like
user_name. Snake case is more commonly used in Python.
• And a variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ) and starts with a letter or the underscore
character. We usually use numbers in a variable names to define
variables that are related to each other. For example, if we need to
assign three temperatures to three variables, we can define variables
like this:
Updating variables
A variable can hold one value at a time. Sometimes and during the execution
of the program, we need to update the value of a variable. To do so, we can use
the = (assignment operator):
24
So, we can simply update a variable by reassigning a new value to it. This new
value can be a value from another variable. For example, we can assign the
value of the default_login_status variable to the user_status variable:
25
A more meaningful input() function
As said earlier, we can also provide an argument for the input() function. By
doing so, our user knows what he should enter. We change the code like this:
When we run the program, it will display a message and asks us to enter our
name:
26
Expressions in Python
Sometimes we need to combine multiple values to create a new value. We call
it an expression. For example, we can concatenate two strings to create a new
string. In this example, we concatenated ‘Direction:’ with ‘Top’ and created a
new string ‘Direction:Top’.
So, this:
27
In an expression, we can also use variables. In this example, we have an
expression that concatenates the string ‘Direction’ with the value that is
inside the variable direction:
28
So, when I enter my name and press the Enter key, it prints the expression
inside the parentheses.
In fact, the entire code will be converted into zeros and ones. This is what a
CPU can understand and execute. In other words, a compiler is like Google
Translate for us. It converts the code from Python to Binary.
When our code is compiled, the computer (CPU) can read, understand and
execute it. This execution process is done by using Python interpreter. Finally,
this Interpreter executes the binary codes line by line:
Compiler
29
Python Variable Exercises
Are you ready to level up your Python skills? Dive into a world of hands-on
learning with the exercises I've carefully crafted just for you.
Why just read about Python when you can put your knowledge into action?
These exercises are designed to reinforce your understanding of key concepts,
sharpen your problem-solving abilities, and ignite your creativity.
Remember, practice makes perfect. By actively engaging with these exercises,
you'll not only build proficiency but also develop a robust programming
mindset. Embrace the thrill of discovery, experiment with different
approaches, and unlock the true potential of Python.
Don't just be a passive reader—be an active learner!
30
Section 4
31
Character number 3
Character number 4
Character number 5
Character number 0
Character number 1
Character number 2
type() function
In python, we have a function named type(). This function returns the type of
a variable. When we run the following code, it will print <class ‘str’> in the
console. str represents string:
When the Python interpreter wants to execute the line 2, it first executes the
type() function. As you see, the type() function accepts one argument. We can
32
provide its argument by passing a variable name or even a value. Then the
type() function returns the type of the language variable. And after that, the
interpreter executes the print() function and prints what the type() has
returned.
In other words, the result of the type() function is an argument for the print()
function.
Let’s back to the main topic of this section; Data Types. In Python there are 5
main data types including Sequences, Boolean, Dictionary, Set and Numeric:
String
Sequence
List
Type
Boolean Typle
Python
Dictionary
data types
Set Integer
Numeric Float
Complex
In this section, I’m going to talk about string, numeric and Boolean.
Integer numbers
We continue with numbers. In real world apps, we have to deal with numbers
too. To define a variable that holds a number, we can simply assign our
number without using single quotes or double quotes:
33
Numbers like 560 that have no floating point are called integer numbers.
We can also have expressions with numbers. In this example, we have an
expression that calculates the remaining days of an account. We can use the –
(minus) operator to subtract numbers:
There is a subtle point here. When we use the input() function to get a value
and enter a number, the returned value is always of type string even when we
enter a number:
34
In other words, the input function returns ‘1000’ and not 1000.
Let’s take another example to explain how to works. Suppose that we want to
take two numbers from our user, a number that represents years and another
one represents months. Then we need to convert them into days:
To do this task, we need to take two values from the user and do some math
operations on the numbers and print the final result:
35
At lines 1 and 2 we get two values from our user
At line 4 we convert years to days and months to days and assign it to the
days variable
At line 6 we print the result
But the result is not what we expected!
Type Casting
The previous program prints 2 for 365 times and prints 3 for 30 times! The
reason is that the input function returns a string. So, if we enter 2 as years and
3 as months, line 4 will be executed like this:
In fact, it displays the string “2” for 365 times and the string “3” for 30 times:
36
That is why we need to convert the string “2” into a number and the string “3”
into a number. In fact, if we need to use years and months in mathematical
operations, we must convert each of them to a numeric data type. To convert a
string type to an integer numeric type, we must use the int() function. The int()
function gets a value of type string and returns a value of type int as the result.
In programming terms, we call this operation Type Casting. So, let’s rewrite
line 4 like this:
37
It first multiplies 2 by 365, then multiplies 3 by 30 and then adds them
together.
Run the program again, and this time it works correctly:
But our task is not completed yet, because the final result is not printed in a
meaningful way. As said earlier, we need a message like this:
To do so, we can define another variable called result and create a meaningful
message by concatenating these numbers with some strings:
38
But when we run this program and enter years and months, we’ll get an error
message:
39
int represents integer. Integer is a number without any floating point. For
example, these numbers are integer:
• 100
• -50
• 0
As we saw already, the error message is like this:
It says: can only concatenate str (not “int”) to str. Python is trying to tell us
that it can’t concatenate a string to an integer.
The solution is to convert integers to strings by using the str() function. The
str() function takes a number as an argument and converts it to a string:
years and months are of type years and months are converted to
string. Because the result of input() integers temporarily, but their type
function is a string value is still string
Please note that we don’t need to convert years and months to integer.
Because they already are of type string.
Now run this code, enter two values as years and months and enjoy the result!
40
We can also cast an integer into float by using the float() function:
If you need to have a complete control on the floating-point part, for example,
you need to have 2 decimal places, then use the format() function:
41
Type conversion
Until now, you learned about a concept named Type Casting that allows us to
use functions like int() or str() to cast a type.
In this example, Python automatically converts the price data type from
integer to float temporarily to do the addition operation:
42
Casting Boolean into integer
We can also cast a Boolean value into an integer value. This is useful mostly
when we need to store Boolean values into database. When we cast a True
value into integer, it returns 1 and when we cast a False value into an integer
value, it returns 0:
By using the bool() function, we can convert an integer into Boolean. This
function returns False for 0 and return True for any number except zero:
43
Concatenating by using format() function
We can also perform string concatenation by using format() function. This
function helps us to do string concatenation in a clean way:
The format() function replaces the value of the followers variable with {}
placeholder.
There is a shorter form of the format() function. In this form, we can simply
put an f before the string and put the variable into the placeholder:
44
We can hold the result of the format() function in a variable and use it in the
next lines:
45
If we need to use multiple variables inside a string, then we can use multiple
placeholders:
Also here is another form of the format() function for the example:
46
Let’s rewrite the year converter example by using the format() function:
So all we need is to put placeholders by using {} and pass the variables to the
format() function to replace with the placeholders.
The format() function has these advantages over using the + (plus) operator:
• It is more readable
• It doesn’t need any type conversion
47
As you see, the pi variable is of type float.
Another point about floating point numbers is that, if a string contains a
floating point number, we can use the float() function to convert the string
into float:
Rounding numbers
This is a common problem in computer programming. Because floating point
values don’t have an exact binary representation. That’s why we may
experience some loss of precision and unexpected results.
To solve this, we need to use the format() function like this:
48
By using this syntax, we round the result value
to 1 decimal place
We can simply change this number to
change number of decimal places
This function replaces the result with the placeholder {}. But before replacing,
it formats the number by using the format we’ve defined inside the curly
braces. In this case, we’ve defined that format our number in a way that
displays only 1 decimal place.
So the format() function has two usages for us:
• Concatenating strings
• Formatting numbers
49
As another example, suppose that we’re going to take two numbers from our
user and check if they are equal or not. We check this equality by using the
equal to == (equal to) operator. So first of all, let’s get two numbers by using
the input() function:
Now, let’s check if the two variables are equal and then print the result. Note
that we need to convert num1 and num2 to integer and then compare them
by using the == operator:
When we run this code, and enter two numbers that are equal, we will get
True:
50
And when we enter two different numbers, then we will get False:
We can reverse a Boolean value by using the not operator. In other words, not
makes True to False and makes False to True:
In the next sections, you’ll see how the == (equal to) operator and other
comparison operators help us to run our code based on conditions.
51
Python Data Types Exercises
Are you ready to level up your Python skills? Dive into a world of hands-on
learning with the exercises I've carefully crafted just for you.
Why just read about Python when you can put your knowledge into action?
These exercises are designed to reinforce your understanding of key concepts,
sharpen your problem-solving abilities, and ignite your creativity.
Remember, practice makes perfect. By actively engaging with these exercises,
you'll not only build proficiency but also develop a robust programming
mindset. Embrace the thrill of discovery, experiment with different
approaches, and unlock the true potential of Python.
Don't just be a passive reader—be an active learner!
52
Section 5
Operators in Python
Arithmetic operators
Sometimes we need to perform arithmetic calculations in our programs. To do
so, we use these commonly used Arithmetic operators:
53
Operator Description Example
+ Addition 10 + 5 = 15
- Subtraction 10 – 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2.0
% Modulus. This operator returns the remainder. 10 % 5 = 0
** Exponentiation 2 ** 3 = 8
Each Arithmetic operator needs two operands. The value(s) that an operator
operates on is called the operand(s):
Operator
10 + 5
Operands
54
1- The return value of the Arithmetic operators is of type numeric. That is
why we used the str() function to print the result of each calculation.
2- The return value of the division operator is of type float. However, we
may don’t need to display the floating point.
To remove the floating point, we can simply use a function named trunc()
that is a part of math class. And as the math module is not accessible in our
code, we must import it first (at line 1):
55
Now you may ask what are modules? In Python, a module is like a library that
contains functions. For example, the math module provides functions that
contains mathematics functions. As you see at line 1, to access a module’s
functions, we need to import it into our program. After that, we can access the
functions that are inside that module. To call a function that is inside a module,
we must use a dot after the module name.
Assignment operators
You already know how the = (assignment operator) works. It assigns a value
into a variable for later use:
However, there’re times that we need to reassign a variable with a new value:
Python offers the Assignment operators. So, we can simply add 3 to the
onlineCustomers by using += operator without any repetition:
56
Operator Example Same As
= x = 10 x = 10
+= x += 2 x=x+2
-= x -= 2 x=x–2
*= x *= 2 x=x*2
/= x /= 2 x=x/2
%= x %= 2 x=x%2
As you see, each Assignment operator like the Arithmetic operator needs two
operands to work on.
Comparison operators
Comparison operators compare two values (operands) and evaluate down to
a Boolean result, True or False. You already seen the == (Equal to) operator:
The != (not equal to) evaluates to False when the operands (values on both
sides) are the same.
Another point about the comparison operators is that the operands can be
Numbers or Strings or Boolean values. You already see how the comparison
operators work with Numbers. Let’s see how they work with Strings.
When the operands are of type String, the comparison operators compare the
operands (Strings) letter by letter:
The result of arePassSame is True because the two operands are the same. In
other words:
58
So, when all the characters are the same, the final result is True. Otherwise,
the result is False. For example, in this case, as ‘c’ is not equal with ‘d’, the
result is False:
Even the following program will print False, because ‘B’ is not equal with ‘b’ as
Python is a case sensitive programming language:
59
Boolean operators return True or False.
Operator Description
and Evaluates down to True if both the operands are True
or Evaluates down to True even if one of the operands is
True
The and operator takes two Boolean values or expressions and evaluates
down to True if both the operands are True. Otherwise, it returns False:
Note that the Boolean operators can work with expressions too. An expression
is a combination of operands and operators:
The or operator takes two Boolean values or expressions and evaluates down
to False if both the operands are False. Otherwise, it returns True:
60
Understanding the Operator Precedence
In simple expressions that have one operator and two operands, the order is
not important. But when we have multiple operators and operands in one
expression, then we must be aware about a concept called Operator
Precedence. This precedence simply defines the order of execution.
To make it clear, I ask you to guess the output of this program:
Why? Because Multiplication has a higher order than Addition. So, it first
calculates 2 * 10 and then adds the result with 5.
Here is the order of operators in Python:
61
Operator Description
() Parentheses
** Exponent
*, /, //, % Multiplication, Division, Floor division,
Modulus
+, − Addition, Subtraction
==, !=, >, >=, <, <= Comparisons
and Logical AND
or Logical OR
Note that the operators with the same precedence have left-to-right
associativity. For example, in an expression like this:
5+2–3
the Addition and Subtraction have the same precedence. So, it evaluates the
expression from left to right.
Also, you may have noticed that Parentheses have the highest precedence. We
can use this feature of parentheses to simplify expressions:
62
63
Python Operators Exercises
Are you ready to level up your Python skills? Dive into a world of hands-on
learning with the exercises I've carefully crafted just for you.
Why just read about Python when you can put your knowledge into action?
These exercises are designed to reinforce your understanding of key concepts,
sharpen your problem-solving abilities, and ignite your creativity.
Remember, practice makes perfect. By actively engaging with these exercises,
you'll not only build proficiency but also develop a robust programming
mindset. Embrace the thrill of discovery, experiment with different
approaches, and unlock the true potential of Python.
Don't just be a passive reader—be an active learner!
64
Section 6
So far, we’ve worked with functions like input(), print(), format(), int() and str().
But there are lots of them in Python. Let’s talk about some other important functions in
Python.
len() function
len() is a function that works with Strings. Suppose that we need to check if a
password is strong enough or not. And one important feature of a strong password is
that the length of it is equal or greater than 8 characters. We can get the length of a
65
String by using the len() function. In this program, we get the length of a password
and check if it is strong or not:
66
lower() and upper() functions
The other useful functions that work with Strings are lower() and upper()
that helps us to convert a String to lowercase or uppercase. Suppose that we
need to get an email two times from our user and check if the emails are the
same. We can’t perform this task like this:
You can think about this code. Why this code doesn’t meet our needs?
Because, our user may enter her/his email in different formats:
[email protected]
[email protected]
[email protected]
And as we know, Python is Case-Sensitive. So, Python considers the emails as
three different texts:
67
So we need something like upper() or lower() to uppercase the inputs or
lowercase them and after that check if they’re the same:
Let’s see another example that directly prints the result of the lower() and
upper():
68
You may have noticed that some functions comes after a period, like lower()
and some are called like len().
find() function
This function is used to search inside a String. This function returns the index
of first occurrence of a substring from the given String:
69
70
Section 7
Conditional Execution
The if statement
The simplest decision-making statement is if statement. if is the most common
flow control in Python. Let’s get a password from our user and if it is a strong
password, then prints ‘it is a strong password’:
71
We can read line 3 like this: if the length of the password (variable) is greater
than or equal to 8 then execute line 4 else skip line 4.
Run this program two times. The first time enter a password that its length is
greater than or equal to 8 characters. It will print a message that says ‘Your
password is strong!’
And the second time, enter a password that its length is less than 8 characters:
72
Put : (Colon) after the if
The if condition
condition
73
When isEligible is True, it runs line 5, otherwise it skips line 5.
As said earlier, an if body can be a single line or multiple lines. Here is a two-
lines body:
Now we have two if statements. One of them checks if the password is greater
than or equal to 8 characters and prints the appropriate message when its
conditions is met and the other if statement (at line 6) checks if the password
length is less than 8 characters and if so, it prints another message.
74
So, when we run this program and enter a password that is less than 8
characters, then we’ll get an appropriate message instead of getting nothing:
Now our program is user friendlier! Because she/he knows what’s going on.
But this program needs some improvements. We can simply use else to
combine the two if statements into one:
We can read this code like this: if the condition is met, then execute the if
block (line 4), else execute the else block (line 6).
When we run this program, we’ll get the same result. But this program has a
better performance. Because it doesn’t need to check two conditions. It only
checks one condition.
Multiple Conditions
Sometimes the program logic requires to check multiple conditions. In such a
case, we can use elif to add extra conditions to the if statement:
75
We can have only one if or else statements, but it is possible to use elif
statement as many times as we need. Each elif statement executes its code
block if the previous conditions were False.
In this example, it checks what number has entered and based on the input
number, it will display a hello message. Our user can enter a number between
1 to 4, otherwise it will print a warning message instead of hello:
76
Note that we need to check user input with a String like ‘1’ or ‘2’ instead of 1
or 2. Because the input function (at line 6), will return a String. So, the type of
the language will be String and we need to check it with another String.
Also, when none of the if conditions are met, the else part will be executed:
Inner conditions
Also, there are times that we need to check multiple conditions in one if
condition. For example, suppose that we need to check tax rate like this:
77
At line 6 we define a variable named taxRate and initialize it with 0
temporarily, we will reassign it with an appropriate value at line 10 or 12
At line 8 we check if isMarried is True, if so then it checks (at line 9) also that
if hasChildren is True too, if so, it sets taxRate to 32
Line 12 will be executed only when the condition at line 9 is not met
The if statements at line 9 is called an inner if statement.
So, line 9 will be executed only if both the conditions are True, otherwise it
executes line 11.
The output of this program is the same as the previous one:
78
We can have as many conditions as we need. In this example, we have three
tests to use in the condition:
So, we use and when all the conditions must be True. Also, there are times that
we need to run a code when either one of the conditions is True. In that case,
we combine the conditions with or operator:
80
Python Conditionals Exercises
Are you ready to level up your Python skills? Dive into a world of hands-on
learning with the exercises I've carefully crafted just for you.
Why just read about Python when you can put your knowledge into action?
These exercises are designed to reinforce your understanding of key concepts,
sharpen your problem-solving abilities, and ignite your creativity.
Remember, practice makes perfect. By actively engaging with these exercises,
you'll not only build proficiency but also develop a robust programming
mindset. Embrace the thrill of discovery, experiment with different
approaches, and unlock the true potential of Python.
Don't just be a passive reader—be an active learner!
81
Section 8
Now you know that, there are built-in functions which are part of Python
Standard Library. In other words, functions like print(), input(), str(), int()
are written by Python developers. All we need as programmers, is to call them.
Besides that, we can define our own functions. Functions that we need to write
according to our needs.
So, there are two categories of functions:
• Built-in functions written by other developers. All we need to do is to
call them.
• User-defined functions written by us as developers. We must first write
the function and then call them.
Let’s see how to write user-defined functions in Python. Functions that belong
to us! Let me give an example to understand what are user-defined functions
and what are their usages.
Suppose we need to get a country name from the user and print its capital. So,
we may need something like this:
82
Write your first function
Now suppose that, we need to get another country from the user and convert
it to a capital name. So, what should we do now? Should we duplicate the same
code?
83
No never!
We must, convert this code to a user-defined function and then use the function
as many times we need. In Python, a user-defined function declaration begins
with the keyword def followed by the function name, a pair of parentheses
and a colon:
84
At line 1 we defined a function named country_to_capital. Use the snake case
convention for function names, in which all the words are written in
lowercase and each space is replaced by an underscore (_)
At lines 2 to 13 we implemented the body of the function. Yes, like the if
statement, user-defined functions have body. We can simply select all the code
we want to indent and press the Tab key
Why? Because at lines 1 to 13, we only defined the function. To run this
function, we need to call it. To do so, simply write the function name followed
by open and close parentheses:
85
So, at line 15, we called the function. Please note that there is not any
indentation. Now run it again. This time Python knows that it must call the
country_to_capital() function. In other words, it must run the body of this
function:
86
Now the body of the country_to_capital() will be executed two times:
So, it is clear that writing our own functions are sometimes useful. They help
us avoid code duplication. Also, functions help us to make our code more
organized.
87
But, in software design, it is a bad practice to write a function that has various
responsibilities. The function we wrote in the previous example, has three
tasks:
1- It gets a country name,
2- then determines the capital based on it,
3- and finally prints the result:
88
At lines 1 to 3 we defined a function named get_country() that gets an input
from user and assigns it to the country variable (line 2) and returns the value
of the country variable (line 3) A function can return any type of value
including strings, numbers or Booleans. We can even return the result of
input() function directly without using the country variable, but it is not
recommended as it decreases code readability.
At line 6 We first calls the get_country(), so it executes this function and after
the execution, returns the value of the country variable. Returns to where? It
returns to the place that get_country() is called.
So, a function can return a value by using the return keyword. We usually put
the return at the end of a function. Because a return ends the function
execution and returns the result to the caller.
When we run this program, we will get the same result. Now let’s extract Task
#3 into a new function.
89
Pass arguments to a function
So, we should define another function that its task is to print something. But
we must pass the values (arguments) it needs:
Parameters
Arguments
Also, when each function has its own specific task, it will increase testability of
our programs.
Besides that, when we follow this principle, it will improve the expandability.
For example, suppose that we want to print the result by using a real printer.
So we can simply write another function that do this and replace it with
print_in_console().
91
So now the country variable at line 9 knows which country our user has
entered.
Then Python continues running next line (line 11), and initializes the capital
variable with a temporary value (line 11), determines the capital (at lines 13
to 18) and finally executes the print_in_console() function, but before
executing, it passes country and capital to the print_in_console() function, so
now print_in_console() function knows what should be printed.
One point that you may have noticed by now is that a function may or may not
accept value or values. Also, a function may or may not return a value. It
depends on your program’s logic.
Previously on functions
If you are still confused about functions, this is for you. Let’s review it!
Python has some pre-written functions like str(). But there are times we need
to have our own functions that are called user-defined functions. So, if we
need to execute the same task again and again, we group its code into a
function, assigns a name to the function and call the function name again and
again, instead of duplicating the code. However, we also split our code into
functions to keep our program’s modularity.
In its simplest form, a function only is written to executes a task, without
accepting parameters or returns a value:
Also, there are times that we need to pass value or values to a function, so that
the function can work based on that value or values. In this example, we pass
the browser that we need to open:
92
If we need to pass multiple values to a function, we need to separate
parameters by using comma:
93
Local scope vs Global scope
Note that we cannot access a variables defined inside a function somewhere
else. Because they have a local scope. It means, when we define a variable
inside a function, it is only available in the function that created it. For
example, we cannot access opened_successfully outside the open_browser
function:
94
On the other hand, variables that are defined outside a function, are global
scope. It means they are accessible everywhere in the code. In this example,
we have defined baseTax variable in the global scope, so it is accessible in the
functions (lines 4 and 7) and outside of the functions (line 9).
One important point to note is that we cannot access a variable before we
create it:
Pro tips
And finally choose meaningful names for your functions. It helps us and other
developers that read our code to quickly understand the purpose of each
function. As functions are actions, the name can start with a varb like:
• send_email
• print_report
• build_database
• insert_into_database
• delete_file
• …
95
Also, if your function returns a value, use verbs like:
• get_email_address
• calculate_profit
• generate_report
• compute_delay
And if your function returns a Boolean value, then it is recommended to name
the function in a short question form:
• is_internet_connected
• are_emails_valid
96
Python Custom Function Exercises
Are you ready to level up your Python skills? Dive into a world of hands-on
learning with the exercises I've carefully crafted just for you.
Why just read about Python when you can put your knowledge into action?
These exercises are designed to reinforce your understanding of key concepts,
sharpen your problem-solving abilities, and ignite your creativity.
Remember, practice makes perfect. By actively engaging with these exercises,
you'll not only build proficiency but also develop a robust programming
mindset. Embrace the thrill of discovery, experiment with different
approaches, and unlock the true potential of Python.
Don't just be a passive reader—be an active learner!
97
Section 9
In Python and other programming languages, a Data Structure defines the way
that a group of related data can be stored under one name. In simple words,
until now, we defined variables to store one value. But by using a Data
Structure, we can store multiple values into one variable.
99
Using 7 variables instead of using a List would be something like this:
Now suppose that we need to know what the lowest temperature was in the
week?
Well, if we’ve stored values into a List, we can simply call a function named
min() and pass it the list of temperatures to find the lowest value:
100
But if we have stored values into multiple variables, we may need something
like this:
List Indexing
I talked already about indexes in Python. For example, the find() function is
used to search inside a String. This function returns the index of first
occurrence of a substring from the given String:
101
The output is 6, because the first occurrence of ‘there’ is at index 6. As said
before, counting starts from zero in Python.
Now let’s talk about how indexes work in Lists. To access each item of the List
individually, we can use the index of that particular item. For example, to
access the first value of the tempInMiami List, we need to use its index inside
[] (square brackets):
102
Index 10 doesn’t exist
in the list
103
To add a new Item to an existing List, we can simply use the insert() function.
The insert() function needs two arguments, an index and the new value we
need to insert in the List:
At line 1 we defined a List named items with two values of type String
At line 3 we inserts a new value ‘Item 3’ at index 2 of this List
So when we use the print() function to print this list, the output will be like
this:
104
We can also add multiple items at the same time to a List. To do so, we first
need to create another List and then extend the first List:
We can also create an empty List and then add items to it:
105
At line 1 we defined an empty list named items with no default items
106
The output is exactly what we expect:
Note that Python is Case-Sensitive. So, we will get an error message if we don’t
consider it:
So, we will get an error that says you’re going to remove something from a list,
but that thing does not exist in that list:
107
Updating an existing item in a List
Here is how we can update an existing item in a List:
We can simply use index of an item to reassign or update its value. So, line 3
means assign ‘Item 3’ with the value that exists at index 2 of the items List:
Clear a List
To remove all Items in a List at the same time, we can call the clear() function:
108
[] represents an empty list.
We can also sort items in descending order by reversing the result. All we
need to do is to pass reverse = True to the sort() function:
109
Note that the sort() function also works with Strings and Characters. By
default, the elements of a list of strings are sorted in alphabetical order:
110
Getting the length of a List
We can also find out how many items are in a List by using the count()
function:
in keyword
By using the in keyword, we can find out if an item exists in a list or not. If the
specified item exists in the list, it returns True otherwise it returns False. In
this example, False exists in the list, so the in keyword returns True and the if
statement executes its body (line 4):
111
Slicing a List in Python
We can also slice a List by using the : (colon slicing) operator. In other words,
we can access a range of items in a List by using this operator:
So, at line 3, we sliced the items List, that its start index is 1 and the end index
is 3. In other words, Python slices the items List from index 1 until index 3:
0 1 2 3 4 5 6
There is also another form of List slicing. We can start slicing from a specified
index to the end:
112
0 1 2 3 4 5 6
A for loop is used to iterate over a sequence like List. In this example, we have
4 iterations. Because the usdPrices List has 4 items. In each iteration, the for
113
loop assigns the current item to the price variable. For example, in the first
iteration, price is 117.6, in the second iteration, the value of the price variable
is 98.0 and so on.
The second way to copy a list is to use a concept named List Comprehension.
It works like the for loop in the previous example:
Filter a List
114
We can also filter a list by using List Comprehension. To filter a List, we need
to add an if statement. In this example, we copy the ages that are greater than
18 in a new List:
115
There is a subtle point here. The console tries to tell us that there are 4 Lists
inside another List. It does this by using [] (square brackets) like this:
[[…], […], […], […]]
So, at line 6 we have a List that contains 4 Lists as its items. Now the question
is how we can access the items of the inner Lists (week1, week2, week3 and
week4) through the main List (month)?
For example, how we can access the first item of the first List?
It is simple, all we need is to use [] (square brackets) two times. In other
words, in this case that we have Lists inside a List, we need to define two
indexes, the first index that defines which List and the second index the
defines which item of that List:
The output is 28, because the first item of the first List is 28!
116
So, by using Lists as items, we can organize our data even more!
However, we can convert a String into a List of characters by using the list()
function:
Tuples in Python
In Python, Tuples are like Lists. It means we can do what you learned about
Lists on the Tuples. The only difference is that Tuples are immutable
(unchangeable). In other words, once a Tuple is assigned, we can’t modify the
items of it.
To define a Tuple that holds the temperature of the last 7 days, we can use this
syntax:
117
And the output:
So, we use () parentheses to create a new Tuple. That’s why the Console uses
parentheses to display the result.
As said earlier, Tuples are immutable (unchangeable). So, we can’t use
functions that edit a Tuple like:
• insert()
• extend()
• remove()
• clear()
• sort()
But we can use the same functions that are used for retrieving items of a Tuple
like:
• len()
• count()
• min()
• max()
We can also slice a Tuple by using the : (colon slicing) operator and there is no
Tuple comprehension.
118
Sets in Python
Sets are also kind of Data Structures that can hold multiple values into one
variable. But Sets have their own advantages. The strength of Sets is that all
items in a set must be unique:
Dictionaries in Python
Dictionaries are used to store a collection of key-value pairs. We use : (colon)
to separate a key from its value and , (comma) to separate key-value pairs
from each other:
119
This is the output of line 3:
keys values
120
Now we can access the values by using the keys:
121
Dictionary comprehension
Like Sets and Lists, we can have Dictionary comprehensions. The simplest
form is like this:
As you see, we have created a copy of the user dictionary by using dictionary
comprehension. When we print the copy dictionary, we will get the same
result.
However, we can use Dictionary comprehension to filter a dictionary. In this
example, we have a dictionary contains tasks and their status. To filter this
dictionary, we can use the if statement. For example, we can filter the
dictionary to display the tasks that are False (are not yet done):
122
When we print the filtered dictionary, it displays the Walking tasks, as its
value is False:
123
Also, by using the values() function, we access all the values of a Dictionary:
Also by using the clear() function we can remove all the elements from a
Dictionary.
124
Now we have a variable named tempInMiami that have 7 values. Also please
note that we need to import a Module named array (line 1). Because Python
doesn’t support Arrays natively.
array.array means there is a Data Structure named array (the second array
after the dot) that is located inside a module named array (the first array):
This may confuse us. Because the names are the same. array in array?! What
the heck! So, let’s use a keyword named as in Python. We use it to assign an
alias name to modules:
Now we can access the array module by its alias name arr. But in Python, we
usually use Array’s replacements like Pandas and NumPy.
125
Pandas and NumPy
In Data-Driven programs, Pandas and NumPy is recommended. There are
libraries that adds more powerful Data Structures to Python. So, if Data
Analytics is your first priority in your programs, then try to learn these
libraries:
In a nutshell, if you need to do some basic tasks with data, use Python built-in
Data Structures like List, Tuple, Set and Dictionary. Otherwise, try to learn
Pandas and NumPy. It is good to know that we also call Lists, Tuples, Sets and
Dictionaries as iterables too. Because we can iterate over their elements.
Homogeneous vs Heterogeneous
There is an important note about the Data Structures you learned. All of them
are Heterogeneous except Arrays that are Homogeneous.
126
So, an Array is Homogeneous. In other words, an Array must contain elements
of the same data type.
Heterogeneous means items of a Data Structure like List can be a combination
of other types like integer numbers, floating-point numbers, Strings and
Tuples:
Casting sequences
We can use list(), tuple(), set() and dict() function for type conversion. For
example, to convert a List into a Tuple, we can simply use the tuple() function:
127
If we have a list of tuples, we can cast it into a dictionary by using the dict()
function. In this example, we have a list contains two tuples that each tuple
has a key and a value. By using the dict() function, we can convert the list into
a dictionary:
128
Python Lists Exercises
Are you ready to level up your Python skills? Dive into a world of hands-on
learning with the exercises I've carefully crafted just for you.
Why just read about Python when you can put your knowledge into action?
These exercises are designed to reinforce your understanding of key concepts,
sharpen your problem-solving abilities, and ignite your creativity.
Remember, practice makes perfect. By actively engaging with these exercises,
you'll not only build proficiency but also develop a robust programming
mindset. Embrace the thrill of discovery, experiment with different
approaches, and unlock the true potential of Python.
Don't just be a passive reader—be an active learner!
129
Section 10
Loops in Python
Two important Loop Structures in Python are For Loop and While Loop.
130
Execute a code over and over
Suppose that we’re writing a digital wallet and one of our tasks is to write a
code that:
• Accepts 5 words as recovery words
• Store the words into a List
• Displays the List
Without loops, we’ll have something like this:
131
But let’s use the For Loop to make life easier!
For Loop
This Loop Structure helps us to executes a code as many times as we need.
That is why I’m going to rewrite the previous code by using a For Loop:
132
As you see, the For Loop keeps our codes readable and makes it easy to
maintain the code.
A For Loop starts with the for keyword follow by a variable followed by in
keyword and a function named range and after that the body of the For Loop:
So, line 3 means repeat the body (lines 4 and 5) for 5 times. range(1, 6)
generates a sequence of numbers in the given range. In this example, it
generates numbers 1, 2, 3, 4 and 5 because we said to start from 1 until 6.
Here is how this program works:
1- In the first repetition, the For loop assigns 1 to the i variable and runs
the body. That is why it asks the user “Please enter word #1: ”, because i
is 1 at the moment
2- In the second repetition, the For loop assigns the next generated
number to i that is 2. That is why it asks the user “Please enter word #2:
”, because i is 2 at the moment
3- In the third repetition, the For loop assigns the next generated number
to i that is 3. That is why it asks the user “Please enter word #3: ”,
because i is 3 at the moment
4- In the fourth repetition, the For loop assigns the next generated number
to i that is 4. That is why it asks the user “Please enter word #4: ”,
because i is 4 at the moment
133
5- In the fifth repetition, the For loop assigns the next generated number to
i that is 5. That is why it asks the user “Please enter word #5: ”, because
i is 5 at the moment
Now you know how to repeat a task as many times as it needed. In
programming terms, we call each repetition an iteration.
The advantage of using loops is that we can simply maintain our programs.
Suppose that we want to change the input message. We can simply change it
at one place (line 4) instead of changing it 5 times:
Iteration i
1th 1
2th 2
3th 3
4th 4
5th 5
134
The range() function
The range() function generates a List of numbers. This function accepts
number or numbers and generates a sequence of numbers in a List. range(1,
6) generates a sequence of numbers in the given range:
[1, 2, 3, 4, 5]
We can also pass only one argument to this function, for example
range(6) that generates a sequence of numbers that starts from 0 until 6:
[0, 1, 2, 3, 4, 5]
So if we pass only 1 argument to the range() function, the default start value
will be 0.
And also we can pass three arguments to the function, for example range(1,
10, 2). That the first argument defines start, the second argument defines the
end and third argument defines the step. So the output of this range()
function is:
In other words, the step defines the incrementation. If we don’t specify the
third argument, the default value will be 1.
135
repetitions. In such a case, we should use While Loop. A While Loop repeats a
block of code as long as its condition is True:
This program accepts a number. If this number is even, then it executes line 7,
and if the number is odd, it executes line 9. This program runs indefinitely,
unless we enter 0. Because at line 3, we have defined while the number is not
0, run the While’s body (lines 4 to 9). Here is a sample output of this program:
When the condition of a while loop stays True forever, it executes its body
forever and is called infinite loop. So be careful about the condition.
136
In a nutshell, the While Loop helps us to run a block of code until a condition is
met. But if we need to iterate over a List, Tuple, Set or Dictionary, For Loop is the
better option.
137
Iterating over a List of Lists
We can also iterate over:
• a List of Lists
• or a List of Tuples
• or a Tuple of Lists
• or a Tuple of Tuples
• …
The same pattern is true for Sets and Dictionaries.
In this example, we have a List of Tuples and want to iterate over it. As you
see, this List las 2 Tuples as its items:
So, we use an outer loop (line 3) to iterate over tuples and use an inner loop
(line 4) to iterate over items of each Tuple.
Here is the Truth Table for this example:
138
Iteration a b
1th iteration of outer loop (' ', ' ') ' '
1th iteration of outer loop (' ', ' ') ' '
2th iteration of outer loop (' ', ' ') ' '
2th iteration of outer loop (' ', ' ') ' '
In other words, the outer Loop executes its body (line 4) two times and in
each execution (iteration), the inner loop executes its body (line 5) two times.
139
We can get values by using keys. To do so, all we need to do is to use the key
name to get the value (line 4):
Or we can directly iterate over the values by using the values() function:
140
Break a Loop
We can use the Break statement to terminate a For Loop or While Loop
immediately if a certain condition is met. In this example, we use the Break to
finish an endless loop. This program accepts unlimited numbers from us and
adds them together. If we enter =, then it terminates the endless loop by using
the Break statement:
At line 1 we defined a variable named sum that will hold the sum of the
numbers
At line 3 we defined an infinite loop. Because the condition is always True
At line 4 we get a value from the user
At line 5 we check if the value is =, then we must end the loop by using the
break (line 6). Otherwise, add the value to the current value of the sum
141
So, when a Break happens, the Loop ignores the remained iterations and
terminates the Loop.
Continue a Loop
The Continue statement ignores the remained block code and returns the loop
execution to the beginning of the loop. For example, let’s check if the value is
not a number, ends the current iteration and returns to the beginning of the
loop. We use isnumeric() method to check if all the characters are numeric:
142
At line 7 we check if the user enters a value that is not numeric, then we
ignore the rest of that iteration and moves to the next iteration by using the
Continue statement (line 8).
In a nutshell, the Break statement ends a loop completely, but a Continue
statement ends the current iteration and moves to the next iteration if exist.
So, when the pass is executed, nothing happens. This is useful when we need
to implement the main structure of our program and then implement the
details.
143
Return multiple values from a function by using
sequences
If we need to return multiple values from a function, we can return a sequence
like List, Tuple, Set or Dictionary. For example, the following function returns
multiple temperatures by using a List:
By doing so, we can simply return multiple values instead of one value from a
function:
144
The output is
145
Python Loops Exercises
Are you ready to level up your Python skills? Dive into a world of hands-on
learning with the exercises I've carefully crafted just for you.
Why just read about Python when you can put your knowledge into action?
These exercises are designed to reinforce your understanding of key concepts,
sharpen your problem-solving abilities, and ignite your creativity.
Remember, practice makes perfect. By actively engaging with these exercises,
you'll not only build proficiency but also develop a robust programming
mindset. Embrace the thrill of discovery, experiment with different
approaches, and unlock the true potential of Python.
Don't just be a passive reader—be an active learner!
146
What’s next?
Looking to get a deeper understanding of Python programming? Look no
further than my exclusive Premium Python Course! Join now and unlock a
wealth of expert insights and cutting-edge concepts.
147