Python Beginners Ebook
Python Beginners Ebook
Beginners
Hira Mariam
Python for Beginners
This work is licensed under the Creative Commons Attribution 4.0 International License. To
view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/ or send a letter to
Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
Contents
1 Introduction ........................................................................................................................................................................ 7
Background ............................................................................................................................................................................................................. 7
Why Python? .......................................................................................................................................................................................................... 7
What Python is used for? .............................................................................................................................................................................. 7
Who this book is for? ....................................................................................................................................................................................... 8
2 Setting Up Your Python Environment ........................................................................................................... 9
Running Python on Windows Command Prompt: ..................................................................................................................... 9
Writing Your First Hello World Program on Windows .......................................................................................................... 11
Running Python on OS X Terminal: ...................................................................................................................................................... 11
Writing Your First Hello World Program on OS X: ....................................................................................................................12
Running Python Externally on a Web Browser: ..........................................................................................................................13
3 Variables and Data Types ..................................................................................................................................... 14
Variables ................................................................................................................................................................................................................. 14
Rules to Use Variables ........................................................................................................................................................................................................... 15
Strings....................................................................................................................................................................................................................... 15
Printing a Substring .................................................................................................................................................................................................................. 16
Removing Whitespace From Strings ......................................................................................................................................................................... 16
Changing Letter Cases in Python ...................................................................................................................................................................................17
Finding the Length of the String .....................................................................................................................................................................................17
Combining or Concatenating More Than One String .....................................................................................................................................17
Adding Newlines and Tabs in Python ....................................................................................................................................................................... 18
Numbers ................................................................................................................................................................................................................. 18
Comments ............................................................................................................................................................................................................. 19
The Zen of Python ...........................................................................................................................................................................................20
4 Comments, Indentations and Statements ............................................................................................... 21
Python Comments and Statements ....................................................................................................................................................21
Multiline Python Statement .......................................................................................................................................................................21
Multiple Python Statement in One Line .......................................................................................................................................... 22
Strings Python Statements ....................................................................................................................................................................... 23
Blank Lines Python Statements ............................................................................................................................................................ 23
Python Indentation .......................................................................................................................................................................................... 23
Python Comment ............................................................................................................................................................................................. 24
Multiline Python Comment ....................................................................................................................................................................... 24
Indentation ............................................................................................................................................................................................................ 25
Conclusion ............................................................................................................................................................................................................ 25
10 Strings .............................................................................................................................................................................. 49
What are Strings ...............................................................................................................................................................................................49
How Strings are Indexed? ..........................................................................................................................................................................50
Slicing a String ....................................................................................................................................................................................................50
Positive and Negative Indexing of Strings .....................................................................................................................................50
Updating a String Through Slicing ...................................................................................................................................................... 51
Deleting a String ............................................................................................................................................................................................... 51
String Operations in Python ...................................................................................................................................................................... 51
The Concatenate Operation .............................................................................................................................................................................................. 51
Using Iteration in Strings ...................................................................................................................................................................................................... 52
Testing Sub Strings within a String .............................................................................................................................................................................. 52
Built-in Functions in Strings ............................................................................................................................................................................................... 53
Formatting Strings in Python ................................................................................................................................................................... 53
How to Ignore Escape Sequence? ............................................................................................................................................................................... 54
11 Lists ..................................................................................................................................................................................... 55
Indexing and Splitting in Lists ................................................................................................................................................................. 55
Updating an Item in List ..............................................................................................................................................................................56
Adding elements to the list ...................................................................................................................................................................... 57
Iterating a List ..................................................................................................................................................................................................... 57
12 Tuples ............................................................................................................................................................................... 58
Using a For Loop in Tuples .......................................................................................................................................................................58
Adding Items to Tuple ..................................................................................................................................................................................58
Negative Indexing in Tuple .......................................................................................................................................................................59
Changing Tuple Values ...............................................................................................................................................................................59
13 Dictionaries ................................................................................................................................................................... 60
Accessing Elements inside a Dictionary ........................................................................................................................................ 60
Changing Elements inside a Dictionary ........................................................................................................................................... 61
Using Loop to print keys and values ................................................................................................................................................. 61
Removing Items from a Dictionary......................................................................................................................................................62
14 Functions........................................................................................................................................................................ 63
How to define a Function? ........................................................................................................................................................................63
How to Call a Function? ..............................................................................................................................................................................64
Adding Parameters in Function Calling ...........................................................................................................................................64
Setting a Default Parameter.....................................................................................................................................................................64
*args or Multiple Arguments ....................................................................................................................................................................65
**kwargs or Multiple Keyword Arguments ....................................................................................................................................65
15 Modules .......................................................................................................................................................................... 66
What is a Module? .......................................................................................................................................................................................... 66
Importing a Module ....................................................................................................................................................................................... 66
‘From’ in Import Statement .......................................................................................................................................................................67
Renaming a Module using Alias ............................................................................................................................................................67
Built in Modules................................................................................................................................................................................................ 68
16 File Handling ............................................................................................................................................................... 70
File in Python .......................................................................................................................................................................................................70
Opening the File ...............................................................................................................................................................................................70
Reading or Writing the File ........................................................................................................................................................................71
Reading Parts of File.................................................................................................................................................................................................................71
Reading Lines of File ................................................................................................................................................................................................................71
Closing the File ............................................................................................................................................................................................................................ 72
Writing to a File ................................................................................................................................................................................................. 72
Creating a New File .................................................................................................................................................................................................................. 72
Appending to A File.................................................................................................................................................................................................................. 73
Deleting a File ..................................................................................................................................................................................................... 73
17 Exception Handling ................................................................................................................................................ 74
What is Error? ...................................................................................................................................................................................................... 74
What is Exception Handling? .................................................................................................................................................................. 74
ZeroDivision Exception ................................................................................................................................................................................ 75
FileNotFoundError Exception ................................................................................................................................................................. 75
Try-Except Code Blocks ............................................................................................................................................................................. 75
Else Block ..............................................................................................................................................................................................................76
Finally Exception .............................................................................................................................................................................................. 77
More Built-in-Exceptions ........................................................................................................................................................................... 77
Conclusion ........................................................................................................................................................................... 79
To Baba,
1
Introduction
Background
Python was created by Guido van Rossum and was released in 1991. It focuses on the
philosophy of code readability and emphasizes on the importance of whitespace. It is used for
writing both small- and large-scale programs.
Why Python?
Python is an easy to learn, readable and powerful programming language that focuses on the the high-
level data structures in a simple but effective perspective towards object oriented programming. Due to
its syntax and easily interpreted nature, it is the most favorite programming language of programmers
for the past few decades. The freedom given by python makes it easy for the developers to not just
create applications but also enable to generate and analyze data through its famous extensive libraries
such as Numpy, Pandas and Matplotlib.
This guide introduces the reader informally about the basic concepts and features in Python language to
have a hands-on experience with python by keeping the self-paced learner in thought to get started.
This guidebook doesn’t offer a detail explanation of Python language but is sufficient enough to provide
with the basics of Python.
• Web development
• Computing scientific and numeric data
• Creating GUI (Graphical User Interface) applications
• Software development
• Creating, managing business applications
It is viable to say that Python is an all-rounder programming language because of its versatile and
accessible nature. Companies like Google, NASA, Yahoo! among many others are using Python, it is no
wonder that Python is the most favorite language of Data Scientists as it is widely used in Artificial
Intelligence projects as well.
2
Setting Up Your Python Environment
If Python is pre-installed on your system then you just have to open Command Prompt in Windows and
Terminal application in MAC OS X. All you need to do is write a few lines of code and you are good to go
STEP 1:
Open Command Prompt on windows, once command prompt is opened
STEP 2:
Type ‘python’ inside the cmd(Command Prompt) shell:
STEP 3:
Once you type ‘python’ then press ‘Enter’, the screen will look like this:
If python is present on your system then you don’t have to download it, you can eaily get started to try
bits of python code, however, if Python is not present on your system then you might want to take a
watch this tutorial here to get a beginner-friendly python environment along with a code editor that will
enhance your options to code in Python.
10
The purpose of writing this simple hello world program is that if it runs correctly on your system then
any Python program could work just fine. We will look into how to write the same program on OS X.
STEP 1:
Go to Applications > Utilities > Terminal. You can also press cmd + spacebar and type ‘Terminal’ inside
the spotlight search bar.
11
STEP 2:
Once the terminal opens, type ‘python’ and press Enter. Your screen will show you the installed version
of python on your system.
Since we want to work with the latest python version, watch how to download the latest version of
python and install a code editor to interpret it here.
You will see your output rightly printed on the screen once you press Enter.
12
Trinket supports Python 3 which makes it an exclusive online code playground for python. Its enormous
support for python libraries among NumPy, Pandas and Matplotlib makes it easy to compute scientific
data.
13
3
Variables and Data Types
Variables
We have previously created a hello world program and saved it as a ‘hello_world.py’ file in our projects
file directory and now it’s time to add a variable to our hello world program. Just add a new line to the
beginning of the program and store it in a random variable
Run this program and you will see the same result as our first hello world program. But this time we
have stored our string inside a variable named ‘result’. A variable is holding the value associated to it. In
this case, the ‘result’ variable is holding the “hello world” value. The advantage of using variable in your
code is that you can use the variable and associate to more than one value at a time.
If you print the variable multiple times just like the code above then python takes the code line by line
and prints the value accordingly. But if the variable has more than one value associated to it and if you
only print the variable once, then python is going to print the latest value the variable is holding.
14
• Variables cannot be started with a number, you can start a variable with an alphabet,
underscore. The variable can contain a number but cannot start with it. For example, you can
write ‘formula_1’ but not ‘1_formula’ otherwise error will be generated.
• Using spaces in your variable name will generate an error, it is better to use underscores if you
want to show some break in your variable names. For example, ‘final result’ will cause an error
but ‘final_result’ won’t.
• Since Python has built-in functions and keywords so don’t use those functions or keyword
names as those names are already reserved, if you try to use keyword or function names as your
variable names then you will encounter an error. For example, the keyword ‘print’ is reserved
for printing only, you cannot use it as a variable name.
• It’s better to use lowercase letters in python, you won’t get any error if you use uppercase
letters, but it is always a good practice to use lowercase letters.
It will take some time for you to understand using variables rightly especially when your programs
become bigger and more complicated. You have to come up with name that are unique, easily readable
and short but descriptive. Remember the code you will write is not just limited to your code editor,
maybe you want to share it with other coders in the future. So, you have to make sure that your code is
easy to understand.
Strings
A string is simply a set of characters. Anything that is inside single or double quotes is called a string.
Depending on the type of sentence that you want to write, you can use single and double quotes
together.
15
Printing a Substring
You can print a part of a string as well. Let’s say that you want to print a few words out of the string but
not the whole string.
Now, let’s say that out of the whole string you want to only print cats and dogs, so basically you are
printing a substring which is a segment of a string, in order to print cats and dogs, you will get the
characters position and slice the string accordingly
The position ‘13’ defines that the string will start printing from the position ‘c’ and goes till the very end.
Note: you don’t have to define an end character position when you are printing the substring till the
very end.
16
The lower() method will print all the letters in the string in lowercase
The title() method will print the first letter of the words present in a string in an uppercase letter.
Now in order to combine these two strings, we are going to use ‘+’ between them to print the final
output
17
The combining method of strings is called concatenation in Python and programming in general.
Now in order to add a tab in python string then you need to add a ‘\’ backslash and a ‘t’ which stands for
tab, it behaves similar to the function of tab key present on the keyboard to give indentation to the text.
Numbers
Numbers are used in programming language to perform scientific calculations, arithmetic operations or
just doing simple math. There are two main types of numbers sued in python:
• Integers
• Float
You can apply simple arithmetic operations on integers like addition, subtraction, multiplication, division
in Python.
18
You can apply the same arithmetic operations to float numbers as well but float values will always have
a decimal. For example, 3.12 and 0.0003 are all float numbers.
Comments
Writing comments is very important in python as it enables coder to take notes and bookmark the code
especially when the code gets bigger and complicated. Note: A comment is never part of the code but it
just hints the coder about a particular block of code to classify. You can write comments in multiple
ways in Python:
Use hashtag (#) in the beginning of the comment, the line will be treated as a comment in python.
Using triple single quotes (‘’’”) in the beginning and at the end is also used to write comments in Python.
You can use docstrings in python as well, A docstring is simply a multi-line string, that is not assigned to
anything. It is specified in source code that is used to document a specific segment of code. You can
represent a docstring by using triple double quotes in the beginning and at the end of the string.
19
20
4
Comments, Indentations and
Statements
In this tutorial we are going to revise the basic syntax of python along with the addition of Statements
and Comments along with some examples.
21
22
If you use double quotes outside, use single quotes wherever you need to use a quote inside.
Python Indentation
Unlike C++ or Java, Python does not use curly braces for indentation. Instead, Python mandates
indentation. At this point, our inner monsters are laughing at the lazy programmers around us.
There are no strict rules on what kind of Python indentation you use. But it must be consistent
throughout the block. Although, four whitespaces are usually preferred, and tabs are discouraged. Let’s
take an example with an inconsistent indentation in python.
23
Python Comment
Python Comment is a programmer’s tool. We use them to explain the code, and the interpreter ignores
them. You never know when a programmer may have to understand code written by another and make
changes to it. Other times, give your brain a month’s time, and it might forget what it once had conjured
up in your code. For these purposes, good code will hold comments in the right places.
In C++, we have // for single-lined comments, and /* … */ for multiple-lined comments. Here, we only
have single-lined python comment.
To declare a Python comment, use the octothorpe (hash) (#).
You can also use triple quotes (‘’’ ‘’’ or “”” “””) for this purpose.
This comment is spread on multi lines. The only difference between a ‘#’ and triple quotes is that ‘#’ is
always spanned on a single line, whereas if your comment is more than one line then you must use
triple (“””) quotes at the start and at the end of the comment.
While triple quotes are generally used for multiline python comment, we can conveniently use them for
python comment as well.
Triple quotes will also preserve formatting.
24
Indentation
Most of the programming languages like C, C++, Java use braces { } to define a block of code. Python
uses indentation.
Generally, four whitespaces are used for indentation and is preferred over tabs. Here is an example:
Conclusion
Hope we have tried to connect you with the basics of how the comments, statements and indentations
work in Python. You can try your own combinations to test further.
25
5
Basic Operators
Python supports basic operations since it is built on logic, a number of operations can be applied. Python
operators are divided into eight categories that you can use to do certain operations:
Arithmetic Operator
Just as the name goes, arithmetic operators are used to do simple calculations like addition, subtraction,
division, modulo, exponential power and multiplication
26
27
Comparison Operator
Comparison operators are used to compare values and return the result by checking the nature of the
output as True or False
28
29
Assignment Operator
Assignment operators are used to assign values (operands) to the variables. There are a lot of
assignment operators used in python:
Calculate exponent(raise
power) of left value with right
operand and assign value to x **= y
**= left operand x = x ** y
30
Logical Operator
Logical operators perform AND, NOT and OR functions between operands
Bitwise Operator
As the name goes by, bitwise operators perform operations bit by bit.
31
Special Operators
• Identity operators: is and is not are the used to see if two operands are present on the same
memory location or not
• Membership operators: in and not are used to check whether a value or operand is present in a
sequence or not
32
6
If Else and Elif Statements
Sometimes we need to set some conditions for our code to run a certain block of code upon meeting the
condition. These are called using conditional statements in programming. Python also supports logical
conditional statements
• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
If Statement
We test a simple condition by using the ‘if’ keyword and then present a certain condition.
Else Statement
The else statement is used when there are two conditions to be checked within a code block. For
example:
33
Elif Statement
Elif conditions are used when there are more than two conditions involved, for example if two values
doesn’t meet the condition then the third condition might work.
34
7
Loops
We need looping or ‘loops’ in python especially when we want a certain block of code to run unless the
condition is met. Let’s say that we want python top print natural numbers from 1 to 10 and then stop.
So, instead of writing the print statement for every number, we will create a loop. Now, there are two
types of loops in python:
• While Loop
• For Loop
• Nested Loops
While Loop
A while loop in python continues to execute the code as long as the given condition is true, if it becomes
false, then the loop stops.
Another reason to use while loop is when we aren’t sure about how many times to iterate.
35
In the above syntax, a while loop starts by checking the expression, if the expression is true, the loop
continues to statements. After making an iteration, it goes back to expression and continues to execute
through the statements until the expression becomes False.
In the above example, the variable n is already set to 1, and a while loop is set to a condition where n is
less than 10, then on line 3 the print statement prints n where currently 1 is stored, on line 4 the n is
incremented by 1 and becomes 2 and n now holds 2. The loop continues to execute and increment until
n becomes 10; when n becomes 10 the expression becomes false, hence the loop stops.
Note: The while loop will run infinite times if ‘n’ doesn’t get an increment, hence it will make your
program unstoppable and may cause errors.
36
For Loop
For loop is a python loop which repeats a group of statements for a given number of times. It is always a
good practice to use the for loop when we know the number of iterations.
37
Here is an example of a list containing fruits, let us use for loop to go through each known number
of fruits:
You can use the for loop to print each letter of a string as well.
38
Explanation
At first, we define a list of total icecream_toppings in this example. Next we made a list
of available_toppings that are currently present. Now if we find anything that is not available currently
like ‘strawberry’ , ‘cotton candy’ and ‘cherry’ then we loop through the list of available_toppings. Inside
the loop we check to see if the available_toppings is present in the list of icecream_toppings, if it is
then we add the available toppings on the ice cream. If the available_toppings is not in the list
of icecream_toppings, the else block will run. The else block will tell which toppings are not currently in
stock.
39
Nested Loops
Python supports using the nested loop that is a loop within a loop. The following example is an
explanation of how a nested loop works.
Let’s look at an example of a nested loop containing for loops inside it.
40
8
Control Statements
Let’s learn about the control statements in python now, control statements change the way we execute
a loop from its normal behavior. There are many types of control statements in python that you can use
to control the loops:
Break Statement
Break statement is used to terminate or abandon the loop. Once the loop breaks then the next
statement after the break continues. The main reason we could use the break statement is to take a
quick exit from a nested loop (i.e. a loop within a loop). The break statement is used with
both while and for loop.
Syntax
41
Continue Statement
Continue statement in Python is used to continue running the program even after the program
encounters a break during execution. The continue statement enables the code to proceed inside a loop
and move on skipping the particular condition.
Syntax
42
The execution will skip the ‘space’ character and continue to print the rest of the loop without any
interruptions.
Pass Statement
The pass statement is used when comment cannot be printed to show the program’s status to the
programmer. It is always going to be a null operation. For example, if a programmer has written a
comment within the code, then that comment will be ignored but the pass statement won’t be ignored.
It will be used as a placeholder.
Syntax
43
44
9
Number Types
There are three main types of numbers in Python:
• Integer
• Decimal
• Complex
These different numbers can be assigned to the variables and to verify the type of any object in Python,
use the function:
The difference between integers and float numbers is that a float number is separated by a decimal. So
’10’ is an integer and ‘10.5’ is a float number. Python gives us the freedom to store the integer, floating
and complex numbers and also lets us do conversion operations between them.
45
Integers in Python
Python can hold signed integers.
It can hold a value of any length, the only limitation being the amount of memory available.
type() function
It takes one argument, and returns which class it belongs to.
isinstance()
It takes two parameters as the argument. So the isinstance() function checks whether or not the object
is an instance or subclass of classinfo and returns True if it is, else it returns false.
Here, 2 is the real part, and 3j is the imaginary part. To denote the irrational part, however, you can’t
use the letter ‘i’, like you would do on paper.
46
Exponential numbers
You can write an exponential number using the letter ‘e’ between the mantissa and the exponent.
Remember that this is power of 10. To raise a number to another’s power, we use the ** operator.
If you face difficulty in Python number types, please comment.
Float in Python
Float, or “floating point number” is a number, positive or negative, containing one or more decimals.
A float value is only accurate upto 15 decimal places. After that, it rounds the number off.
47
In this tutorial, we learnt about Python number types. We looked at int, float, and complex numbers in
detail. You can try out your own combination and test accordingly.
48
10
Strings
In this tutorial we will learn about strings in python. We will learn about how to create, edit and delete
strings, also we will learn about the associate operations and functions of strings.
Note: Strings are not limited to be enclosed in single or double quotes, rather you can use triple quotes
as well to create a multiline string:
49
Since, indexing always starts from 0, so the first letter will be ‘p’ in this case which is stored at 0 index.
The output of the above code will be:
Slicing a String
You can also slice a string by choosing the index number of characters that you want to slice through the
slicing method. Let’s slice p from python by omitting index ‘0’ from the rest of the index numbers of
characters:
50
Deleting a String
You can delete a string too but remember that deleting a character from a string is not possible however
you can delete an entire string using del function:
You can also concatenate a string by using the * sign i.e. if you want to print a same string multiple times
then you need to multiply the string with that particular number.
51
52
53
Now, there are multiple ways to tackle the issue of this syntax error caused by using double quotes or
single quotes together. You can use triple quotes around single and quotes to remove this issue or you
can use escape sequence (\) to remove the issue.
54
11
Lists
Python list is used to store the sequence of different data types. Python, however, includes six kinds of
data types that can store the sequences, but list is the most prevalent and reliable form.
A list may be defined as a collection of different types of values or items. The items in the list are divided
by the comma (,) and items are encapsulated inside the square brackets [].
List = [1,2,3,4,5,6]
1 2 3 4 5 6
55
Python gives us the flexibility to use negative indexing as well, unlike other languages. From the right,
negative indexes are counted. The list's last component (most right) has the index-1, its next element is
placed in the index-2 (from right to left) and so on until most of the left component is found.
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
You can also delete the queue components by using the del keyword.
Also, Python provides us with the remove() method or a pop() method if we don't know which
component to remove from the list. The pop() method removes the last element of the list if the index is
not provided.
56
Iterating a List
You can iterate through a list as well by using a for loop
57
12
Tuples
Using Python Tuple, the sequence of immutable python objects is stored. Tuple is similar to lists since it
is possible to change the value of the items stored in the list while the tuple is immutable and it is not
possible to change the value of the items stored in the tuple.
A tuple comprises of set of comma-separated objects encapsulated inside the parentheses. The
following can be described as a tuple:
banana won’t be created as a new element since tuple doesn’t support it. Hence, the output will be:
58
We were able to convert the tuple into a list by using the list() constructor and later we converted the
list into a tuple again by using the tuple() constructor.
59
13
Dictionaries
A dictionary is an unordered, mutable, and indexed collection. Dictionaries are created by using curly br
ackets in Python, and they consist of key value pairs. Let's create a simple dictionary to understand
more:
In the above example we have seen that we have created a dictionary known as book, which consists of
three key-value pairs where pages, name and year are the keys and 277, Gone Girl and 2007 are their
respective values.
60
You can also print values separately which is not possible in using a regular for loop (which only prints
keys), so in order to print values you can use the values() method at the end of the dictionary’s name,
If you want to print both keys and values together as a key-value pair using a for loop, you can do that as
well by using two variables n and m that will get stored in items() methods,
61
You can use the del function as well to delete an item inside a dictionary or the whole dictionary as well:
Similarly, you can delete the whole dictionary as well by using the del keyword:
62
14
Functions
This tutorial will guide you through the Python function. It enables you know how to build user-defined
functions and use them to compose Python module programs.
Python enables us to split a big program into the chunks of function-friendly buildin. The
function includes the collection of { } curly brackets. A function can be called several times to provide the
python program with reusability and modularity.
• First, to define a python function you will use the keyword ‘def’ before the describing the name
of the function. ‘def’ stands for ‘define’. Once you have added def followed by the function
name (which should follow the same rules that we used while defining the variables in python),
and after defining the function name add parentheses as well with colon in the end. Syntax of
writing a function:
• Next, you will add the function body, this part decides what your function is going to do. Add
valid python code here.
• You can add a return statement if you want. However, that is completely optional.
63
print ("My name is " + name + " and my age is " + str(age))
change_name("Hira", 25)
change_name("Smith", 30)
64
65
15
Modules
What is a Module?
A module is a python file with a ‘.py’ extension which consists of functions, statements and variables.
The reason we use modules is to break down big programs into simpler and smaller ones. We can reuse
module files anytime as well.
Let’s create a module file and name it as ‘my_code.py’, and create a function inside it.
Importing a Module
Now that we created a module file, let’s save it in the same directory where our main python file is
stored. Now let’s suppose we are inside our main.py file; now it’s time to use the import statement to
import the my_code.py file:
When the python interpreter sees an import statement, it imports the module file if the module is
present in the same directory, otherwsie it will show an error. Once the module is imported then you
can call the relevant function name that you want to use.
Note: Whenever you want to use the function from your module file, then you have to follow the
syntax: modulename.functionname().
66
Note: once you have specifically imported the function, variable or statement in your main program then
you don’t have use modulename.functionname() syntax while calling it in your main file. Just call the
name directly with from statement.
67
Built in Modules
There is an extensive list of all the built-in modules that python supports, each caters a different
functionality and usage depending on what we want to calculate. In order to see the list of modules
python supports just type:
68
69
16
File Handling
File in Python
We all know about what is a file in conventional terms but let's talk about the file in python. It is just like
a normal file that is stored in the conventional way inside the hard disk because things stored in RAM
are temporary and are likely to be missing once the computer gets turn off.
Let's say we want to read from or write a file in python so we will have to open the file first. And after
performing particular task we need to close the file as well. So, we have to follow all the steps in order
to handle files in python. Python file operations is divided into four parts:
The open() function takes two parameters; filename, and mode separated by the commas (filename,
mode)
• Filename is going to be the name of the file that you want to open.
• Mode is going to decide that in which specification we want to open the file. There are four
different types of modes that you can use:
o "r" - Read Mode - It is the default value when there is no mode defined. 'r' is used to
open the file in read mode
o "a" - Append Mode - It opens to file for appending, and if there is none then it creates
one.
o "w" - Write Mode - It opens the file for writing, This mode can overwrite or create new
content in the file.
o "x" - Create Mode - It is only validated as long as there is no existing file. If the file
already exists in the directory, then it shows an error.
o "t" - Text Mode - Default text view mode. The file in python always opens in the text
mode unless you change it.
o "b" - BinaryMode - If your file is an image then you may want to utilize this mode to
open image files.
70
To open the file, you need to use the following syntax in a python file, let's suppose that file is main.py,
here you will enter the following:
Note: The above statement opens the file named 'new' in the default read ('r') and text mode (t'). If the
file doesn't exist in the directory, then you will get an error.
Once the read() method is printed then all the contents present in the 'new.txt' file will get printed on
the screen, so the output will be:
Output:
If you run the readline() function twice then python will execute the second line and on.
71
Writing to a File
Once we learned about reading the file, now it is time use the write() method in 'w' mode. This will
erase all previous content and overwrite new one.
So, the new text has replaced the old one, and all previous data is erased.
Run the code once, in order to write something to it, remove the previous code and enter the following:
72
Appending to A File
You can append text at the end of the existing content as well by using the 'a' as your parameter.
Deleting a File
You can delete a file in python as well by using the import os statement
If you will check your directory, you will see that the ‘new’ file isn’t there anymore.
73
17
Exception Handling
What is Error?
Error occurring is an unfortunate event in coding that happens when something in the code is not right.
It could be a human mistake in coding structure or calculations.
74
ZeroDivision Exception
Let’s look at a quick example of the zero-exception error that happens when a number is divided by 0.
Above, you can see that there is a ZeroDivisionError: division by zero, python stops the program right
there unless we put an exception to prepare ourselves for this kind of error.
FileNotFoundError Exception
When we are working with files, it is very common to have missing files issues. This may occur due to a
different storage location of the file or maybe you have misspelled the file name or the file may not exist
at all. Let’s try an example and read a file named ‘popeye.txt’. Now the below program is trying to read
the file ‘popeye.txt’ but since we haven’t saved the file let’s see what happens:
The output reports a FileNotFoundError exception. To minimize this exception, the try-except block will
be useful so that the program doesn’t generate any error.
You can use exceptions to prevent programs from crashing. This is very reason why we need exceptions
in the first place.
75
Else Block
To make more sense of the try-except block, we can introduce an else statement with it as well to or
calculate the answer if the given condition is met otherwise.
76
Finally Exception
After trying out try-except and try-except-else blocks, it is time to learn about the finally
block. This block will always execute no matter whether try turns out to be true or false.
More Built-in-Exceptions
Here is a list of more python built-in-exceptions that can help you minimize errors in your programs.
Check out more on Python Exceptions Docs
EXCEPTION DESCRIPTION
EOFError Raised when the input() function hits the end-of-file condition.
KeyboardInterrupt Raised when the user hits the interrupt key (Ctrl+c or delete).
NameError Raised when a variable is not found in the local or global scope.
77
EXCEPTION DESCRIPTION
RuntimeError Raised when an error does not fall under any other category.
78
Conclusion
This book may not contain all your answers regarding Deep Python, but will surely make you familiar
with the initial programming concepts and syntax of how simple Python is to start with as this book is a
beginner’s guide to launch in Python. You can always refer to the online resources like StackOverflow,
Quora and Python.org to learn more about other branches (Libraries) that will help you learn python
even in more depth.
79