Hands-On Python Programming For Beginners Learn Practical Python Fast
Hands-On Python Programming For Beginners Learn Practical Python Fast
Edited by AI Publishing
eBook Converted and Cover by Gazler Studio
Published by AI Publishing LLC
ISBN-13: 978-1-7347901-9-1
Legal Notice:
You are not permitted to amend, use, distribute, sell, quote, or
paraphrase any part of the content within this book without the specific
consent of the author.
Disclaimer Notice:
Kindly note that the information contained within this document is solely
for educational and entertainment purposes. No warranties of any kind
are indicated or expressed. Readers accept that the author is not
providing any legal, professional, financial, or medical advice. Kindly
consult a licensed professional before trying out any techniques
explained in this book.
https://www.aipublishing.io/book-hoppfb
(Note: The order number or the subscription email is
required.)
Get in Touch with Us
Preface
Book Approach
Who Is This Book For?
How to Use This Book?
About the Author
Chapter 1: Introduction
1.1. History of Python
1.2. Uses of Python
1.3. Commonly Used Python IDEs
1.4. Environment Setup
1.4.1. Windows Setup
1.4.2. Mac Setup
1.4.3. Linux Setup
1.4.4. Using Google Colab Cloud Environment
1.5. Writing Your First Program
1.6. Python Syntax
Chapter 2: Python Variables and Data Types
2.1. Python Variables
2.2. Python Data Types
2.2.1. Numeric Types
2.2.2. Strings
2.2.3. Boolean Variables
2.2.4. Lists
2.2.5. Tuples
2.2.6. Dictionaries
Exercise 2.1
Exercise 2.2
Chapter 3: Python Operators
3.1. What Are Python Operators
3.2. Arithmetic Operators
3.2.1. Addition Operator
3.2.2. Subtraction Operator
3.2.3. Multiplication Operator
3.2.4. Division Operator
3.2.5. Modulus Operator
3.2.6. Exponent Operator
3.3. Comparison Operators
3.3.1. Equality Operator
3.3.2. Inequality Operator
3.3.3. Greater Than Operator
3.3.4. Smaller Than Operator
3.3.5. Greater Than or Equals to Operator
3.3.6. Smaller Than or Equals to Operator
3.4. Assignment Operators
3.4.1. Assignment
3.4.2. Add and Assign
3.4.3. Subtract and Assign
3.4.4. Multiply and Assign
3.4.5. Divide and Assign
3.4.6. Take Modulus and Assign
3.4.7. Take Exponent and Assign
3.5. Logical Operators
3.5.1. AND Operator
3.5.2. OR Operator
3.5.3. NOT Operator
3.6. Membership Operators
3.6.1. The in Operator
3.6.2. The not in Operator
3.7. Identity Operators
3.7.1. The is Operator
3.7.2. The is not Operator
Exercise 3.1
Exercise 3.2
Chapter 4: Decision Making and Iteration Statements in
Python
4.1. Conditional Statements in Python
4.1.1. If and Else Statements
4.1.2. Elif Statements
4.1.3. Ternary Operator
4.1.4. Nesting Conditional Statements
4.2. Iteration Statements in Python
4.2.1. For Loop
4.2.2. While Loop
4.2.3. Nested Loops
4.2.4. Continue Pass and Break Statements
4.2.5. List Comprehensions in Python
Exercise 4.1
Exercise 4.2
Chapter 5: Functions in Python
5.1. What Are Functions?
5.2. Defining and Calling Functions
5.3. Parameterized Functions
5.4. Returning Values from Functions
5.5. Global and Local Variables and Functions
5.6. Lambda Functions
5.7. Recursive Functions
5.8. Function Decorators
5.8.1. Returning a Function
5.8.2. Passing a Function as a Parameter
5.8.3. Creating Decorators
5.9. Iterators and Generators
5.9.1. Iterators
5.9.2. Generators
Exercise 5.1
Exercise 5.2
Chapter 6: Object-Oriented Programming with Python
6.1. What Is Object-Oriented Programming?
6.2. Defining Classes and Creating Objects
6.3. Declaring Methods and Variables in a Class
6.4. Class Constructors
6.5. Class Members vs. Instance Members
6.6. Create Iterators Using Classes
6.7. Inheritance in Python
6.7.1. A Simple Example of Inheritance
6.7.2. An Advanced Example of Inheritance
6.7.3. Calling Parent Class Constructor via a Child
Class
6.7.4. Polymorphism
Exercise 6.1
Exercise 6.2
Chapter 7: Exception Handling with Python
7.1. What Are Exceptions?
7.2. Handling Multiple Exceptions
7.3. Individually Handling Different Exceptions
7.4. The Finally and Else Block
7.5. User-Defined Exceptions
Exercise 7.1
Exercise 7.2
Chapter 8: Reading and Writing Data from Files and
Sockets
8.1. Importing Files in Python
8.2. Working with Text Files
8.2.1. Reading Text Files
8.2.2. Writing/Creating Text Files
8.3. Working with CSV Files
8.3.1. Reading CSV Files
8.3.2. Writing CSV Files
8.4. Working with PDF Files
8.4.1. Reading PDF Files
8.4.2. Writing PDF Files
8.5. Sending and Receiving Data Over Sockets
8.5.1. Sending Data Through Sockets
8.5.2. Receiving Data Through a Socket
Exercise 8.1
Exercise 8.2
Chapter 9: Regular Expressions in Python
9.1. What is Regex?
9.2. Specifying Patterns Using Meta Characters
9.2.1. Square Brackets []
9.2.2. Period (.)
9.2.3. Carrot (^) and Dollar ($)
9.2.4. Plus (+) and Question Mark (+)
9.2.5. Alteration (|) and Grouping ()
9.2.6. Backslash
9.2.7. Special Sequences
9.3. Regular Expression Functions in Python
9.3.1. The findall() function
9.3.2. The split() function
9.3.3. The sub() and the subn() functions
9.3.4. The search()
Exercise 9.1
Exercise 9.2
Chapter 10: Some Useful Python Modules
10.1. Python Debugger
10.2. Collections Module
10.2.1. Counters
10.2.2. Default Dictionaries
10.2.3. Named Tuples
10.3. DateTime Module
10.3.1. Working with Time Only
10.3.2. Working Dates Only
10.4. Math Module
10.5. Random Module
10.6. Find Execution time of Python Scripts
10.6.1. Using Time Module
10.6.2. Using Timeit Module
10.6.3. The ##timeit Command
Exercise 10.1
Exercise 10.2
Chapter 11: Creating Custom Modules in Python
11.1. Why You Need Modules?
11.2. Creating and Importing a Basic Module
11.3. Creating and Importing Multiple Modules
11.4. Adding Classes to Custom Modules
11.5. Importing Modules from a Different Path
11.6. Adding Modules to Python Path
Exercise 11.1
Exercise 11.2
Chapter 12: Creating GUI in Python
12.1. Creating a Basic Window
12.2. Working with Widgets
12.2.1. Adding a Button
12.2.2. Adding a Text Field
12.2.3. Adding a Message Box
12.2.4. Adding Multiple Widgets
12.3. Creating a Layout
Exercise 12.1
Exercise 12.2
Chapter 13: Useful Python Libraries for Data Science
13.1. NumPy Library for Numerical Computing
13.1.1. Creating NumPy Arrays
13.1.2. Reshaping NumPy Arrays
13.1.3. Array Indexing and Slicing
13.1.4. NumPy for Arithmetic Operations
13.1.5. NumPy for Linear Algebra Operations
13.2. Pandas Library for Data Analysis
13.2.1. Reading Data into Pandas Dataframe
13.2.2. Filtering Rows
13.2.3. Filtering Columns
13.2.4. Sorting Dataframes
13.3. Matplotlib for Data Visualization
13.3.1. Line Plots
13.3.2. Titles Labels and Legends
13.3.3. Scatter Plots
13.3.4. Bar Plots
13.3.5. Pie Charts
Exercise 13.1
Exercise 13.2
Project 1: A Simple GUI-Based Calculator in Python
Importing the Required Libraries
Creating Main Window
Adding Widgets and Logic
Project 2: Alarm Clock with Python
Importing the Required Libraries
Creating Main Window
Adding Widgets and Logic
Project 3: Hangman Game in Python
Importing the Required Libraries
Creating Main Window
Adding Widgets and Logic
From the Same Publisher
Exercise Solutions
Exercise 2.1
Exercise 2.2
Exercise 3.1
Exercise 3.2
Exercise 4.1
Exercise 4.2
Exercise 5.1
Exercise 5.2
Exercise 6.1
Exercise 6.2
Exercise 7.1
Exercise 7.2
Exercise 8.1
Exercise 8.2
Exercise 9.1
Exercise 9.2
Exercise 10.1
Exercise 10.2
Exercise 11.1
Exercise 11.2
Exercise 12.1
Exercise 12.2
Exercise 13.1
Exercise 13.2
Preface
If you are reading these lines, you are probably one of those
people who are either absolute beginners to programming or
are familiar with some programming language other than
Python. If you fall in one of these two categories, you have
made an excellent decision on purchasing this book.
In this book, you will learn all these concepts. So, buckle up
for a journey that may give you your career break!
§ Book Approach
The book follows a very simple approach. It is divided into 13
chapters, followed by three simple projects. The first 7
chapters of this book explain the environment set, software
installation, and the core Python programming concepts
such as Python syntax, data types and variables, conditional
and decision statements, functions and methods, exception
handling, and object-oriented programming. The last 6
chapters of the book are geared toward the explanation of
some of the most useful Python libraries and utilities.
1. Desktop Development
Python is widely used for developing desktop-based
applications. Python contains a variety of libraries, such
as PyQt, PyGUI, Kivy, and WxPython, that can be used to
develop beautiful GUI-based desktop applications.
2. Web Development
A programming language is of no use if you cannot
develop web applications with it. A python developer has
the luxury of gaining access to various libraries like
HTTPS, FTP, and SSL. Furthermore, various development
frameworks such as Django and flask exist, which you can
use to quickly develop a basic platform for your web
applications.
1. Atom
Developed by Github, Atom is an extremely lightweight
IDE that supports development in multiple languages,
including Python. Atom supports syntax highlighting,
IntelliSense, and easy installation of various Python
packages. Atom is open source and free of cost.
3. PyCharm
PyCharm, as the name suggests, helps you develop
Python applications like a charm. Developed by JetBrains,
PyCharm comes with some of the most premium features
for Python development. Version control system,
IntelliSense, code refactoring, code debugging and
inspection, error-highlighting, and fixing are some of the
most common features of PyCharm. PyCharm’s trial
version is free for one month. You have to buy the
premium version after that.
4. Spyder
Spyder is an open-source IDE for scientific computing
and can also be used for Python development. Like all the
other advanced Python editors, Spyder supports static
and dynamic debugging, syntax highlighting, error
highlighting, and version control. The easiest way to get
up and running with Spyder is by installing Anaconda
distribution. Anaconda is a popular distribution for data
science and machine learning.
5. Jupyter Notebook
The official website of the Jupyter Notebook defines
Jupyter as “an open-source web application that allows
you to create and share documents that contain live
code, equations, visualizations, and narrative text.”
Jupyter notebook is an excellent tool for Python
development if you are new to Python. With Jupyter
notebook, you can write and execute your Python
programs in small chunks using Jupyter cells. Jupyter can
also be downloaded as a part of Anaconda distribution.
$ cd / tmp
$ curl –o https://repo.anaconda.com.archive/Anaconda3-5.2.0-
Linux-x86_64.sh
$ sha256sum Anaconda3-5.2.0-Linux-x86_64.sh
09f53738b0cd3bb96f5b1bac488e5528df9906be2480fe61df40e0e0d19e3d48
Anaconda3-5.2.0-Linux-x86_64.sh
$ bash Anaconda3-5.2.0-Linux-x86_64.sh
The command line will produce the following output. You will
be asked to review the license agreement. Keep on pressing
Enter until you reach the end.
Output
Output
[/home/tola/anaconda3] >>>
At this point, you will also have the option to download the
Visual Studio Code. Type yes or no to install or decline,
respectively.
$ source `/.bashrc
$ conda list
https://colab.research.google.com/
Next, click on File -> New notebook, as shown in the
following screenshot.
Next, to run your code using GPU, from the top menu, select
Runtime -> Change runtime type, as shown in the following
screenshot:
You should see the following window. Here, from the
dropdown list, select GPU and click the Save button.
To make sure you are running the latest version of
TensorFlow, execute the following script in the Google Colab
notebook cell. The following script will update your
TensorFlow version.
1. import tensorflow as tf
2. print(tf.__version__)
With Google Cloud, you can import the datasets from your
Google drive. Execute the following script. And click on the
link that appears, as shown below:
You will be prompted to allow Google Colab to access your
Google drive. Click Allow button as shown below:
You will see a link appear, as shown in the following image
(The link has been blinded here).
Copy the link and paste it in the empty field in the Google
Colab cell, as shown below:
This way, you can import datasets from your Google drive to
your Google Colab environment.
The above script prints a string value in the output using the
print() method. The print() method is used to print on the
console any string passed to it. If you see the following
output, you have successfully run your first Python program.
Output:
§ Keywords
Every programming language has a specific set of words that
perform specific functions and cannot be used as a variable
or identifier. Python has the following set of keywords:
For instance, the keyword class is used to create a new class
in Python. (We will see classes in detail in a later chapter.)
Furthermore, the if keyword creates an if condition. If you try
to use any of these keywords as variables, you will see errors.
§ Python Statements
Statements in Python are the smallest units of executable
code. When you assign a value to an identifier, you basically
write a statement. For example, age = 10 is a Python
statement. When Python executes this statement, it assigns a
value of 10 to the age identifier.
age =10
print(age)
print(message)
Output:
print(message)
§ Indentation
Indentation is one of those features that distinguish Python
from other advanced programming languages, such as C++,
Java, and C#. In the other programming languages, normally,
braces ({) are used to define a block of code.
age =8
if age <10:
print("Age is less than 10")
print("You do not qualify")
else:
print("Age is greater than or equal to 10")
print("You do qualify")
Output:
§ Comments
Comments are used to add notes to a program. Comments
do not execute, and you don’t have to declare them in the
form of statements. Comments are used to explain the code
so that if you take a look at the code after a long time, you
understand what you did.
#This is comment 1
#This is comment 2
#This is comment 3
Enough of the theory! From the next chapter, you will study
what are Python Variables and Data Types and how to
declare and use variables of different types in Python.
Python Variables and Data Types
In this chapter, you will study Python variables, what are the
different data types that you can work with within Python.
What are the different functions that you can perform on
different data types? So let’s begin without any further ado.
Script 1:
Script 2:
print(type(Name))
print(type(Age))
print(type(Weight))
print(type(Married))
Output:
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
Script 3:
print(Name)
print(Weight)
print(Married)
The output shows that all three variables, i.e., Name, Weight,
and Married contain a Boolean True as their values.
Output:
True
True
True
Script 4:
int_num=25
print(type(int_num))
Output:
<class 'int'>
You can check all the methods and attributes associated with
an object using the dir()method, as shown below. You will
study methods and attributes in detail in a later chapter. For
now, just remember that methods perform some functionality
while attributes store some data related to an object.
Script 5:
dir(int_num)
Output:
['__abs__',
'__add__',
'__and__',
'__bool__',
'__ceil__',
'__class__',
'__delattr__',
'__dir__',
'__divmod__',
'__doc__',
'__eq__',
'__float__',
'__floor__',
'__floordiv__',
'__format__',
'__ge__',
'__getattribute__',
'__getnewargs__',
'__gt__',
'__hash__',
'__index__',
'__init__',
'__init_subclass__',
'__int__',
'__invert__',
'__le__',
'__lshift__',
'__lt__',
'__mod__',
'__mul__',
'__ne__',
'__neg__',
'__new__',
'__or__',
'__pos__',
'__pow__',
'__radd__',
'__rand__',
'__rdivmod__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rfloordiv__',
'__rlshift__',
'__rmod__',
'__rmul__',
'__ror__',
'__round__',
'__rpow__',
'__rrshift__',
'__rshift__',
'__rsub__',
'__rtruediv__',
'__rxor__',
'__setattr__',
'__sizeof__',
'__str__',
'__sub__',
'__subclasshook__',
'__truediv__',
'__trunc__',
'__xor__',
'as_integer_ratio',
'bit_length',
'conjugate',
'denominator',
'from_bytes',
'imag',
'numerator',
'real',
'to_bytes']
§ Floats
To create a floating type variable, you just have to declare a
number with decimals, as shown below:
Script 6:
flt_num=2.6554
print(type(flt_num))
Output:
<class 'float'>
You can also create a floating variable using the “e” value to
define exponents.
Script 7:
flt_num=2.6554e3
print(flt_num)
print(type(flt_num))
Output:
2655.4
<class 'float'>
§ Complex Numbers
Complex numbers are numbers that consist of a real number
and an imaginary part. You can also create variables that
store complex numbers in Python, as shown in the following
script:
Script 8:
cmp_num=-.785+7J
print(type(cmp_num))
Output:
<class 'complex'>
§ Binary Numbers
Binary numbers store data in the form of 1s and 0s. You can
define binary numbers in python by prefixing “0b” before a
binary number. The binary numbers are converted into
integers when you try to print them or check their type. Look
at the following script for reference.
Script 9:
bin_num=0b11010000
print(bin_num)
print(type(bin_num))
Output:
208
<class 'int'>
2.2.2. Strings
Script 10:
Output:
Script 11:
Output:
Script 12:
print(str_mul)
Output:
Script 13:
Output:
Script 14:
Output:
§ String Concatenation
String concatenation refers to joining two strings.
Script 15:
Since the second character in the string is “e,” you can see
the character “e” printed in the console output.
Output:
'e'
print(len(my_string))
Output:
29
Let’s now see how you can add two strings. To do so, you can
use the addition operator (+). The following script
concatenates two strings, displays the concatenated string on
the console, and then displays the length of the concatenated
string.
Script 17:
Output:
Script 18:
car ="Honda"
isHonda=False
if car =="Honda":
isHonda=True
else:
isHonda=False
print(isHonda)
Output:
True
2.2.4. Lists
§ Creating Lists
To create a list, you have to add items inside a square
bracket. The items should be separated by a comma. The
following script creates a list of four strings containing color
names.
Script 19:
colors =["Red","Green","Blue","Orange"]
print(colors)
print(type(colors))
Output:
mixed_list=[20,"Male","USA",True]
print(mixed_list)
Output:
Script 21:
colors =["Red","Green","Blue","Orange"]
print(colors[1])
Output:
Green
You can also iterate through all the list items using a for loop.
You will see for loops in chapter 4. For now, just keep in mind
that you can also access sequentially iterate through list
items.
Script 22:
for col in colors:
print(col)
Output:
Red
Green
Blue
Orange
Script 23:
print(len(colors))
Output:
Script 24:
colors =["Red","Green","Blue","Orange"]
colors.append("Black")
print(colors)
Output:
['Red', 'Green', 'Blue', 'Orange', 'Black']
§ Updating a List
To update a list, you can simply access the list index for the
item to be updated and assign a new item to that list index. In
the following script, the second item in the colors list is
replaced by the color “Yellow.”
Script 25:
colors =["Red","Green","Blue","Orange"]
colors[1]="Yellow"
print(colors)
Output:
Script 26:
colors[4]="Yellow"
print(colors)
Output:
§ Deleting a List Item
To delete a list item, you have two options. You can either
pass the item to the remove() function, as shown in the
following script:
Script 27:
colors =["Red","Green","Blue","Orange"]
colors.remove("Green")
print(colors)
Output:
The other option is to pass the list index to the pop() method
of the list, as shown below:
Script 28:
colors =["Red","Green","Blue","Orange"]
colors.pop(2)
print(colors)
2.2.5. Tuples
§ Creating a Tuple
To create a tuple, you need to add items inside the round
bracket or parenthesis. Like lists, the items in a tuple are
separated by commas. The following script creates a tuple
with 4 items.
Script 29:
my_tuple=("James",25,"Male",True)
print(my_tuple)
print(type(my_tuple))
Output:
Script 30:
print(my_tuple[1])
Output:
25
Script 31:
print(my_tuple[-1])
Output:
True
Finally, you can also iterate through all the tuple items using a
for loop, as shown in the following script:
Script 32:
Output:
James
25
Male
True
§ Immutability
I said earlier that tuples are immutable and cannot be
modified. Let’s prove it. The following script tries to update
the value of the second item of the my_tuple tuple.
Script 33:
my_tuple=("James",25,"Male",True)
my_tuple[1]=30
Output:
You can try to add and remove items from a tuple, and you
will see a similar exception.
2.2.6. Dictionaries
§ Creating a Dictionary
The following script creates a dictionary country_capitals that
stores country names as keys and the corresponding country
capitals as values. The script then prints the country_capital
dictionary along with its type.
Script 34:
country_capitals={"England":"London",
"France":"Paris",
"Japan":"Tokyo",
"China":"Beijing"}
print(country_capitals)
print(type(country_capitals))
Output:
Script 35:
country_capitals[0]
Output:
A dictionary item is accessed via its key. For instance, to
access the value for the item with the key Japan, you need to
pass Japan as the value inside the square brackets, as shown
below:
Script 36:
print(country_capitals["Japan"])
Output:
Tokyo
Script 37:
fork,vincountry_capitals.items():
print(k+" ->"+v)
Output:
England ->London
France ->Paris
Japan ->Tokyo
China ->Beijing
To iterate through all the dictionary keys, you can use the
keys() method, as shown in the following script.
Script 38:
for kincountry_capitals.keys():
print(k)
Output:
England
France
Japan
China
Script 39:
for v incountry_capitals.values():
print(v)
Output:
London
Paris
Tokyo
Beijing
Script 40:
country_capitals={"England":"London",
"France":"Paris",
"Japan":"Tokyo",
"China":"Beijing"}
country_capitals["Greece"]="Athens"
print(country_capitals)
Output:
Script 41:
country_capitals={"England":"London",
"France":"Paris",
"Japan":"Tokyo",
"China":"Beijing"}
country_capitals["Japan"]="XYZ"
print(country_capitals)
Output:
Script 42:
country_capitals={"England":"London",
"France":"Paris",
"Japan":"Tokyo",
"China":"Beijing"}
delcountry_capitals["France"]
print(country_capitals)
Output:
Script 43:
country_capitals={"England":"London",
"France":"Paris",
"Japan":"Tokyo",
"China":"Beijing"}
country_capitals.clear()
print(country_capitals)
Output:
{}
Exercise 2.1
Question 1:
Question 2:
Question 3:
colors ={"color1":"red",
"color2":"blue",
"color1":"green"}
print(colors["color1"])
A. Red
B. Blue
C. Green
D. None of the Above
Exercise 2.2
Create a dictionary that contains days of a week(starting
from Monday) as values. The keys should start from 1 with an
increment of 1. Display the 3rd week of the day using its key.
Use a loop to display all the key-value pairs (see the section
on accessing dictionary items for reference).
Python Operators
Script 1:
X =10
Y =5
result = X + Y
print(result)
Output:
15
Script 2:
X =10
Y =5
result = X - Y
print(result)
Output:
Script 3:
X =10
Y =5
result = X * Y
print(result)
Output:
50
Script 4:
X =10
Y =5
result = X / Y
print(result)
Output:
2.0
Script 5:
X =10
Y =7
result = X % Y
print(result)
Output:
3
3.2.6. Exponent Operator
Script 6:
X =2
Y =5
result = X ** Y
print(result)
Output:
32
Script 7:
X =2
Y =5
result = X ** Y
print(result)
Output:
False
Script 8:
X =10
Y =5
X != Y
Output:
True
Script 9:
X =10
Y =5
X > Y
Output:
True
Script 10:
X =10
Y =5
X < Y
Output:
False
Script 11:
X =10
Y =5
X >= Y
Output:
True
Script 12:
X =10
Y =5
X <= Y
Output:
False
Script 13:
X =10
Y =5
Z = X + Y
print(Z)
Output:
15
The add and assign operator adds the values of the operands
on the left and right side of the operator and assigns the
resultant value to the operand on the left side of the add and
assign operator. Here is an example.
Script 14:
X =10
Y =5
X += Y
print(X)
Output:
15
Script 15:
X =10
Y =5
X -= Y
print(X)
Output:
Script 16:
X =10
Y =5
X *= Y
print(X)
Output:
50
3.4.5. Divide and Assign
Script 17:
X =10
Y =5
X /= Y
print(X)
Output:
2.0
Script 18:
X =10
Y =7
X %= Y
print(X)
Output:
3
Script 19:
X =2
Y =5
X **= Y
print(X)
Output:
32
Script 20:
X =True
Y =False
X and Y
Output:
False
3.5.2. OR Operator
The OR operator performs the logical OR operation between
the operands and returns true if the result of at least one of
the expressions involved in the OR operation is true. Here is
an example.
Script 21:
X =True
Y =False
X or Y
Output:
True
Script 22:
X =True
Y =False
not(X and Y)
Output:
True
Script 23:
items =[1,3,4]
print(4in items)
Output:
True
Script 24:
items =[1,3,4]
print(4notin items)
Output:
False
The is operator returns true if two objects are equal and share
the same memory locations. For instance, the following script
will return TRUE since the lists a and c are equal and point to
the same memory location.
Script 25:
a =["red","green","blue"]
b =["red","green","blue"]
c = a
a is c
Output:
True
Script 26:
a =["red","green","blue"]
b =["red","green","blue"]
c = a
a isnot c
Output:
False
Exercise 3.1
Question 1:
a =["red","green","blue"]
print("red"isin a)
A. True
B. False
C. SyntaxError
D. red is in a
Question 2:
X =100
Y =50
not(X is Y)
A. True
B. False
C. SyntaxError
D. None of the Above
Question 3:
Exercise 3.2
Suppose you have the following the following three Python
variables:
a =400
b =350
c = b
d =[100,200,300,400]
ifTrue:
print("The condition is true")
Output:
Script 2:
x =50
y =30
if x > y:
print("x is greater than y")
Output:
x is greater than y
Script 3:
if x < y:
print("x is less than y")
If you want to execute a particular piece of code, in case the
if condition returns false, you can use the else block, as
shown in the following example.
Script 4:
if x < y:
print("x is less than y")
else:
print("x is greater than y")
Output:
x is greater than y
Script 5:
x =50
y =30
z =20
if x < y:
print("x is smaller than y")
elif y < z:
print("y is smaller than z")
elif x < z:
print("x is smaller than z")
else:
print("z is the smallest integer")
Output:
Script 6:
car ="Honda"
print(isHonda)
Output:
True
Script 7:
x =50
y =30
z =20
if x > y:
print("x is greater than y")
if x > z:
print("x is greater than z")
else:
print("x is not greater than z")
elif y < z:
print("y is smaller than z")
elif x < z:
print("x is smaller than z")
else:
print("z is the smallest integer")
x is greater than y
x is greater than z
foriinrange(10):
print("hello")
Output:
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
hello
Script 9:
foriinrange(10):
print(i)
Output:
0
1
2
3
4
5
6
7
8
9
Let’s now do something fancy. Let’s try to print the table of
integer 6 using a for loop. Here is the script which does that.
Notice, here, since we do not want to start from 0, we
increment i by 1 while printing the product of 6 and the value
stored by the variable i.
Script 10:
foriinrange(10):
print("6 x", i+1,"= ",6*(i+1))
Output:
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60
If you do not want to use the item that is being iterated and
you are only concerned about the number of iterations, you
can skip the temporary iteration variable and replace it with
an underscore. The following for loop executes 10 times.
However, there is no temporary variable that holds the value
of the item being iterated.
Script 11:
for _inrange(10):
print("hello world")
Output:
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
Script 12:
days =
["sunday","monday","tuesday","wednesday","thursday","friday","s
aturday"]
Output:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
saturday
Script 13:
j =0
while j<10:
print("hello world")
j = j +1
Output:
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
As you did for the for loop, you can also use a while loop to
print the table of an integer. Look at the following script:
Script 14:
j =0
while j<10:
print("6 x", j+1,"= ",6*(j+1))
j = j +1
Output:
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60
Script 15:
foriinrange(5):
for j inrange(5):
print(i,"-",j)
Output:
0 - 0
0 - 1
0 - 2
0 - 3
0 - 4
1 - 0
1 - 1
1 - 2
1 - 3
1 - 4
2 - 0
2 - 1
2 - 2
2 - 3
2 - 4
3 - 0
3 - 1
3 - 2
3 - 3
3 - 4
4 - 0
4 - 1
4 - 2
4 - 3
4 - 4
Script 16:
In the output below, you can see all even integers from 0 to
20.
Output:
0
2
4
6
8
10
12
14
16
18
20
Script 17:
Output:
1
3
5
7
9
11
13
15
17
19
Script 18:
if num%2!=0:
print(num)
if num >10:
break
Output:
1
3
5
7
9
11
Script 19:
cars =["Honda","Toyota","Ford","BMW","KIA","Renault",
"Peugeot"]
short_cars=[]
for car in cars:
iflen(car)<5:
short_cars.append(car)
print(short_cars)
Output:
Script 20:
cars =["Honda","Toyota","Ford","BMW","KIA","Renault",
"Peugeot"]
print(short_cars2)
Output:
Exercise 4.1
Question 1:
Question 2:
Question 3:
Exercise 4.2
Write a program that prints the prime numbers between 1
and 100.
Functions in Python
In this chapter, you will study what Python functions are, how
to define and call functions, how to pass and return values
from a function, and what are some of the most common uses
of functions.
Functions can save you not only lots of lines of code but also
foster usability. A function defined in one application can be
used in another application with or without modification.
Finally, functions are an integral part of object-oriented
programming.
5.2. Defining and Calling Functions
To define a function, you can use the def keyword, followed
by the function name and a pair of parentheses. For instance,
the following script defines a function named my_function().
The function prints a simple string on the console.
Script 1:
Script 2:
Output:
Script 3:
defprint_eight():
foriinrange(1,11):
print("8 x ",str(i)," = ",str(8*i))
Script 4:
print_eight()
Output:
8 x 1 = 8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40
8 x 6 = 48
8 x 7 = 56
8 x 8 = 64
8 x 9 = 72
8 x 10 = 80
Script 5:
defshow_custom_message(my_message):
for _inrange(5):
print(my_message)
Script 6:
In the output, you can see the string that you passed to the
show_custom_message()five times.
Output:
Script 7:
defshow_custom_message(my_message, count):
for _inrange(count):
print(my_message)
If you run the following script, you will see a string message
printed 10 times on the console. Without functions, you will
have to write 10 print statements.
Script 8:
Output:
Script 9:
defadd_numbers(a,b,c):
result = a + b + c
print(result)
Script 10:
add_numbers(10,12,35)
Output:
57
Script 11:
defdisplay_table(num):
foriinrange(1,11):
print(str(num)," x ",str(i)," = ",str(num*i))
Script 12:
display_table(7)
Output:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
Script 13:
defadd_numbers(a,b,c):
result = a + b + c
print(result)
result =add_numbers(10,12,35)
Output:
57
Script 14:
print(result)
The output shows that the result contains null. This is because
the add_numbers() function did not return anything.
Output:
None
To make a function return values, you need to use the return
keyword. The values to be returned are mentioned after the
return keyword. For instance, in the following script, the
add_numbers() method returns the value stored in the results
variable to the function call.
Script 15:
defadd_numbers(a,b,c):
result = a + b + c
return result # return keyword returns values
result =add_numbers(10,12,35)
Now, if you print the result variable, it will contain the value
returned by the add_numbers() function, as shown below:
Script 16:
print(result)
Output:
57
Script 17:
deftake_cubes(a,b,c):
a3 = a **3
b3 = b **3
c3 = c **3
Script 18:
x, y, z =take_cubes(2,4,6)
print(x)
print(y)
print(z)
Output:
8
64
216
The following script defines one global variable num1 and one
local variable num2. The num1 variable is accessible inside the
add_ten() function. Inside the function, the num1 and num2
variables are added.
Script 19:
#global variable
num1 =10
defadd_ten():
#local variable
num2 =5
result = num2 + num1
print(result)
If you run the above script, you will see that no error occurs
because the global variable num1 is accessible everywhere,
including inside the add_ten() function.
Script 20:
add_ten()
Output:
15
Script 21:
#global variable
num1 =10
defadd_ten():
#local variable
num2 =5
result = num2 + num1
print(result)
print(num1)
print(num2)
In the output, you will see an error that says that the num2
variable is not defined. This is because the num2 variable is a
local variable inside the add_ten() function, and the Python
interpreter could not find it outside the add_ten() function.
Output:
Script 22:
defglobal_func():
print("This is a global function")
deflocal_func():
print("This is a local function")
Script 23:
Output:
Script 24:
square =lambda x: x * x
Script 25:
print(square (2))
Output:
Script 26:
defadd_numbers(a,b,c):
result = a + b + c
return result
Script 27:
add_numbers2 =lambda a, b, c: a + b + c
Script 28:
print(add_numbers2(10,12,35))
Output:
57
Script 29:
Output:
(27, 125)
Script 30:
defmy_func(num):
if num ==0:
return
else:
my_func(num -1)
print("The function is called recursively for",str(num),"times")
my_func(7)
Output:
Script 31:
deftake_fact(num):
if num ==1:
return1
else:
fact = num *take_fact(num -1)
return fact
take_fact(8)
Output:
40320
Script 32:
defmy_function():
print("This is my first function")
Script 33:
my_function
Output:
<function __main__.my_function()>
Script 34:
defglobal_func():
print("This is a global function")
deflocal_func():
print("This is a local function")
Script 35:
my_func=global_func()
Output:
This is a global function
Script 36:
print(my_func)
Output:
You can call a function using its variable name, just like the
lambda function. For instance, to call the local_func() stored
in the my_func variable, you need to add parenthesis in front
of the my_func variable name. Look at the following script for
reference.
Script 37:
my_func()
Output:
Script 38:
def function1(my_func):
print("This is from the original function")
Script 39:
Output:
Script 40:
defdecorator_function(orignal_function):
defextended_function():
print("This line executes before the original function")
orignal_function()
returnextended_function
Script 41:
defmy_original_function():
print("This is the orignal function that is extended by the
extended function")
Script 42:
extended_function=decorator_function(my_original_function)
Script 43:
extended_function()
Output:
Script 44:
@decorator_function
def my_original_function2():
print("This function is extended using @ symbol with decorator")
Script 45:
my_original_function2()
The following script creates an iterator for the colors list with
four items and iterates through all four items.
Script 46:
colors =["Red","Green","Blue","Orange"]
my_iterator=iter(colors)
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
Output:
Red
Green
Blue
Orange
Once you iterate through all the items in an iterator and then
call the next() method, you will see an error, as shown below:
Script 47:
print(next(my_iterator))
Output:
5.9.2. Generators
Script 48:
defget_evens(num):
x =0
while x < num:
yield x
x = x +2
Script 49:
nums=get_evens(11)
When you call the generator function for the first time using
the __next__() function, x will have a value of 0, which will be
returned. The value of x will be updated to 2 after the first
call. The __next__() method will keep returning the next even
number until the number is less than 11 (the value passed as a
parameter to the get_evens() generator).
Script 50:
print(nums.__next__())
print(nums.__next__())
print(nums.__next__())
print(nums.__next__())
print(nums.__next__())
print(nums.__next__())
Output:
0
2
4
6
8
10
Script 51:
print(nums.__next__())
Output:
Script 52:
foriinget_evens(11):
print(i)
Output:
0
2
4
6
8
10
Exercise 5.1
Question 1:
Question 2:
Question 3:
Exercise 5.2
Write a function that calculates and prints the first N numbers
of the Fibonacci series, where N is any integer.
Script 1:
## defining a class
classNewClass:
defclass_method(self):
Script 2:
Script 3:
## defining a class
classNewClass:
defclass_method(self):
Output:
Script 5:
Output:
red
24
Script 6:
Output:
Script 7:
## defining a class
classNewClass:
Output:
Script 9:
Output:
Script 10:
classNewClass:
def__init__(self,my_color,my_id):
Output:
Purple
50
Script 12:
Output:
Pink
100
You can see that constructor makes your life much easier,
especially when you want to initialize some member
attributes at the time of object initialization.
Script 13:
classNewClass:
## class variable
num_objects=0
## constructor
def__init__(self,my_color,my_id):
## instance method
defdisplay_vars(self):
print(self.color)
print(self.id)
## class method
defshow_object_counts():
print("Number of objects:",str(NewClass.num_objects))
When you create the first object of the NewClass class, the
value of the num_objects will be incremented to 1, as shown
in the following script.
Script 14:
Output:
Purple
50
Number of objects: 1
Now, when you create another object of the NewClass class,
the value of class variable num_objects will be incremented
to 2 since it is shared between all the objects, and previously
it had a value of 1. Execute the following script to see this for
yourself.
Script 15:
Output:
Pink
100
Number of objects: 2
Script 16:
classGet_Evens:
def__iter__(self):
def __next__(self):
#save the previous iterator value
new_id= self.id
classGet_Evens:
def__iter__(self):
def __next__(self):
#save the previous iterator value
new_id= self.id
Script 17:
get_evens=Get_Evens()
get_evens_iter=iter(get_evens)
print(next(get_evens_iter))
Output:
2
You can keep calling the next() method to get the next
iterator value, as shown in the following script:
Script 18:
print(next(get_evens_iter))
print(next(get_evens_iter))
print(next(get_evens_iter))
print(next(get_evens_iter))
print(next(get_evens_iter))
Output:
4
6
8
10
12
You can also use a for loop to iterate through your custom
iterator. You just have to call the next() method on the
iterator inside the for loop. Look at the following script for
reference.
Script 19:
get_evens=Get_Evens()
get_evens_iter=iter(get_evens)
for _ inrange(10):
print(next(get_evens_iter))
Output:
2
4
6
8
10
12
14
16
18
20
Script 20:
class Parent:
defdisplay_text(self):
self.id=10
print("A function inside the parent class")
class Child(Parent):
pass
Let’s create an object of the Child class and call the display_
text() method.
Script 21:
child = Child()
child.display_text()
print(child.id)
Output:
The output shows that you were able to successfully call the
display_text() method from the Child class object, although
the display_text() method is not defined inside the Child
class. However, since the Child class inherits the Parent class,
which contains the display_text() method, you can call the
method using the Child class object.
Script 22:
class Shape:
defdisplay_shape_attr(self):
print("The shape name is ",self.shape_name)
print("The shape area is ",self.area)
Let’s create two child classes from the Shape class. The first
class that we are going to create is a Circle class that has its
attribute radius and a method that displays the value of the
radius attribute. Notice the relationship between the Circle
and Shape class is is-a, as a Circle is-a Shape.
Script 23:
class Circle(Shape):
defset_circle_attr(self, radius):
self.radius= radius
defdisplay_circle_attr(self):
print("The radius of the circle is ",self.radius)
Script 24:
class Square(Shape):
defset_square_attr(self, vertices):
self.vertices= vertices
defdisplay_square_attr(self):
print("Total number of vertices in a square ",self.vertices)
You can see that both Circle and Square classes have two
common attributes name and area. The common attributes
are implemented in the parent Shape class. The specific
attributes, i.e., radius and vertices, are implemented in Circle
and Square classes, respectively.
Output:
Script 26:
Output:
Script 27:
class Shape:
defdisplay_shape_attr(self):
print("The shape name is ",self.shape_name)
print("The shape area is ",self.area)
Script 28:
class Circle(Shape):
Now, when you create an object of the Circle class, you pass
three parameter values. The first two parameter values will
initialize the parent class attributes: name and area, while the
third parameter will initialize the child class attribute, radius.
Script 29:
Output:
6.7.4. Polymorphism
When you pass the value for the three parameters, the sum
of three parameter values will be returned. If you pass two
values, c will be assigned the value of c. If the value of the
parameter c is zero, you subtract b from a and return the
value.
Script 30:
defmy_func(a,b,c=0):
if c ==0:
return a - b
else:
return a + b + c
Script 31:
print(my_func(10,22,20))
print(my_func(15,10))
Output:
52
5
Script 32:
class Shape:
defdisplay_shape_attr(self):
print("The shape name is ",self.shape_name)
print("The shape area is ",self.area)
Script 33:
class Circle(Shape):
Script 34:
class Square(Shape):
def__init__(self, name, area, vertices):
super().__init__(name, area)
self.vertices= vertices
Script 35:
shape= Shape("Shape",500)
circle= Circle("Circle",700,400)
square = Square("Square",500,4)
shape.display_shape_attr()
print("==================================")
circle.display_shape_attr()
print("==================================")
square.display_shape_attr()
Output:
Exercise 6.1
Question 1:
Question 2:
Question 3:
Which of the following method is used to call the parent
class constructor in Python?
A. parent()
B. base()
C. super()
D. object()
Exercise 6.2
Perform the following tasks:
1. Create a Parent class Vehicle with two instance
attributes: name and price, and one instance method
show_vehicle(). The show_vehicle() method displays
the name and price attributes.
2. Initialize the Vehicle class attributes using a
constructor.
3. Create a class Car that inherits the Parent Vehicle
class. Add an attribute named tires to the Car class.
Override the show_vehicle() method of the parent
Vehicle class and display name, price, and tire
attributes.
4. Inside the Car class constructor, call the Vehicle class
constructor and pass the name and price to the
parent Vehicle class constructor.
5. Create objects of Car and Vehicle classes, and call
show_vehicle() method using both objects.
Exception Handling with Python
Script 1:
Output:
Script 2:
Script 3:
divide_numbers(20,0)
When you run the above script, an error will occur, which
says that you cannot divide a number by zero. You can see
that the error only occurs when you pass 0 as the value for
the parameter b. Otherwise, this error will never occur. This is
an example of an exception.
Output:
Script 4:
defdivide_numbers(a, b):
result = a / b
print(result_new)
Script 5:
divide_numbers(20,0)
Output:
Let’s now pass a non-zero value for the variable b, i.e., 10, as
shown in the following script.
Script 6:
divide_numbers(20,10)
When you run the above script, you will see a NameError
exception since the variable “result_new” is not defined
before it is used.
Output:
So, you can see that one python script can generate multiple
exceptions.
Script 7:
defdivide_numbers(a, b):
try:
result = a / b
print(result_new)
except:
print("an exception occurred")
Now, if you execute the following script, a division by zero
exception will occur.
Script 8:
divide_numbers(20,0)
Output:
an exception occurred
Script 9:
divide_numbers(20,10)
Output:
an exception occurred
Script 10:
defdivide_numbers(a, b):
try:
result = a / b
print(result_new)
exceptExceptionas e:
print(e)
Script 11:
divide_numbers(20,0)
Output:
division by zero
Script 12:
divide_numbers(20,10)
Output:
Script 13:
defdivide_numbers(a, b):
try:
result = a / b
print(result_new)
#catching name error exception
exceptNameError:
print("One of your variables is not initialized before usage")
#catching divide by zero exception
exceptZeroDivisionError:
print("Division of a number by zero is not possible")
Script 14:
divide_numbers(20,0)
You can see from the output below that the except block for
the ZeroDivisionError is executed, and the corresponding
statement is printed.
Output:
Similarly, if you execute the following script, you will see that
the NameError exception will occur, and the except block
that handles the NameError exception will execute.
Script 15:
divide_numbers(20,10)
Output:
Script 16:
defdivide_numbers(a, b):
try:
result = a / b
print(result)
#catching name error exception
exceptNameError:
print("One of your variable is not initialized before usage")
#catching divide by zero exception
exceptZeroDivisionError:
print("Division of a number by zero is not possible")
finally:
print("This will be called in any case")
Script 17:
divide_numbers(20,0)
In the output, you will see the output from the except block
that catches the ZeroDivisionError exception. The output also
shows that the print statement inside the finally block is also
executed.
Output:
Script 18:
divide_numbers(20,10)
Output:
2.0
this will be called in any case
Script 19:
defdivide_numbers(a, b):
try:
result = a / b
print(result)
exceptNameError:
print("One of your variable is not initialized before usage")
else:
print("The exception did not occur")
finally:
print("This will be called in any case")
For instance, if you run the following script, no exception will
occur, and therefore, the code block that follows the else
statement will execute, along with the finally block.
Script 20:
divide_numbers(20,10)
Output:
2.0
The exception did not occur this will be called in any case
Script 21:
my_list=[]
for _ inrange(4):
my_list.append("Hello world")
print(my_list)
iflen(my_list)>3:
raiseException("This list cannot contain more than 3 items")
Output:
The exception defined in the previous script was named
Exception. You can define your custom-named exception by
creating a class that inherits from the Exception class.
Script 22:
classListItemOverFlow(Exception):
"""Exception raised when more than 3 items are added in a list
Attributes:
new_list -- the list itself
error_message -- the detail of the exception
"""
Script 23:
my_list=[]
for _ inrange(4):
my_list.append("Hello world")
print(my_list)
iflen(my_list)>3:
raiseListItemOverFlow(my_list)
Output:
Script 24:
classListItemOverFlow(Exception):
"""Exception raised when more than 3 items are added in a list
Attributes:
new_list -- the list itself
error_message -- the detail of the exception
"""
Script 25:
my_list=[]
for _ inrange(4):
my_list.append("Hello world")
print(my_list)
iflen(my_list)>3:
raiseListItemOverFlow(my_list)
Output:
Exercise 7.1
Question 1:
Question 2:
Question 3:
Exercise 7.2
Create a custom exception named
EvenNumberInsertionException, which tells users that they
cannot add an even number in a list of integers. Create a list
and add some odd and even numbers to it. Raise the
EvenNumberInsertionException and tell the user the even
number added along with the error message.
Reading and Writing Data from
Files and Sockets
In this chapter, you will see how to read and write data to
different types of files. You will also study how to send and
receive data over sockets.
Mode Description
R Opens file for read-only
r+ Opens file for reading and writing
rb Only Read file in binary
rb+ Opens file to read and write in binary
w Opens file to write only. Overwrites existing files
with the same name
wb Opens file to write only in binary. Overwrites
existing files with the same name
+ Opens file for reading and writing
wb Opens file to read and write in binary. Overwrites
existing files with the same name
A Opens a file for appending content at the end of the
file
a+ Opens file for appending as well as reading content
ab Opens a file for appending content in binary
ab+ Opens a file for reading and appending content in
binary
The following script opens a simple text file for reading and
writing. The script also prints the object type returned by the
open() function. Depending upon the file, the open()
function returns an object which you can use to perform
different types of operations on the file.
Script 1:
file_handle_text=open("E:/Datasets/my_text.txt","r+")
type(file_handle_text)
Output:
_io.TextIOWrapper
In the same way, you can open word files and pdf files as
shown in scripts 2 and 3, respectively.
Script 2:
file_handle_word=open("E:/Datasets/my_text.docx","r+")
type(file_handle_word)
Output:
_io.TextIOWrapper
Script 3:
file_handle_pdf=open("E:/Datasets/my_text.pdf","r+")
type(file_handle_pdf)
Output:
_io.TextIOWrapper
You can print the complete file name along with the
pathname, the file mode, and whether the file is closed or not
using the name, mode, and closed attributes, respectively.
Script 4:
print(file_handle_pdf.name)
print(file_handle_pdf.mode)
print(file_handle_pdf.closed)
Output:
E:/Datasets/my_text.pdf
r+
False
Once you have opened a file, you must close it so that some
other application can access it. To close a file, you need to
call the closed() method.
Script 5:
file_handle_pdf.close()
print(file_handle_pdf.closed)
Output:
True
To read a text file with Python, you first have to open the file
with read permissions and then call the read() method using
the file handler object. The following script reads a file
named “my_text.txt.”
Script 6:
file_handle_text=open("E:/Datasets/my_text.txt","r+")
file_content=file_handle_text.read()
print(file_content)
The output shows that the file contains three lines of text.
You can open your text file if you want.
Output:
hello there
Welcome to Python from zero to hero
You will learn Python in this book.
Instead of reading the whole file, you can also read a file
partially. For instance, if you want to read a specific number
of characters from a text file, you need to pass the number
of characters as a parameter value to the read() function, as
shown below:
Script 7:
file_handle_text=open("E:/Datasets/my_text.txt","r+")
file_content=file_handle_text.read(20)
print(file_content)
Output:
hello there
Welcome
Finally, you can also read a file line by line using the
readline() function. The read line function is an iterator that
returns the next line of text until all the lines have been read.
Here is an example of the readline() function.
Script 8:
file_handle_text=open("E:/Datasets/my_text.txt","r+")
file_line1 =file_handle_text.readline()
file_line2 =file_handle_text.readline()
print(file_line1)
print(file_line2)
file_handle_text.close()
Output:
hello there
Script 9:
withopen("E:/Datasets/my_text.txt", mode
='r')asfile_handle_text:
file_content=file_handle_text.read()
print(file_content)
Output:
hello there
Welcome to Python from zero to hero
You will learn Python in this book.
Before creating a text file, let’s see how you can write text to
an existing file. To do so, you need to open a file with the
append mode ‘a’. Next, to write text at the end of the
existing text, you can call the write() method. The text to be
written is passed as a parameter to the write() method. Here
is an example:
Script 10:
file_handle_text=open("E:/Datasets/my_text.txt","a")
file_handle_text.write("This line is appended to the existing
file")
file_handle_text.close()
Script 11:
file_handle_text=open("E:/Datasets/my_text.txt","r+")
file_content=file_handle_text.read()
print(file_content)
Output:
hello there
Welcome to Python from zero to hero
You will learn Python in this book.This line is appended to the
existing file
Script 12:
file_handle_text=open("E:/Datasets/my_text2.txt","w")
file_handle_text.write("This line will overwrite the existing
content or will be written in a new file")
file_handle_text.close()
To read a CSV file in Python, you first need to import the csv
module. Next, you need to open the CSV file using the
open() function. Next, you need to call the reader() function
from the CSV module and pass it the file object. The reader()
method returns a list that contains items that correspond to
rows in the CSV file. You can then iterate through the list
items. Here is an example.
Script 13:
import csv
withopen("E:/Datasets/my_csvfile.csv", mode
='r')asfile_handle_csv:
file_content=csv.reader(file_handle_csv)
for row infile_content:
print(row)
Output:
To write a CSV file, you need to first create a list whose items
correspond to the columns headers of the CSV file. For
records, you need to create a list of lists where each internal
list corresponds to CSV rows and items correspond to
column values. After that, you need to open a CSV file with
write mode. The file object is then passed to the write()
method from the CSV module. The write() method returns
the writer object. Finally, to write the header, pass the
header list to the writerow() function. Similarly, to write
rows, pass the records list to the writerows() method, as
shown in the following script.
Script 14:
import csv
headers =['Name','Age','Gender','City']
records =[['nick',29,'male','lyon'],
['joseph',30,'male','manchester'],
['zita',35,'female','berlin']]
Let’s read your newly created CSV file to see if records have
been correctly added to the file.
Script 15:
import csv
withopen("E:/Datasets/my_csvfile2.csv", mode
='r')asfile_handle_csv:
file_content=csv.reader(file_handle_csv)
for row infile_content:
print(row)
You can see the file contents of your newly created CSV file.
Output:
To read a PDF file, you need to first open a file with the read
binary mode. Next, you need to pass the file object to the
PdfFileReader() method from the PyPDF2 module. The
object returned by the PdfFileReader()method can then be
used to read PDF files.
Script 16:
import PyPDF2
file_handle_pdf=open("E:/Datasets/my_text.pdf","rb")
pdf_object= PyPDF2.PdfFileReader(file_handle_pdf)
print(pdf_object.numPages)
Output:
To print the text, you first need to get the page using the
getPage() method. Next, using the page object, you can call
the extractText() method to get the page text. The following
script prints the text of the first page in your PDF document.
Script 17:
page_one=pdf_object.getPage(0)
print(page_one.extractText())
To print the text from all the pages, you can simply iterate
through all the pages, grab the current page using the
getPage method, and print its text using the extractText()
function. The following script prints text from all the pages in
your PDF document.
Script 18:
foriinrange(pdf_object.numPages):
new_page=pdf_object.getPage(i)
print("===================")
print(new_page.extractText())
The next step is to open the file that you want to write using
the open() function. Finally, the file object returned by the
open() function is passed to the write() method of the PDF
writer object.
Script 19:
pdf_writer= PyPDF2.PdfFileWriter()
Next, you need to call the listen() method using the Socket
class object. The listen method specifies the number of
connections to the queue. In the following script, five
connections will be queued at a time, after which the new
connections will not be accepted by the socket.
To send data back to the client, you need to call the send()
method on the connection and pass the data that you want
to send to the client as the method parameter.
Script 20:
import socket
new_socket=socket.socket()
print("Socket successfully created")
port =5555
new_socket.bind(('', port))
print("socket connected to port %s"%(port))
new_socket.listen(5)
print("Server is listening to request")
whileTrue:
conn,clt_address=new_socket.accept()
print('Received connection request from',clt_address)
conn.close()
When you run the above script, the server will start listening
at port 5555.
Output:
Script 21:
client_socket=socket.socket()
port =5555
client_socket.connect(('127.0.0.1', port))
print(client_socket.recv(2048))
client_socket.close()
When you run the above script, you will receive a message
from the server, as shown below.
Output:
On the server side, you will see the IP address and port of
the client application with a message that a connection was
successfully received.
Exercise 8.1
Question 1:
Question 2:
Question 3:
What are the values of the parameters that you need to pass
to the connect() method of the socket() to connect to a
remote server application through a socket?
A. Server name and server ip name
B. Server ip address and port number
C. Server ip address, port number, and application name
D. Both A and C
Exercise 8.2
Create a new text file. Write three lines of text in the text file.
Read all the text from the file line by line using the with
operator.
Regular Expressions in Python
import re
pattern ='^p.*y$'
string_list=["pathology","biology","geography","psychology",
"mathematics"]
forstrinstring_list:
result =re.match(pattern,str)
if result:
print(str)
Output:
pathology
psychology
Script 2:
import re
pattern ='.*[ab].*'
string_list["pathology","nic","jos","biology","geography",
"psychology","mathematics"]
forstrinstring_list:
result =re.match(pattern,str)
if result:
print(str)
Output:
pathology
biology
geography
mathematics
Script 3:
import re
pattern ='.....'
string_list=["pathology","nic","jos","biology","geography",
"psychology","mathematics"]
forstrinstring_list:
result =re.match(pattern,str)
if result:
print(str)
Output:
pathology
biology
geography
psychology
mathematics
Script 4:
import re
pattern ='^p.*y$'
string_list=["pathology","biology","geography","psychology",
"mathematics"]
forstrinstring_list:
result =re.match(pattern,str)
if result:
print(str)
Output:
pathology
psychology
Script 5:
import re
pattern ='.*og+y'
string_list=["pathology","biology","geography","psychology",
"mathematics"]
forstrinstring_list:
result =re.match(pattern,str)
if result:
print(str)
Output:
pathology
biology
psychology
Script 6:
import re
pattern ='.*at?h'
string_list=["pathology","biology","geography","psychology",
"mathematics"]
forstrinstring_list:
result =re.match(pattern,str)
if result:
print(str)
Output:
pathology
mathematics
9.2.5. Alteration (|) and Grouping ()
Script 7:
import re
pattern ='(^p)|(.*s$)'
string_list=["pathology","biology","geography","psychology",
"mathematics"]
forstrinstring_list:
result =re.match(pattern,str)
if result:
print(str)
Output:
pathology
psychology
mathematics
9.2.6. Backslash
Script 8:
import re
pattern ='25\.+.*'
string_list=["pathology","biology","25.245","""geography",
"psychology","mathematics"]
forstrinstring_list:
result =re.match(pattern,str)
if result:
print(str)
Output:
25.245
Script 9:
import re
pattern ='\Apat'
string_list=["pathology","biology","25.245","""geography",
"psychology","mathematics"]
forstrinstring_list:
result =re.match(pattern,str)
if result:
print(str)
Output:
pathology
The \d+ operator searches for all the digits within a string.
Here is an example.
Script 10:
import re
pattern ='\d+'
str="This is 10, he is 20"
result =re.findall(pattern,str)
print(result)
Output:
['10', '20']
Script 11:
import re
pattern ='\D+'
str="This is 10, he is 20"
result =re.findall(pattern,str)
print(result)
Output:
Script 12:
import re
pattern ='\w+'
str="This is % 10 # he is 20"
result =re.findall(pattern,str)
print(result)
Output:
Script 13:
import re
pattern ='\w+'
str="This is % 10 # he is 20"
result =re.findall(pattern,str)
print(result)
Output:
[' ', ' % ', ' # ', ' ', ' ']
Script 14:
import re
pattern ='\d+'
str="This is 10 he is 20 and the gate is 80"
result =re.findall(pattern,str)
print(result)
Output:
Script 15:
import re
pattern ='\d+'
str="This is 10 he is 20 and the gate is 80."
result =re.split(pattern,str)
print(result)
Output:
['This is ', ' he is ', ' and the gate is ', '.']
import re
pattern ='\d+'
str="This is 10 he is 20 and the gate is 80."
new_str=re.sub(pattern,'XX',str)
print(new_str)
Output:
Script 17:
import re
pattern ='\d+'
str="This is 10 he is 20 and the gate is 80."
new_str=re.subn(pattern,'XX',str)
print(new_str)
Output:
Script 18:
import re
pattern ='\d+'
str="This is 10 he is 20 and the gate is 80."
result =re.search(pattern,str)
print(result)
Output:
Exercise 9.1
Question 1:
Question 2:
Question 3:
Exercise 9.2
Write a regular expression that returns all words from a list
that contain a carrot (^) symbol or a dollar sign ($), or a plus
(+) sign.
Some Useful Python Modules
In this chapter, you will see how to use the following Python
modules:
1. Debugger Module
2. Collections Module
3. DateTime Module
4. Math Module
5. Random Module
6. Time and Timeit Modules
For instance, in the following script, the total price for the
first item, i.e., laptop in the total_price dictionary, is 5, as can
be seen from the first item in the quantities list.
Next, you execute a loop that displays item names and the
average prices for all the items. The average price of an item
in the total_price dictionary can be calculated by dividing the
dictionary value for the item by the corresponding value in
the quantity list.
For instance, the average price of the first item, i.e., laptop,
can be calculated by dividing 100 by the first item in the
quantity list, i.e., 5.
Script 1:
total_price={'laptop':100,'cell phone':75,
'keyboard':40,'mic':40,'mouse':15}
quantities =[5,5,5,10,5]
average_price=(price/quantity)
print("The average price for a", item,"is",str(average_price))
Output:
Script 2:
total_price={'laptop':100,'cell
phone':75,'keyboard':40,'mic':40,'mouse':15}
quantities =[5,5,0,10,5]
average_price=(price/quantity)
print("The average price for a", item,"is",str(average_price))
Output:
Imagine a scenario where you are reading data from a list of
thousand records. In this case, it is difficult to find the item for
which the quantity is 0 by simply looking at the list. Another
option is to print the item before printing its average price, as
shown in the following script.
Script 3:
total_price={'laptop':100,'cell
phone':75,'keyboard':40,'mic':40,'mouse':15}
quantities =[5,5,0,10,5]
print(item)
average_price=(price/quantity)
print("The average price for a", item,"is",str(average_price))
From the output, you can see that the error occurs while
printing the average price for the item keyboard.
Output:
However, if you have thousands of records, you will have to
execute thousands of print statements for one variable. If you
also want to print the value of the quantity variable, you will
have to write another print statement or concatenate the
value with the value of the item. Hence, a lot of computations
will take place.
Script 4:
importpdb
total_price={'laptop':100,'cell
phone':75,'keyboard':40,'mic':40,'mouse':15}
quantities =[5,5,0,10,5]
try:
average_price=(price/quantity)
print("The average price for a", item,"is",str(average_price))
except:
pdb.set_trace()
Type the name of a variable in the text box to see its value.
For instance, if you type an item, you will see “keyboard” in
the output, as shown below.
Output:
Similarly, you can type price and quantity in the text field to
see their values. See how simple it is? You don’t have to
execute any print statement; your code will remain clean, and
yet you will be able to check the values of all the variables in
your code.
Script 5:
Script 6:
cars =["Honda","Honda","Honda","Honda","Ford","Ford",
"BMW","BMW","BMW","BMW","BMW","BMW","BMW"]
print(Counter(cars))
In the output below, you can see the count of each item in the
cars list. For instance, you can see that the item BMW exists
for seven times in the cars list and so on.
Output:
cars_count= Counter(cars)
print(cars_count["Honda"])
Output:
Script 8:
str_count= Counter("adklasjdkasdlaj")
print(str_count)
Output:
Script 9:
from collections importdefaultdict
normal_dic={'BMW':7,'Honda':4,'Ford':2}
print(normal_dic["BMW"])
Output:
Script 10:
print(normal_dic["Toyota"])
Since the item with the key Toyota doesn’t exist in the
normal_ dic dictionary, you will see the following exception.
Output:
Script 11:
def_dic=defaultdict(lambda:"Not Available")
def_dic["BMW"]=7
print(def_dic["BMW"])
print(def_dic["Toyota"])
Output:
7
Not Available
Script 12:
normal_tuple=("BMW",10,"Black")
print(normal_tuple[2])
Output:
Black
Script 13:
car_tuple=namedtuple('Car',['Name','Model','Color'])
cars =car_tuple(Name ="BMW", Model=10, Color ="Black")
Now, you can assess the items in the named tuple object cars
using the index names. For instance, to access the third item,
you can either use the integer index 2 or the named index
Color, as shown in the following script.
Script 14:
print(cars[2])
print(cars.Color)
Output:
Black
Black
Script 15:
import
datetime datetime_now=datetime.datetime.now()
print(datetime_now)
print(datetime_now.ctime())
Output:
2021-04-11 10:37:45.726437
Sun Apr 11 10:37:45 2021
To see all the attributes of the datetime class, you can pass
the datetime object that was created in the last script to the
dir() method, as shown below.
Script 16:
print(dir(datetime_now))
Output:
['__add__',
'__class__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__ne__',
'__new__',
'__radd__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rsub__',
'__setattr__',
'__sizeof__',
'__str__',
'__sub__',
'__subclasshook__',
'astimezone',
'combine',
'ctime',
'date',
'day',
'dst',
'fold',
'fromisocalendar',
'fromisoformat',
'fromordinal',
'fromtimestamp',
'hour',
'isocalendar',
'isoformat',
'isoweekday',
'max',
'microsecond',
'min',
'minute',
'month',
'now',
'replace',
'resolution',
'second',
'strftime',
'strptime',
'time',
'timestamp',
'timetuple',
'timetz',
'today',
'toordinal',
'tzinfo',
'tzname',
'utcfromtimestamp',
'utcnow',
'utcoffset',
'utctimetuple',
'weekday',
'year']
From the output, you can see that the datetime object can be
used to store various information about a date such as year,
weekday, second, timestamp, minute, hour, microsecond, etc.
Script 17:
date1 =datetime.datetime.now()
date2 =datetime.datetime(1990,4,10)
date_dif= date1-date2
print(date_dif.days)
print(date_dif.total_seconds())
Output:
11324
978431869.338581
You can work with time exclusively using the time object of
the datetime module. The following script creates a new time
object and then prints the object type and its attributes and
methods.
Script 18:
import datetime
new_time=datetime.time()
print(type(new_time))
print(dir(new_time))
Output:
<class 'datetime.time'>
Script 19:
new_time=datetime.time(5,30)
print(new_time.hour)
print(new_time.minute)
print(new_time.second)
print(new_time.microsecond)
Since you did not specify any value for second and
microsecond attributes, you can see 0 in the output for these
attributes.
Output:
5
30
0
0
You can also replace the value of the hour, minute, or second
using the replace() function.
Script 20:
new_time=new_time.replace(hour =7)
print(new_time.hour)
Output:
You can also create objects that store information about the
date only (no time information), as shown in the following
script.
Script 21:
import datetime
new_date=datetime.date(2019,2,10)
print(new_date.ctime())
Output:
Script 22:
print(dir(new_date))
Output:
Finally, you can also replace day, month, and other attributes
in a date object using the replace() function.
Script 23:
import datetime
new_date=datetime.date(2019,2,10)
new_date=new_date.replace(day =20)
print(new_date.ctime())
Output:
Script 24:
import math
angle =math.radians(90)
print(angle)
Output:
1.5707963267948966
The following script finds the sine, cosine, and tangent values
of an angle. The angle value is passed in radians to the sin(),
cos(), and tan() functions, respectively.
Script 25:
print(math.sin(angle))
print(math.cos(angle))
print(math.tan(angle))
Output:
1.0
6.123233995736766e-17
1.633123935319537e+16
You can use the pow() method from the Math module to raise
an integer to the power of another integer. For instance, the
following script prints the result when the integer 4 is raised
to the power of 5.
Script 26:
print(math.pow(4,5))
Output:
1024.0
Similarly, you can find the square root of an integer using the
sqrt() method, as shown below.
Script 27:
print(math.sqrt(225))
Output:
15.0
You can also calculate natural log and log with the base 10,
using the log() and log10() functions, as shown in the
following script:
Script 28:
print(math.log(100))
print(math.log10(100))
Output:
4.605170185988092
2.0
Script 29:
import random
print(random.random())
Output:
0.6631112113673787
Script 30:
print(random.randint(0,50))
print(random.randint(0,50))
print(random.randint(0,50))
Output:
31
2
17
Script 31:
print(random.randrange(0,50))
print(random.randrange(0,50,3))
print(random.randrange(0,50,5))
Output:
27
27
20
You can also select an item from a list randomly using the
choice() function from the random module. Here is an
example:
Script 32:
cars =[1,15,36,14,15,10]
print(random.choice(cars))
Output:
14
Finally, to randomly shuffle items within a list, you can use the
shuffle() function from the Random module. Take a look at
the following example:
Script 33:
cars =[1,15,36,14,15,10]
cars_shuffle=random.shuffle(cars)
print(cars_shuffle)
Output:
None
10.6. Find Execution time of Python Scripts
Execution time is an important metric for measuring the
performance of a specific piece of code. In programming, you
can implement the same logic using different pieces of code.
However, you should select an approach that is not very slow.
Otherwise, users will have to wait for long periods to perform
desired tasks using your application.
Script 34:
defget_fib(num):
if num ==1or num ==2:
return1
else:
returnget_fib(num-1)+get_fib(num-2)
get_fib(20)
Output:
6765
The following script defines the get_fib2() method, which
calculates the value of a Fibonacci number using a for loop.
Script 35:
def get_fib2(num):
if num ==1:
return0
if num ==2:
return1
num1 =1
num2 =1
foriinrange(3, num+1):
num1 = num2
num2 =val
returnval
get_fib2(20)
Output:
6765
The following script measures the execution time for the get_
fib() function for calculating the 30th number in the Fibonacci
series.
Script 36:
import time
start_time=time.time()
get_fib(30)
end_time=time.time()
script_time=end_time-start_time
print(str(script_time))
Output:
0.28528690338134766
Script 37:
import time
start_time=time.time()
val= get_fib2(30)
end_time=time.time()
script_time=end_time-start_time
print(str(script_time))
Output:
0.0
You can also use the timeit module for calculating the
execution time of a program. To do so, you need to call the
timeit() method from the timeit module. You need to pass the
function call and the function script that you want to measure
for execution speed as string parameters to the timeit()
method.
The following script stores the function call and the function
body in the string format in the variables statement and
setup, respectively.
Script 38:
statement ="get_fib(30)"
setup ="""
def get_fib(num):
if num == 1 or num == 2:
return 1
else:
return get_fib(num-1) + get_fib(num-2)
"""
importtimeit
timeit.timeit(statement, setup, number =100)
Output:
37.98757040000055
Script 40:
statement ="get_fib2(30)"
setup ="""
def get_fib2(num):
if num == 1:
return 0
if num == 2:
return 1
num1 = 1
num2 = 1
num1 = num2
num2 = val
return val
"""
Script 41:
importtimeit
timeit.timeit(statement, setup, number =100)
Output:
0.000453499998911866
If you are using the Jupyter Notebook, you can find the
execution time of a particular script by simply adding the
command %%timeit command at the top of the cell that
contains your script.
Script 42:
%%timeit
get_fib(30)
Output:
Script 43:
%%timeit
get_fib2(30)
Output:
In this chapter, you have seen how to work with some of the
most useful modules in Python. In the next chapter, you will
see how to create your custom modules in Python.
Exercise 10.1
Question 1:
Question 2:
Question 3:
Exercise 10.2
Find the number of counts for each unique value in the
following list using the for loop and the Counter object
[Apple, Orange, Apple, Apple, Orange, Banana, Orange,
Orange].
Creating Custom Modules in Python
Now that you know why modules can make your life easier,
let’s see how you can develop a module in Python.
Script 1:
defshow_message():
print("Hello from your custom module")
You can give any name to the new file. I will name it test.py.
To use the module mymodule in the file test.py, you need to
import the mymodule first. You can import your custom
module in the same way as you imported built-in Python
modules in the last chapter. You have to use the keyword
import, followed by the module name mymodule.
Script 2:
importmymodule
mymodule.show_message()
Output:
Script 3:
frommymoduleimportshow_message
show_message()
Output:
Script 4:
defshow_message():
print("Hello from your custom module")
deffind_square(num):
return num * num
Script 5:
frommymoduleimportshow_message
find_square(5s)
Here is the output of the above script. The output shows that
the find_square function is not defined.
Output:
Script 6:
frommymoduleimport*
show_message()
result =find_square(5)
print(result)
Output:
Script 7:
importmymodule
deffind_cube(num):
return num *mymodule.find_square(num)
Script 8:
result =find_cube(5)
print(result)
Output:
125
Script 9:
importmymodule
import mymodule2
result =mymodule.find_square(5)
print(result)
result = mymodule2.find_cube(5)
print(result)
Output:
25
125
Script 10:
classCustomClass:
defshow_message(self):
print("Hello from your custom module")
deffind_square(self, num):
return num * num
Script 11:
importmymodule
my_class=mymodule.CustomClass()
result =my_class.find_square(5)
print(result)
Output:
25
11.5. Importing Modules from a Different Path
In the previous section, you placed your module file and your
test file in the same directory. However, you can also save
your module file in a different directory and still import the
module into your application. Let’s see how you can do so.
Script 12:
class CustomClass3:
defshow_message(self):
print("Hello from your custom module")
deffind_square(self, num):
return num * num
Script 13:
import sys
sys.path.append("E:/modules")
Script 14:
import mymodule3
my_class3 = mymodule3.CustomClass3()
result = my_class3.find_square(5)
print(result)
Output:
25
Script 15:
import sys
print(sys.path)
Output:
['C:\\ProgramData\\Anaconda3\\python38.zip',
'C:\\ProgramData\\Anaconda3\\DLLs',
'C:\\ProgramData\\Anaconda3\\lib',
'C:\\ProgramData\\Anaconda3', '',
'C:\\ProgramData\\Anaconda3\\lib\\site-packages',
'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\email-
6.0.0a1-py3.8.egg', 'C:\\ProgramData\\Anaconda3\\lib\\site-
packages\\win32', 'C:\\ProgramData\\Anaconda3\\lib\\site-
packages\\win32\\lib',
'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\Pythonwin',
C:\\ProgramData\\Anaconda3\\lib\\site-packages’
Save your mymodule3.py file in this path. Now, you can call
functionalities from the mymodule3 module without
explicitly adding the path of the mymodule3.py file into your
application.
Script 16:
import mymodule3
my_class3 = mymodule3.CustomClass3()
result = my_class3.find_square(5)
print(result)
Output:
25
Exercise 11.1
Question 1:
Question 2:
Question 3:
Until now, you have been writing Python code that displays
data in the console output. However, most modern Python
applications will require you to develop graphical user
interfaces (GUI). Various Python libraries allow you to
develop GUI. However, Tkinter
(https://docs.python.org/3/library/tkinter.html) is the only
built-in Python library for GUI development.
In this chapter, you will see how to develop a basic GUI using
the Python Tkinter library.
Script 1:
# importing tkinter
fromtkinterimport*
# creating instance of Tk class
main_window= Tk()
type(main_window)
Output:
You can set the title of the window using the title attribute.
Similarly, to set the window’s width, height, and location, you
can use the geometry attribute. The width and height in
pixels and the distance in pixels from the top and left of the
screen are specified in the following format: Width x Height
+ Distance from left + Distance from the top.
The following script sets the width and height of the window
to 500 pixels. The distance from the left of the screen will be
100 pixels, while the distance from the top of the screen will
be 200 pixels.
Script 2:
# importing tkinter
fromtkinterimport*
Output:
Let’s add a simple label to our window. To do so, you need
to create an object of the Label class. In the constructor, the
window name to which you want to attach the label is
passed as the first parameter. The label text is passed to the
text parameter, as shown below.
You also need to call the pack() method on the Label class
object to attach the label to the window.
Script 3:
# importing tkinter
fromtkinterimport*
# creating instance of Tk class
main_window= Tk()
Output:
You can also specify the callback function that is called when
you click the button using the command attribute. Finally,
you need to call the pack() method on all the widgets that
you need to attach to your main window. For reference, look
at the following script.
Script 4:
# importing tkinter
fromtkinterimport*
main_window.mainloop()
Output:
a button is clicked
Apart from the main window attribute, you can bind the text
entered in the Entry field to an object of StringVar using the
textvariable attribute of the Entry class.
Finally, you can call the pack() method via the text_field
object. Notice here you passed True as the value for the
expand attribute, which will expand the widget to the full
width of the main window.
Script 5:
# importing tkinter
fromtkinterimport*
main_window.mainloop()
Output:
Script 6:
# importing tkinter
fromtkinterimport*
defmy_func():
ifmy_text.get()=="":
print("Enter something in the text box")
else:
print("You entered:",my_text.get())
main_window.mainloop()
Output:
You entered: Hello, this is a random text
Script 7:
# importing tkinter
fromtkinterimport*
defmy_func():
showinfo(
title ="Information",
message ="You clicked a button"
)
main_window.mainloop()
Output:
12.2.4. Adding Multiple Widgets
Script 8:
# importing tkinter
fromtkinterimport*
main_window.mainloop()
Output:
a button is clicked
Script 9:
# importing tkinter
fromtkinterimport*
main_window.mainloop()
Output:
a button is clicked
Script 10:
# importing tkinter
fromtkinterimport*
defmy_func():
text =""
ifmy_text.get()=="":
text ="Enter something in the text box"
else:
text ="You entered:"+my_text.get()
main_window.mainloop()
Output:
12.3. Creating a Layout
Layouts help you organize your widget in a specific way.
The following script creates a grid layout with two rows and
three columns.
To create a grid layout, you only need to define the position
and width of each column via the columnconfigure() method
of the Tk class object (which is also your main window).
The following script adds two labels to the main window. The
first label is positioned at the first row and first column index.
The second label is positioned in the first row and second
column.
Script 11:
# importing tkinter
fromtkinterimport*
main_window.mainloop()
Output:
Exercise 12.1
Question 1:
You need to call the mainloop() method from the object of
the Tk class in Tkinter because:
A. It opens the main GUI window
B. It keeps the GUI window open
C. It allows users to interact with widgets
D. None of the above
Question 2:
Question 3:
Exercise 12.2
Create a simple login form that looks like the one in the
following image, using Tkinter.
When you click the `Login to your account` button, the
email should be displayed in a message box.
Useful Python Libraries for Data
Science
In this chapter, you will study three very useful libraries for
data science, namely: NumPy, Pandas, and Matplotlib. The
NumPy library is commonly used for performing complex
mathematical operations on data. The Pandas library is used
for data preprocessing, analysis, and manipulation tasks.
Finally, the Matplotlib library is commonly used for data
visualization and plotting.
Script 1:
importnumpyas np
nums_list=[10,12,14,16,20]
nums_array=np.array(nums_list)
type(nums_array)
Output:
numpy.ndarray
Script 2:
row1 =[10,12,13]
row2 =[45,32,16]
row3 =[45,32,16]
Output:
(3, 3)
Script 3:
nums_arr=np.arange(5,11)
print(nums_arr)
Output:
[5 6 7 8 9 10]
Script 4:
nums_arr=np.arange(5,12,2)
print(nums_arr)
Output:
[5 7 9 11]
Script 5:
ones_array=np.ones(6)
print(ones_array)
Output:
[1. 1. 1. 1. 1. 1.]
Script 6:
ones_array=np.ones((6,4))
print(ones_array)
Output:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
Script 7:
uniform_random=np.random.rand(4,5)
print(uniform_random)
Output:
Script 8:
normal_random=np.random.randn(4,5)
print(uniform_random)
Output:
Script 9:
integer_random=np.random.randint(10,50,5)
print(integer_random)
Output:
[25 49 21 35 17]
Script 10:
uniform_random=np.random.rand(4,6)
uniform_random=uniform_random.reshape(3,8)
print(uniform_random)
Output:
[[0.37576967 0.5425328 0.56087883 0.35265748 0.19677258
0.65107479 0.63287089 0.70649913]
[0.47830882 0.3570451 0.82151482 0.09622735 0.1269332
0.65866216 0.31875221 0.91781242]
[0.89785438 0.47306848 0.58350797 0.4604004 0.62352155
0.88064432 0.0859386 0.51918485]]
Script 11:
s =np.arange(1,11)
print(s)
Output:
[1 2 3 4 5 6 7 8 9 10]
Script 12:
print(s[1])
Output:
2
To slice an array, you have to pass the lower index followed
by a colon and the upper index. The items from the lower
index (inclusive) to the upper index (exclusive) will be
filtered.
The following script slices the array “s” from the 1st index to
the 9th index. The elements from index 1 to 8 are printed in
the output.
Script 13:
print(s[1:9])
Output:
[2 3 4 5 6 7 8 9]
If you specify only the upper bound, all the items from the
first index to the upper bound are returned. Similarly, if you
specify only the lower bound, all the items from the lower
bound to the last item of the array are returned.
Script 14:
print(s[:5])
print(s[5:])
Output:
[1 2 3 4 5]
[6 7 8 9 10]
Script 15:
row1 =[10,12,13]
row2 =[45,32,16]
row3 =[45,32,16]
Output:
[[10 12 13]
[45 32 16]]
Similarly, the following script returns all the rows but only the
first two columns.
Script 16:
row1 =[10,12,13]
row2 =[45,32,16]
row3 =[45,32,16]
Output:
[[10 12]
[45 32]
[45 32]]
Script 17:
row1 =[10,12,13]
row2 =[45,32,16]
row3 =[45,32,16]
Output:
[[32 16]
[32 16]]
Script 18:
nums=[10,20,30,40,50]
np_sqr=np.sqrt(nums)
print(np_sqr)
Output:
Script 19:
nums=[10,20,30,40,50]
np_log= np.log(nums)
print(np_log)
Output:
§ Finding Exponents
The exp() function takes the exponents of all the elements in
a list, as shown below:
Script 20:
nums=[10,20,30,40,50]
np_exp=np.exp(nums)
print(np_exp)
Output:
nums=[10,20,30,40,50]
np_sine=np.sin(nums)
print(np_sine)
nums=[10,20,30,40,50]
np_cos=np.cos(nums)
print(np_cos)
Output:
Here is an example.
Script 22:
A =np.random.randn(4,5)
B =np.random.randn(5,4)
Z = np.dot(A,B)
print(Z)
Output:
Script 23:
row1 =[10,12,13]
row2 =[45,32,16]
row3 =[45,32,16]
Output:
row1 =[1,2,3]
row2 =[4,5,6]
row3 =[7,8,9]
inverse =np.linalg.inv(nums_2d)
print(inverse)
Output:
Script 25:
row1 =[1,2,3]
row2 =[4,5,6]
row3 =[7,8,9]
determinant =np.linalg.det(nums_2d)
print(determinant)
Output:
-9.51619735392994e-16
Script 26:
row1 =[1,2,3]
row2 =[4,5,6]
row3 =[7,8,9]
trace =np.trace(nums_2d)
print(trace)
Output:
15
Import pandas as pd
Script 27:
import pandas as pd
titanic_data=pd.read_csv(r"E:\Datasets\titanic_data.csv")
titanic_data.head()
Output:
The read_csv() method reads data from a CSV or TSV file and
stores it in a Pandas dataframe, which is a special object that
stores data in the form of rows and columns.
Script 28:
titanic_pclass1=(titanic_data.Pclass==1)
titanic_pclass1
Output:
0 False
1 True
2 False
3 True
4 False
...
886 False
887 True
888 False
889 True
890 False
Name: Pclass, Length: 891, dtype: bool
Script 29:
titanic_pclass1=(titanic_data.Pclass==1)
titanic_pclass1_data =titanic_data[titanic_pclass1]
titanic_pclass1_data.head()
Output:
Script 30:
titanic_pclass_data=titanic_data[titanic_data.Pclass==1]
titanic_pclass_data.head()
Output:
Script 31:
ages =[20,21,22]
age_dataset=titanic_data[titanic_data["Age"].isin(ages)]
age_dataset.head()
Output:
Script 32:
ages =[20,21,22]
ageclass_dataset=titanic_data[titanic_data["Age"].isin(ages)&
(titanic_data["Pclass"]==1)]
ageclass_dataset.head()
Output:
Script 33:
titanic_data_filter=titanic_data.filter(["Name","Sex","Age"])
titanic_data_filter.head()
The output below shows that the dataset now contains only
the Name, Sex, and Age columns.
Output:
For instance, the following script drops the Name, Age, and
Sex columns from the Titanic dataset and returns the
remaining columns.
Script 34:
titanic_data_filter=titanic_data.drop(["Name","Sex","Age"], axis
=1)
titanic_data_filter.head()
Output:
Further Readings – Pandas Filter
To study more about the Pandas Filter method, please
check Pandas’ official documentation for the filter method
(https://bit.ly/2C8SWhB). Try to execute the filter method
with a different set of attributes as mentioned in the official
documentation.
Script 35:
age_sorted_data=titanic_data.sort_values(by=['Age'])
age_sorted_data.head()
Output:
To sort by the descending order, you need to pass False as
the value for the ascending attribute of the sort_values()
function. The following script sorts the dataset by descending
order of age.
Script 36:
age_sorted_data=titanic_data.sort_values(by=['Age'], ascending
=False)
age_sorted_data.head()
Output:
The following script first sorts the data by Age and then by
Fare, both by descending orders.
Script 37:
age_sorted_data=titanic_data.sort_values(by=['Age','Fare'],
ascending =False)
age_sorted_data.head()
Output:
Further Readings – Python Pandas Module
To study more about the Python Pandas module, please
check the official documentation
(https://pandas.pydata.org/). Get used to searching and
reading this documentation. It is a great resource of
knowledge.
Finally, before you can plot any graphs with the Matplotlib
library, you will need to import the pyplot module from the
Matplotlib library. And since all the scripts will be executed
inside Jupyter Notebook, the statement %matplotlib inline
has been used to generate plots inside Jupyter Notebook.
Execute the following script:
Script 38:
importmatplotlib.pyplotasplt
%matplotlib inline
Script 39:
importmatplotlib.pyplotasplt
importnumpyas np
import math
x_vals=np.linspace(0,20,20)
y_vals=[math.sqrt(i)foriinx_vals]
plt.plot(x_vals,y_vals)
To plot a line plot via the pyplot module, you only need to call
the plot() method of the pyplot module and then pass it the
values for the x and y axes. It is important to mention that plt
is an alias for pyplot in script 1. You can name it anything you
want. Here is the output for script 39.
Output:
This is one of the ways to plot a graph via Matplotlib. There is
also another way to do so. You have to first call the figure()
method via the plt module, which draws an empty figure.
Next, you can call the axes() method, which returns an axes
object. You can then call the plot() method from the axes
object to create a plot, as shown in the following script.
Script 40:
importmatplotlib.pyplotasplt
importnumpyas np
import math
x_vals=np.linspace(0,20,20)
y_vals=[math.sqrt(i)foriinx_vals]
fig =plt.figure()
ax =plt.axes()
ax.plot(x_vals,y_vals)
The following script sets the plot size to 8 inches wide and 6
inches tall.
Script 41:
importmatplotlib.pyplotasplt
importnumpyas np
import math
plt.rcParams["figure.figsize"]=[8,6]
x_vals=np.linspace(0,20,20)
y_vals=[math.sqrt(i)foriinx_vals]
plt.plot(x_vals,y_vals)
In the output, you can see that the default plot size has been
increased.
Output:
Script 42:
importmatplotlib.pyplotasplt
importnumpyas np
import math
x_vals=np.linspace(0,20,20)
y_vals=[math.sqrt(i)foriinx_vals]
plt.xlabel('X Values')
plt.ylabel('Y Values')
plt.title('Square Roots')
plt.plot(x_vals,y_vals)
Here, in the output, you can see the labels and titles that you
specified in the above script.
Output:
Script 43:
importmatplotlib.pyplotasplt
importnumpyas np
import math
x_vals=np.linspace(0,20,20)
y_vals=[math.sqrt(i)foriinx_vals]
plt.xlabel('X Values')
plt.ylabel('Y Values')
plt.title('Square Roots')
plt.plot(x_vals,y_vals,'r')
Output:
importmatplotlib.pyplotasplt
importnumpyas np
import math
x_vals=np.linspace(0,20,20)
y_vals=[math.sqrt(i)foriinx_vals]
plt.xlabel('X Values')
plt.ylabel('Y Values')
plt.title('Square Roots')
plt.plot(x_vals,y_vals,'r', label ='Square Root')
plt.legend(loc='upper center')
Output:
You can also plot multiple line plots inside one graph. All you
have to do is call the plot() method twice with different
values for the x and y axes. The following script plots a line
plot for square root in red and for a cube function in blue.
Script 45:
importmatplotlib.pyplotasplt
importnumpyas np
import math
x_vals=np.linspace(0,20,20)
y_vals=[math.sqrt(i)foriinx_vals]
y2_vals =x_vals**3
plt.xlabel('X Values')
plt.ylabel('Y Values')
plt.title('Square Roots')
plt.plot(x_vals,y_vals,'r', label ='Square Root')
plt.plot(x_vals, y2_vals,'b', label ='Cube')
plt.legend(loc='upper center')
Output:
Further Readings – Matplotlib Line Plot
To study more about Matplotlib line plots, please check
Matplotlib’s official documentation for line plots
(https://bit.ly/33BqsIR). Get used to searching and reading
this documentation. It is a great resource of knowledge.
Script 46:
importmatplotlib.pyplotasplt
importnumpyas np
import math
import pandas as pd
data =pd.read_csv("E:\Datasets\iris_data.tsv",sep='\t')
data.head()
plt.xlabel('Sepal Length')
plt.ylabel('Petal Length')
plt.title('Sepal vs Petal Length')
plt.scatter(data["SepalLength"], data["PetalLength"], c ="b")
The output shows a scattered plot with blue points. The plot
clearly shows that with an increase in sepal length, the petal
length of an iris flower also increases.
Output:
Further Readings – Matplotlib Scatter Plot
To study more about Matplotlib scatter plot, please check
Matplotlib’s official documentation for scatter plots
(https://bit.ly/3a8Dtef). Get used to searching and reading
this documentation. It is a great resource of knowledge.
Script 47:
import pandas as pd
data =pd.read_csv(r"E:\ Datasets\titanic_data.csv")
data.head()
Output:
To plot a bar plot, you need to call the bar() method. The
categorical values are passed as the x-axis, and
corresponding aggregated numerical values are passed on
the y-axis. The following script plots a bar plot between
genders and ages of the Titanic ship.
Script 48:
importmatplotlib.pyplotasplt
importnumpyas np
import math
plt.xlabel('Gender')
plt.ylabel('Ages')
plt.title('Gender vs Age')
plt.bar(data["Sex"], data["Age"])
Output:
Further Readings – Matplotlib Bar Plot
To study more about Matplotlib bar plots, please check
Matplotlib’s official documentation for bar plots.
(https://bit.ly/2PNKR5r). Get used to searching and reading
this documentation. It is a great resource of knowledge.
Script 49:
Output:
Exercise 13.1
Question 1:
Question 2:
Question 3:
Exercise 13.2
Create a random NumPy array of 5 rows and 4 columns.
Using array indexing and slicing, display the items from row 3
to end and column 2 to end.
Solution:
uniform_random=np.random.rand(4,5)
print(uniform_random)
print("Result")
print(uniform_random[2:,3:])
Project 1
Script 1:
# importing tkinter
fromtkinterimport*
# importing tkk
fromtkinterimportttk
Script 2:
Script 3:
Script 4:
text =StringVar()
# creating a text field using Entry class
text_field=ttk.Entry(main_window,textvariable= text, width=55)
Script 5:
expression_string=""
defpress_button(num):
# access the global expression_string
globalexpression_string
Script 6:
defpress_equal_button():
try:
# access the global expression_string
globalexpression_string
except:
# show error in case of exception
text.set(" error ")
Script 7:
def clear():
# update expression_string to an empty string
expression_string=""
Script 8:
my_button1.grid(row=1, column=0,padx=5,pady=5)
my_button2.grid(row=1, column=1,padx=5,pady=5)
my_button3.grid(row=1, column=2,padx=5,pady=5)
my_button_plus.grid(row=1, column=3,padx=5,pady=5)
Similarly, the following script adds four buttons in a third of
the grid. The buttons added are “4, 5, 6, and —”.
Script 9:
my_button4.grid(row=2, column=0,padx=5,pady=5)
my_button5.grid(row=2, column=1,padx=5,pady=5)
my_button6.grid(row=2, column=2,padx=5,pady=5)
my_button_minus.grid(row=2, column=3,padx=5,pady=5)
The following script adds four more buttons in the fourth row
of the grid. The buttons added are “7, 8, 9, and x”.
Script 10:
my_button8.grid(row=3, column=1,padx=5,pady=5)
my_button9.grid(row=3, column=2,padx=5,pady=5)
my_button_mul.grid(row=3, column=3,padx=5,pady=5)
Script 11:
my_button0.grid(row=4, column=0,padx=5,pady=5)
my_button_dot.grid(row=4, column=1,padx=5,pady=5)
my_button_clr.grid(row=4, column=2,padx=5,pady=5)
my_button_div.grid(row=4, column=3,padx=5,pady=5)
Script 12:
Script 13:
When you execute all of the above scripts in this project, you
will see the following GUI.
You can play around with the calculator and try other
calculations to see if the calculator works correctly.
Final Output
Project 2
In this project, you will create a very simple alarm clock with
Python. You will again use the Tkinter library along with other
built-in Python functionalities to develop the alarm clock.
Here is how your alarm clock will look.
The alarm clock will play an audio of a siren at the time you
passed to the hour, minutes, and seconds fields. The time
should be passed in the 24-hour time format.
Script 1:
fromtkinterimport*
fromtkinterimportttk
import datetime
import time
importwinsound
fromtkinter.messageboximportshowinfo
from threading import*
Script 2:
main_window= Tk()
main_window.title("Python Alarm Clock")
Script 3:
Script 4:
Script 5:
Before you add a button for setting the alarm, you need to
define a callback function that contains the logic used to set
the alarm. The following script implements that function.
Script 7:
defset_alarm():
whileTrue:
# Set Alarm
alarm_time= f"{txt_hours.get()}:{txt_mins.get()}:
{txt_mins.get()}"
# playing sound
winsound.PlaySound('E:/Datasets/siren.wav',winsound.SND_FILENAME
|winsound.SND_ASYNC)
If you directly call the set_alarm() method, your GUI will not
be responsive. If you run the set_alarm() method inside the
thread, the set_alarm() method will execute in parallel with
other GUI operations, and your main window will not become
unresponsive.
Script 8:
defstart_alarm_thread():
t1=Thread(target=set_alarm)
t1.start()
Next, you will create the button, which, when clicked, will
execute the set_alarm() method in a thread. You can see that
the callback function for the button in the following script is
start_alarm_thread().
Script 9:
Finally, the following script adds a label and a text field that
displays the current system time.
Script 10:
Script 11:
Final Output
If you execute all the scripts in this project, you will see the
following output. Try to enter hours, minutes, and seconds in
the corresponding text fields to set the alarm, and then click
the SET ALARM button. You will hear a siren when the
current system time becomes equal to the alarm time.
Project 3
In this project, you will see how to create a very basic version
of the hangman game.
Let’s see how to develop such a game with Python. The GUI
of the game will look like this:
Importing the Required Libraries
As always, you start by importing the required libraries.
Script 1:
# importing tkinter
fromtkinterimport*
# importing tkk
fromtkinterimportttk
import random
Script 2:
main_window= Tk()
main_window.title("Hangman Game")
main_window.geometry("400x400+100+200")
Script 3:
The following script also adds a text field using the Entry
widget. This text field contains dashes for each character in
the word to be guessed. Whenever a character is correctly
guessed by the user, the dash in the corresponding position
of the text field is replaced by the character guessed
correctly.
Script 4:
The words list stores the names of all the words. The word
that is to be guessed will be randomly selected from this list.
You can add more words if you like.
The rem_guess will store the integer value for the number of
remaining guesses. The value of this variable is initially set to
5. You can add or decrease this value if you want.
Script 5:
word_to_guess=""
rem_guess=""
cor_guess=""
empty_str=""
original_word=""
definitialize_values():
globalword_to_guess
globaloriginal_word
globalempty_str
globalrem_guess
globalcor_guess
# intitializing values
initialize_values()
The following script creates two labels and two text fields.
The user enters the character to be guessed in the first text
field. The second text field displays the allowed number of
remaining wrong guesses.
Script 6:
tf_rg=ttk.Entry(main_window,textvariable=txt_rg, font=
("Courier",10))
tf_rg.grid(row=4, column=1,padx=5,pady=5)
Script 7:
defmake_guess():
showinfo(
title ="Information",
message ="You have used all your guesses. \n You lost. \n
The correct word is: "+word_to_guess+". \nTry Again"
)
initialize_values()
txt_ip.set("")
txt_rg.set(rem_guess)
# if you have more wrong guesses left
else:
showinfo(
title ="Information",
message ="Wrong Guess"
)
return
cor_guess=cor_guess+1
#if the number of correct guesses are equal to the word length
ifcor_guess==len(word_to_guess):
Script 8:
Script 9:
Final Output
Here is the final output of your project. You can see from the
following screenshot that the user has guessed two
characters, “e” and “g,” correctly. Also, the user has made one
wrong guess since the allowed number of remaining wrong
guesses is 4.
And that’s it. You have developed your very own hangman
game. Congratulations!
From the Same Publisher
Exercise 2.1
Question 1:
Answer: B
Question 2:
Answer: D
Question 3:
colors ={"color1":"red",
"color2":"blue",
"color1":"green"}
print(colors["color1"])
A. Red
B. Blue
C. Green
D. None of the Above
Answer: A
Exercise 2.2
Create a dictionary that contains days of a week (starting
from Monday) as values. The keys should start from 1 with an
increment of 1. Display the 3rd week of the day using its key.
Use a loop to display all the key-value pairs (see the section
on accessing dictionary items for reference).
Solution:
days ={1:"Monday",
2:"Tuesday",
3:"Wednesday",
4:"Thursday",
5:"Friday",
6:"Saturday",
7:"Sunday"}
print(days[3])
fork,vindays.items():
print(str(k)+" ->"+v)
Exercise 3.1
Question 1:
A. True
B. False
C. SyntaxError
D. red is in a
Answer: C
Question 2:
X =100
Y =50
not(X is Y)
A. True
B. False
C. SyntaxError
D. None of the Above
Answer: A
Question 3:
Exercise 3.2
Suppose you have the following the following three Python
variables:
a =400
b =350
c = b
d =[100,200,300,400]
Solution:
a =400
b =350
c = b
d =[100,200,300,400]
print(a > b)
print(b < a and b is c)
print(b in d)
print(a in d)
print((a + b)notin d)
Exercise 4.1
Question 1:
You should use a while loop when:
A. You want to repeatedly execute a code until a certain
condition returns true
B. When you know the exact number of times you want
to execute a piece of code
C. To execute a code 10 times
D. None of the above
Answer: A
Question 2:
Answer: C
Question 3:
Answer: C
Exercise 4.2
Write a program that prints the prime numbers between 1
and 100.
Solution:
foriinrange(1,101):
ifi==1:
print(i)
else:
prime =True
for j inrange(2,i):
ifi% j ==0:
prime =False
break
if prime:
print(i)
Exercise 5.1
Question 1:
Answer: D
Question 2:
Question 3:
Answer: A
Exercise 5.2
Write a function that calculates and prints the first N
numbers of the Fibonacci series, where N is any integer.
Solution:
defget_fib(num):
if num ==1or num ==2:
return1
else:
returnget_fib(num-1)+get_fib(num-2)
get_fib(8)
Exercise 6.1
Question 1:
Answer: D
Question 2:
Answer: C
Question 3:
Exercise 6.2
Perform the following tasks:
1. Create a Parent class Vehicle with two instance
attributes: name and price, and one instance method
show_vehicle(). The show_vehicle() method displays
the name and price attributes.
2. Initialize the Vehicle class attributes using a
constructor.
3. Create a class Car that inherits the Parent Vehicle
class. Add an attribute named tires to the Car class.
Override the show_vehicle() method of the parent
Vehicle class and display name, price, and tire
attributes.
4. Inside the Car class constructor, call the Vehicle class
constructor and pass the name and price to the
parent Vehicle class constructor.
5. Create objects of Car and Vehicle classes, and call
show_vehicle() method using both objects.
Solution:
class Vehicle:
defshow_vehicle(self):
print("The vehicle name is:", self.name)
print("The vehicle price is:",str(self.price))
class Car(Vehicle):
defshow_vehicle(self):
print("The vehicle name is:", self.name)
print("The vehicle price is:",str(self.price))
print("Number of tyres:",str(self.tires))
vehicle = Vehicle("Vehicle",20000)
vehicle.show_vehicle()
print("=====")
car = Car("Car",15000,4)
car.show_vehicle()
Exercise 7.1
Question 1:
Answer: A
Question 2:
Question 3:
Answer: D
Exercise 7.2
Create a custom exception named
EvenNumberInsertionException, which tells users that they
cannot add an even number in a list of integers. Create a list
and add some odd and even numbers to it. Raise the
EvenNumberInsertionException and tell the user the even
number added along with the error message.
Solution:
classEvenNumberInsertionException(Exception):
"""Exception raised when an even number is inserted in a list
Attributes:
new_list -- the list itself
error_message -- the detail of the exception
"""
def__str__(self):
return f'{self.new_list[-1]} -> {self.error_message}'
my_list=[]
foriin[1,3,5,7,8,9,12,15,17]:
my_list.append(i)
print(my_list)
if i%2==0:
raiseEvenNumberInsertionException(my_list)
Exercise 8.1
Question 1:
Answer: D
Question 2:
Answer: B
Question 3:
What are the parameters values that you need to pass to the
connect() method of the socket()to connect to a remote
server application through a socket?
A. Server name and server ip name
B. Server ip address and port number
C. Server ip address, port number, and application name
D. Both A and C
Answer: B
Exercise 8.2
Create a new text file. Write three lines of text in the text file.
Read all the text from the file line by line using the with
operator.
Solution:
file_handle_text=open("E:/Datasets/my_new_file.txt","w")
file_handle_text.write("This is line 1\n")
file_handle_text.write("This is line 2\n")
file_handle_text.write("This is line 3\n")
file_handle_text.close()
withopen("E:/Datasets/my_new_file.txt", mode
='r')asfile_handle_text:
file_content=file_handle_text.read()
print(file_content)
Exercise 9.1
Question 1:
Answer: C
Question 2:
Answer: B
Question 3:
Answer: B
Exercise 9.2
Write a regular expression that returns all words from a list
that contain a carrot (^) symbol or a dollar sign ($), or a plus
(+) sign.
Solution:
import re
pattern ='(.*\^.*)|(.*\$.*)|(.*\+.*)'
string_list=["path+ology","biolo$gy","25","""geogr^aphy",
"psychology","mathematics"]
forstrinstring_list:
result =re.match(pattern,str)
if result:
print(str)
Exercise 10.1
Question 1:
Answer: C
Question 2:
Answer: D
Question 3:
Which of the following modules and expressions can be used
to find script time in Jupyter?
A. ##
B. timeit
C. time
D. all of the above
Answer: D
Exercise 10.2
Find the number of counts for each unique value in the
following list using the for loop and the Counter object
[Apple, Orange, Apple, Apple, Orange, Banana, Orange,
Orange].
Solution:
fruits =["Apple","Orange","Apple","Apple","Orange","Banana",
"Orange","Orange"]
fruits_dic={}
for fruit in fruits:
if fruit notinfruits_dic:
fruits_dic[fruit]=1
else:
fruits_dic[fruit]+=1
print(fruits_dic)
fruits_count= Counter(fruits)
print(fruits_count)
Exercise 11.1
Question 1:
Answer: B
Question 2:
Answer: D
Question 3:
Answer: D
Exercise 11.2
Perform the following tasks:
Create a custom module1 that contains a function that
returns the cube of a number.
Solution:
deffind_cube(num):
import module1
deffind_sum_cube(num1, num2):
num1_cube1 =(module1.find_cube(num1))
num1_cube2 =(module1.find_cube(num2))
import module1
import module2
result = module1.find_cube(3)
print(result)
result = module2.find_sum_cube(2,3)
print(result)
Exercise 12.1
Question 1:
Answer: B
Question 2:
Answer: C
Question 3:
Answer: D
Exercise 12.2
Create a simple login form that looks like the one in the
following image, using Tkinter.
Solution:
fromtkinterimport*
fromtkinterimportttk
main_window= Tk()
main_window.columnconfigure(0, weight=1)
main_window.columnconfigure(1, weight=1)
email_text=StringVar()
email_field=ttk.Entry(main_window,textvariable=email_text)
email_field.grid(column=1, row=0,padx=5,pady=5)
pass_text=StringVar()
pass_field=ttk.Entry(main_window,textvariable=pass_text)
pass_field.grid(column=1, row=1,padx=5,pady=5)
defmy_func():
text =""
ifemail_text.get()=="":
text ="Enter your email first"
else:
text ="Your email is:"+email_text.get()
my_button2.grid(column=0, row=2,columnspan=2,padx=5,pady=5)
main_window.mainloop()
Exercise 13.1
Question 1:
Answer: B
Question 2:
Answer: C Question 3:
Answer: A
Exercise 13.2
Create a random NumPy array of 5 rows and 4 columns.
Using array indexing and slicing, display the items from row
3 to end and column 2 to end.
Solution:
uniform_random=np.random.rand(4,5)
print(uniform_random)
print("Result")
print(uniform_random[2:,3:])