python notebook
python notebook
Python is one of the most popular and widely used programming language in nowadays, because
of its simplicity, extensive features and support of libraries. Python also have clean and simple
syntax which makes it beginner-friendly, while it also provides powerful libraries and
frameworks that makes it perfect for the developers.
What is Python?
print("Hello World!")
In Python, it is one line of code. It requires simple syntax to print 'Hello World'
Python provides many useful features to the programmer. These features make it the most
popular and widely used language. We have listed below few-essential features of Python.
I. Ease to use and Learn: Python has a simple and easy-to-understand syntax, unlike other
languages such as C, C++, Java, etc., which makes it easier for the beginners to learn.
III. GUI Programming Support: Python provides several GUI frameworks, such as Tkinter
and PyQt, which allows developers to create desktop application easily.
IV. Dynamic Memory Allocation: Python automatically manages memory allocation which
makes it easier for developers to write complex programs without worrying about
memory management.
V. Wide Range of Libraries and Frameworks: Python has a vast collection of libraries and
frameworks, such as NumPy, Pandas, Django, and Flask, that can be used to solve a wide
range of problems.
VI. Versatility: Python is a universal language in various domains such as web development,
machine learning, data analysis, scientific computing, and more.
1
Python is a general-purpose, popular programming language, and it is used in almost every
technical field. The various areas of Python use are given below.
Data Science: Data Science is a vast field, and Python is an important language for this
field because of its simplicity, ease of use, and availability of powerful data analysis and
visualization libraries like NumPy, Pandas, and Matplotlib.
Machine Learning: Python is also widely used for machine learning because of its
simplicity, ease of use and the availability of powerful machine learning libraries.
Data Analysis: Python is also used to create visualizations of data. It is also used to
analyze the price trends and market predictions and automate workflows across multiple
data sources.
Web Development: Python is used to develop websites and web applications. There are
several popular frameworks like Django and Flask which are used to build web
applications.
Python has wide range of libraries and frameworks widely used in various fields such as machine
learning, artificial intelligence, web applications, etc. We define some popular frameworks and
libraries of Python as follows.
BeautifulSoup: a library for web scraping and parsing HTML and XML
2
Pytest: a testing framework for Python Django
Streamlit: a library for building interactive web apps for machine learning and data science
Features of Python
From the development of Ada Lovelace's machine algorithm in 1843 to the latest and popular
high-level programming languages like C++, Python, and Java, a wide range of programming
languages have been developed by programmers in order to solve real-world challenging
problems. However, not every programming language stands out in the limelight. Every
programming language is dependent on their core features like accessibility, flexibility,
portability, responsibility, and a lot more. In simpler terms, the utility of any programming
language is considered using its essential features.
Python is a programming language freely available at the official website. One can download
and install it by clicking on the following link: Download Python. Python, being an open-source
programming language, allows users to access its source code available to the public. This source
code can be downloaded for usage as well as sharing purpose allowing users to contribute to the
Python community from around the world.
2. Easy to Learn and Code: Python is a high-level programming language that is quite easier to
learn when compared to other programming languages like C, Java, C#, JavaScript, etc. Python
offers a clean and simple syntax, similar to plain English making it easy for beginners to
comprehend and write programs quickly.
Example
Output:
In the above example, we can observe that a simple line of code prints a message on the screen.
3
3. Easy to Read: Python is an expressive language with quite straightforward syntax. The chunks
of code in Python are structured using the indentations making it exceptional programming
language when compared to other programming languages like C++ or Java.
5. Cross-Platform Compatibility: Python is also a portable language that can be run on different
operating systems (like Windows, MacOS, Linux, Unix) without any modification. This feature
of Python allows programmers to write and run any of its scripts on any platform without the
need to change anything.
6. Interpreted Language: Python is an interpreted language as it runs code line by line, rather
than compiling the complete code into machine code before execution. At first, Python
interpreter reads the Python source code and converts it into an immediate form called bytecode.
This bytecode is then executed by the Python virtual machine. This process makes debugging
much easier as the errors are detected quickly.
7. Dynamically Typed Language: Python is also a dynamically typed language allowing Python
to figure out the variable types (int, double, long, etc.) automatically at the run time, without the
need of declaring them manually.
Example
var_1 = 5
var_2 = 4.7
var_3 = "Welcome"
4
print("Value of var_2:", var_2)
Output:
Value of var_1: 5
Explanation:
In the above snippet of code, we have defined three different variables without declaring their
types. We have then printed their values along with their types. As a result, we can observe that
their types have been assigned automatically and correctly by Python itself.
10. GUI Programming Support: Python also provides an excellent support for the development
of Graphical User Interfaces (GUIs) through various libraries and frameworks.
Python plays a significant role in web development. With the use of simple tags like <py-script>,
<py-env>, etc., can be used to write and run Python codes in HTML, allowing programmers to
do front-end development work in Python with JavaScript. Python provides multiple frameworks
like Django and Flask to do back-end development.
12. Strong Community Support: Python has gained popularity over the year making it one of the
most favourable programming languages for multi-purpose development. This leads Python to
have a huge community around the world. There are multiple forums, documentations, and
5
tutorials available online in order to help user to learn and resolve any problems while
programming.
13. Extensive Libraries and Frameworks: Python has a huge collection of libraries and
frameworks, making development faster, easier and more efficient across different domains. This
feature of Python allows developers to mainly focus on solving problems and save their time
from writing everything from scratch.
14. Multiple Programming Paradigms Support: Python is a programming language that supports
multiple programming paradigms, which makes it a highly versatile and powerful language
15. Automatic Memory Management: Python offers automatic memory management, which
means developers do not require to allocate or deallocate memory manually. The memory
manager of Python handles object creation, memory allocation, garbage collection, and memory
optimization automatically. Let us take an example where we can see Python's automatic
memory management in act. Suppose that we have a Python program that manages user
accounts. Each time a user logs in, an object is created, and when they log out, the object is
automatically removed.
16. Multi-threading and Multiprocessing: Python allows multiple tasks to run at once. This
process is known as concurrency, and it can be achieved by the multi-threading and
multiprocessing features of Python.
Python Applications
1) Web Applications: We can use Python to develop web applications. It provides libraries to
handle internet protocols such as HTML and XML, JSON, Email processing, request,
beautifulSoup, Feedparser, etc. One of Python web-framework named Django is used on
Instagram. Python provides many useful frameworks, and these are given below:
2) Desktop GUI Applications: The GUI stands for the Graphical User Interface, which provides
a smooth interaction to any application. Python provides a Tk GUI library to develop a user
interface. Some popular GUI libraries are given below.
Tkinter or Tk
wxWidgetM
6
PyQt or Pyside
4) Software Development: Python is useful for the software development process. It works as a
support language and can be used to build control and management, testing, etc.
Buildbot and Apache Gumps are used for automated continuous compilation and testing.
5) Scientific and Numeric: This is the era of Artificial intelligence where the machine can
perform the task the same as the human. Python language is the most suitable language for
Artificial intelligence or machine learning. It consists of many scientific and mathematical
libraries, which makes easy to solve complex calculations.
SciPy
Scikit-learn
NumPy
Pandas
Matplotlib
7
Oddo is an example of the all-in-one Python-based application which offers a range of business
applications. Python provides a Tryton platform which is used to develop the business
application.
7) Audio or Video-based Applications: Python is flexible to perform multiple tasks and can be
used to create multimedia applications. Some multimedia applications which are made by using
Python are TimPlayer, cplay, etc. The few multimedia libraries are given below.
Gstreamer
Pyglet
QT Phonon
Fandango (Popular )
CAMVOX
9) Enterprise Applications: Python can be used to create applications that can be used within an
Enterprise or an Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.
10) Image Processing Application: Python contains many libraries that are used to work with the
image. The image can be manipulated according to our requirements. Some libraries of image
processing are given below.
OpenCV
Pillow
SimpleITK
With the rapid growth of Python in new technologies, it continues to define the future of
software development, which makes it an important skill in today's tech environment.
Let us start our journey with Python using a classic introductory program in almost every
programming language. It simply prints the text "Hello, World!" on the console.
8
Example
print("Hello, World!")
Output:
Hello, World!
Explanation:
In the above snippet of code, we have used print(), a built-in function in Python, to display
output to the user. "Hello, World!" is a string literal. It's the text we want to display, enclosed
within double quotes. The print() function takes this string as input and displays it.
Indentation: Python uses indentation in order to define code blocks. Unlike other programming
languages that make use of parentheses {} or keywords, Python uses proper indentation in the
form of spaces or tabs for the code to function correctly. Moreover, it also improves the
readability of the code.
Dynamic Typing: Python is dynamically typed language. This means that we are not required to
declare the data types of variables explicitly. For example, x = 10 is an integer, but assigning x =
"hello" later changes it to a string.
Virtual Environments: Python supports virtual environments (venv) which helps isolating the
dependencies for different projects. This also helps preventing package conflicts and ensuring
each project runs with the required library versions.
Extensive Library Support: Python offers a rich set of built-in libraries like math, itertools,
datetime, collections, and functools, enabling efficient problem-solving without reinventing the
wheel.
PEP 8: Python's official style guide promotes best practices such as meaningful variable names,
consistent indentation, proper spacing, and a 79-character line limit for better code readability
and maintainability.
Example
9
# simple program to print your name in Python
name = "Eren"
Output:
Explanation:
In the above example, we have defined a variable as name and initialized it with a value - "Eren".
We have then used the print() function to display the name for the users.
Example
# initializing variables
num_1 = 24
num_2 = 31
Output:
24 + 31 = 55
Explanation:
In the above program, we have defined two variables as num_1 and num_2, and initialized them
with the values - 24 and 31, respectively. We have then performed addition of these two
variables and stored their result in a third variable called sum. Finally, we have used the print()
function to display the output to the users.
10
Example 3: Taking Input from the Users
Example
Output:
Explanation:
In the above example, we have used the input() function. input() is a built-in function in Python
that waits for the user to type something and press Enter. We have added a prompt "Enter Your
Text: " in the input() function that is displayed to users, guiding them what to enter. We have
defined a variable as user_input to store the entered value from the user. We have then used the
print() function to display the entered text from the user..
Python Keywords
Every scripting language has designated words or keywords, with particular definitions and
usage guidelines. Python is no exception. The fundamental constituent elements of any Python
program are Python keywords.
Python keywords are unique words reserved with defined meanings and functions that we can
only apply for those functions. You'll never need to import any keyword into your program
because they're permanently present.
Python's built-in methods and classes are not the same as the keywords. Built-in methods and
classes are constantly present; however, they are not as limited in their application as keywords.
Assigning a particular meaning to Python keywords means you can't use them for other purposes
in our code. You'll get a message of SyntaxError if you attempt to do the same. If you attempt to
assign anything to a built-in method or type, you will not receive a SyntaxError message;
however, it is still not a smart idea.
11
Python contains thirty-five keywords in the most recent version, i.e., Python 3.8. Here we have
shown a complete list of Python keywords for the reader's reference.
False
await
else
import
pass
None
break
except
in
raise
True
Class e.t.c
We may wish to describe the code we develop. We might wish to take notes of why a section of
script functions, for instance. We leverage the remarks to accomplish this. Formulas, procedures,
and sophisticated business logic are typically explained with comments. The Python interpreter
overlooks the remarks and solely interprets the script when running a program. Single-line
comments, multi-line comments, and documentation strings are the 3 types of comments in
Python.
Our code is more comprehensible when we use comments in it. It assists us in recalling why
specific sections of code were created by making the program more understandable.
Aside from that, we can leverage comments to overlook specific code while evaluating other
code sections. This simple technique stops some lines from running or creates a fast pseudo-code
for the program.
12
Readability of the Code
Code
Output:
Everything following the # is omitted. As a result, we may put the program mentioned above in
one line as follows:
Code
print( 'This is not a comment' ) # this code is to show an example of a single-line comment
Output:
This program's output will be identical to the example above. The computer overlooks all content
following #.
13
Multi-Line Comments
Python does not provide the facility for multi-line comments. However, there are indeed many
ways to create multi-line comments.
In Python, we may use hashtags (#) multiple times to construct multiple lines of comments.
Every line with a (#) before it will be regarded as a single-line comment.
Code
# it is a
# comment
In this case, each line is considered a comment, and they are all omitted.
Because Python overlooks string expressions that aren't allocated to a variable, we can utilize
them as comments.
Code
We can observe that on running this code, there will be no output; thus, we utilize the strings
inside triple quotes(""") as multi-line comments.
Python Docstring
The strings enclosed in triple quotes that come immediately after the defined function are called
Python docstring. It's designed to link documentation developed for Python modules, methods,
classes, and functions together. It's placed just beneath the function, module, or class to explain
what they perform. The docstring is then readily accessible in Python using the __doc__
attribute.
Code
14
return x + y
print( add.__doc__ )
Output:
Python Variables
In Python, variables are essentially constructing blocks that allow developers to store, control,
and manage data efficaciously. A variable in Python is largely a symbolic name assigned to a
memory place in which data is stored. Unlike statically typed languages (together with C or
Java), Python is dynamically typed, which means variables no longer require specific
announcements of their type; the type is inferred at runtime primarily based on the assigned fee.
Python variables have several specific functions that make them incredibly easy and smooth to
use. Let's discover those key functions in detail.
1. No Need for Explicit Type Declaration: Python is not a strict language like C or Java, one
need not define a variable before using it, like we do in Java or C language. One need not define
the type of variable. It directly defines the type of variable based on the value that the users store
in it during the execution.
Example:
x = 10 # Integer
y = 3.14 # Float
15
Here, Python automatically detects x as an integer, y as a float, name as a string, and is_active as
a Boolean with no explicit type declaration.
2. Dynamically Typed: Python is a dynamically types language which indicates that one can
change the type of variable during the runtime also. One can change the variable types during the
execution without any problems or errors.
Example:
This flexibility helps Python developers to write concise and adaptable code. However, it also
calls for cautious management to keep away from accidental errors.
3. Memory Efficient (Variables Reference Objects, Not Raw Data): In Python, variables do not
store values directly. Instead, they act as references (or pointers) to objects in memory. When a
variable is assigned a value, it references an object in Python's memory space rather than storing
the actual raw data.
Example:
a = 10
If two unchangeable values are stored in two variable like numbers, strings or tuples, then python
will optimize the memory utilization of variable without duplicating the information and pointing
each variable to same object.
4. Easy Reassignment (Variables Can Hold Different Types): Python variables are not fixed to a
single data type. They can be reassigned to different types at any point during program
execution.
Example:
x = 42 # x is an integer
16
x = [1, 2, 3] # x is now a list
Advantage:
This makes Python enormously flexible for fast improvement and prototyping.
Disadvantage:
This can cause unexpected errors so that type checking can be needed.
5. Used for Storing Values, Objects, and Complex Data Structures: The language Python is store
variable from simple data type like strings and integers to more complex data types like lists,
dictionaries, sets and many more user defined objects.
a = 2.34566 # Float
This feature made python to be used in many advanced technologies like data science, web
development, machine learning and many more.
Variable Declaration: In python, one need not define the variable at the beginning before storing
a value in it like they do in other programming languages. Simply using the assignment operator
(=) is sufficient.
Syntax:
variable_name = value
Example:
17
height = 5.6 # A float variable
Key Points:
Python automatically detects the data type based on the value assigned.
Variables can preserve distinct data types consisting of integers, floats, strings, lists, and more.
Python follows certain rules and best practices for naming variables:
The names of the variables have to start with a letter (A-Z or a-z) or an underscore (_)
Reserved Python keywords cannot be used as variable names (class, def, return, etc.)
my_variable = 10
_name = "Alice"
variable_123 = 42
CamelCaseVariable = "Hello"
18
Bad: x, a1, var1
Python supports multiple data types for variables. The type of a variable is automatically
determined when a value is assigned.
Data Type
int
Integer values
x = 10
float
Decimal values
y = 3.14
str
Text (string)
name = "Alice"
bool
Boolean values
is_active = True
Assigning Multiple Variables in Python: Python makes the code extra readable and efficient by
adding this feature of assigning more than one variable at once. Let's discover the multiple
methods to access more than one variable assigned in Python.
Python allows assigning more than one variable in a single line via isolating them with commas.
This is frequently known as tuple unpacking, though parentheses are optionally available.
Syntax:
Example
19
a, b, c = 110, 120, 130
Output:
10 20 30
Explanation:
In first line, the values 110, 120, and 130 are assigned to a, b, and c.
Advantages:
In Python, it's very important to know the scope and lifetime of variables, in order to know them
one has to understand the concept of local and global variables. These variables differ in where
and how they are being accessed. Let's go deeper into the concepts and understand how exactly
these variables work.
1. Local Variables in Python: A local variable is defined inside a function and can be accessed
inside that function.
Once the characteristic execution ends, the local variable is destroyed and is now not handy.
Characteristics:
Example
def my_function():
print(local_var)
20
my_function()
# print(local_var) # Uncommenting this line will raise an error because local_var is not
accessible outside the function.
Output:
I'm local
Explanation:
When you attempt to print local_var outside the function, Python will boost a NameError
because local_var isn't always defined inside the global scope.
2. Global Variables in Python: A global variable is defined outside the function and can be
accessed with the aid of any part of this program.
Global variables can be used across distinctive functions, and their values persist at some stage in
the program execution.
Characteristics:
Example
def display():
Output:
I'm global
Explanation:
21
The display() function can access and print the global variable global_var even though it is
defined outside the function.
This suggests that global variables are accessible globally across the program.
In Python, kind conversion (or kind casting) refers to the process of changing one data type into
another. Python helps with each implicit and explicit type of conversion, which allows flexibility
in dealing with variables of various types.
1. Implicit Type Conversion (Automatic Type Conversion): Implicit type conversion, also called
automatic kind conversion, occurs when Python automatically converts one data type to any
other without explicit instruction from the programmer. This happens when you perform
operations on compatible data types, and Python guarantees that the operation executes
smoothly.
How It Works:
Python automatically promotes smaller or much less specific types to large or more precise ones.
For instance, if you upload an int to a float, Python automatically converts the int to a float to
avoid data loss.
Example
a = 10 # int
b = 2.5 # float
Output:
Explanation:
When a+b is done, Python will convert the integer data type "a" to a data type float so that the
addition will be done inside the float data type only.
As a result, the variable c holds a data type float value (12.5), and its type is <class 'float'>.
22
Python best performs implicit conversions between compatible types (e.g., int to float, int to
complex).
Implicit conversion does not show up, but it can bring a loss of precision or data (e.g., converting
a float to an int automatically).
2. Explicit Type Conversion (Manual Type Conversion): Explicit type conversion, additionally
known as manual type casting, takes place when you use Python's built-in function to convert a
variable from one type to another. You must specify the type you want to convert a variable into.
Example
x = "100" # string
Output:
Explanation:
After conversion, y holds the integer value 100, and its type is <class 'int'>.
1. __name__ Variable:
23
A special integrated variable that stores the name of the current module that the user is working
on, in python is _name_ variable. When one runs a Python file, the value of __name__ is set to
"__main__" , if the file is executed without any delay. If the file is imported as a module from
another script, __name__ is set to the module's name. This feature gives us a difference when
running a script without any delay and uploading the script as a part of another program.
2. __main__ Block:
A common Python idiom that is used commonly is The if __name__ == "__main__": block is
used to check whether the script is being run immediately (as opposed to imported). When the
script will be run without delay then only the code that is inside this block will be executed. This
will be useful for writing code that may function both as a standalone script and as a reusable
module.
Example:
if __name__ == "__main__":
else:
In Python, one can delete a variable using the del keyword. Once a variable is deleted, it gets
eliminated from the memory, and attempting to get access to it afterward will raise an error.
Example:
x = 100
del x
The variable x is assigned a value of 100, and then del x removes it from memory.
Trying to print x after deletion will raise a NameError because the variable no longer exists.
24
Every value has a datatype, and variables can hold values. Python is a powerfully composed
language; consequently, we don't have to characterize the sort of variable while announcing it.
The interpreter binds the value implicitly to its type.
a=5
We did not specify the type of the variable a, which has the value five from an integer. The
Python interpreter will automatically interpret the variable as an integer.
We can verify the type of the program-used variable thanks to Python. The type() function in
Python returns the type of the passed variable.
Consider the following illustration when defining and verifying the values of various data types.
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
A variable can contain a variety of values. On the other hand, a person's id must be stored as an
integer, while their name must be stored as a string. The storage method for each of the standard
data types that Python provides is specified by Python. The following is a list of the Python-
defined data types.
Numbers
Sequence Type
Boolean
25
Set
Dictionary
Numbers: Numeric values are stored in numbers. The whole number, float, and complex
qualities have a place with a Python Numbers datatype. Python offers the type() function to
determine a variable's data type. The instance () capability is utilized to check whether an item
has a place with a specific class.
When a number is assigned to a variable, Python generates Number objects. For instance,
a=5
b = 40.5
c = 1+3j
Output:
Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and so on.
An integer can be any length you want in Python. Its worth has a place with int.
Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to
within 15 decimal places.
Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y signify
the genuine and non-existent parts separately. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.
Sequence Type
26
String: The sequence of characters in the quotation marks can be used to describe the string. A
string can be defined in Python using single, double, or triple quotes. String dealing with Python
is a direct undertaking since Python gives worked-in capabilities and administrators to perform
tasks in the string. When dealing with strings, the operation "hello"+" python" returns "hello
python," and the operator + is used to combine two strings. Because the operation "Python" *2
returns "Python," the operator * is referred to as a repetition operator.
Example - 1
print(str)
s = '''''A multiline
string'''
print(s)
Output:
A multiline
string
Example - 2
Output:
he
27
o
List: Lists in Python are like arrays in C, but lists can contain data of different types. The things
put away in the rundown are isolated with a comma (,) and encased inside square sections []. To
gain access to the list's data, we can use slice [:] operators. Like how they worked with strings,
the list is handled by the concatenation operator (+) and the repetition operator (*).
Example:
print(type(list1))
print (list1)
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
print (list1 * 3)
Output:
[2]
[1, 'hi']
28
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
Tuple: In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items
from various data types. A parenthetical space () separates the tuple's components from one
another. Because we cannot alter the size or value of the items in a tuple, it is a read-only data
structure.
Example:
print (type(tup))
print (tup)
# Tuple slicing
print (tup[1:])
print (tup[0:1])
print (tup * 3)
t[2] = "hi"
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
29
('hi',)
t[2] = "hi";
Dictionary: A dictionary is a key-value pair set arranged in any order. It stores a specific value
for each key, like an associative array or a hash table. Value is any Python object, while the key
can hold any primitive data type.
The comma (,) and the curly braces are used to separate the items in the dictionary.
# Printing dictionary
print (d)
print (d.keys())
print (d.values())
Output:
dict_keys([1, 2, 3, 4])
30
dict_values(['Jimmy', 'Alex', 'john', 'mike'])
Boolean: True and False are the two default values for the Boolean type. These qualities are
utilized to decide the given assertion valid or misleading. The class book indicates this. False can
be represented by the 0 or the letter "F," while true can be represented by any value that is not
zero.
print(type(True))
print(type(False))
print(false)
Output:
<class 'bool'>
<class 'bool'>
Set: The data type's unordered collection is Python Set. It is iterable, mutable(can change after
creation), and has remarkable components. The elements of a set have no set order; It might
return the element's altered sequence. Either a sequence of elements is passed through the curly
braces and separated by a comma to create the set or the built-in function set() is used to create
the set. It can contain different kinds of values.
set1 = set()
print(set2)
set2.add(10)
print(set2)
31
#Removing element from the set
set2.remove(2)
print(set2)
Output:
Decision making is the most important aspect of almost all the programming languages. As the
name implies, decision making allows us to run a particular block of code for a particular
decision. Here, the decisions are made on the validity of the particular conditions. Condition
checking is the backbone of decision making.
If Statement: The if statement is used to test a specific condition. If the condition is true, a block
of code (if-block) will be executed.
If - else Statement: The if-else statement is similar to if statement except the fact that, it also
provides the block of the code for the false case of the condition to be checked. If the condition
provided in the if statement is false, then the else statement will be executed.
Nested if Statement: Nested if statements enable us to use if ? else statement inside an outer if
statement.
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block. If two
statements are at the same indentation level, then they are the part of the same block.
Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python. Indentation is the most used part of the python language since it declares
the block of code. All the statements of one block are intended at the same level indentation. We
will see how the actual indentation takes place in decision making and other stuff in python.
32
The if statement The if statement is used to test a particular condition and if the condition is true,
it executes a block of code known as if-block. The condition of if statement can be any valid
logical expression which can be either evaluated to true or false.
if expression:
statement
Example 1
if num%2 == 0:
# Here, we are checking the condition. If the condition is true, we will enter the block
Output:
# Here, we are checking the condition. If the condition is true, we will enter the block
33
# Here, we are checking the condition. If the condition is true, we will enter the block
# Here, we are checking the condition. If the condition is true, we will enter the block
Output:
Enter a: 100
Enter b: 120
Enter c: 130
The if-else statement provides an else block combined with the if statement which is executed in
the false case of the condition.
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
if condition:
#block of statements
else:
if age>=18:
34
# Here, we are checking the condition. If the condition is true, we will enter the block
else:
Output:
if num%2 == 0:
# Here, we are checking the condition. If the condition is true, we will enter the block
else:
Output:
The elif statement: The elif statement enables us to check multiple conditions and execute the
specific block of statements depending upon the true condition among them. We can have any
number of elif statements in our program depending upon our need. However, using elif is
optional.
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.
if expression 1:
35
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example 1
if number==10:
# Here, we are checking the condition. If the condition is true, we will enter the block
elif number==50:
# Here, we are checking the condition. If the condition is true, we will enter the block
elif number==100:
# Here, we are checking the condition. If the condition is true, we will enter the block
else:
Output:
36
Enter the number?15
Example 2
# Here, we are checking the condition. If the condition is true, we will enter the block
# Here, we are checking the condition. If the condition is true, we will enter the block
# Here, we are checking the condition. If the condition is true, we will enter the block
# Here, we are checking the condition. If the condition is true, we will enter the block
else:
Output:
Python Loops
37
The following loops are available in Python to fulfil the looping needs. Python offers 3 choices
for running the loops. The basic functionality of all the techniques is the same, although the
syntax and the amount of time required for checking the condition differ.
We can run a single statement or set of statements repeatedly using a loop command.
The following sorts of loops are available in the Python programming language.
Sr.No.
While loop: Repeats a statement or group of statements while a given condition is TRUE. It
tests the condition before executing the loop body.
For loop: This type of loop executes a code block multiple times and abbreviates the code
that manages the loop variable.
Statements used to control loops and change the course of iteration are called control statements.
All the objects produced within the local scope of the loop are deleted when execution is
completed.
Break statement: This command terminates the loop's execution and transfers the program's
control to the statement next to the loop.
Continue statement: This command skips the current iteration of the loop. The statements
following the continue statement are not executed once the Python interpreter reaches the
continue statement.
Pass statement: The pass statement is used when a statement is syntactically necessary, but no
code is to be executed.
Tuple is one of the four primary data types in Python. It is a used for storing a collection of
objects. A tuple is quite similar to a Python list in terms of indexing, nested objects, and
repetition; however, the main difference between both is that the tuples in Python are immutable,
unlike the Python list which is mutable.
38
The following is an example of a tuple.
Example:
Tuples are an immutable data type, implying that the data elements of this data type cannot be
changed after they are generated. Each data element in a tuple has a particular order that never
changes as the tuples are ordered sequences.
Forming a Tuple:
Let us consider the following example demonstrating the inclusion of different data types in a
tuple:
Code:
emptyTuple = ()
39
nestedTuple = ("Javatpoint", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
Output:
Empty tuple: ()
Explanation:
In the above snippet of code, we have created four different tuples containing different types of
elements. The first tuple is an empty tuple defined using the parentheses with no element in
between. After that, we have defined an integer tuple consisting of 6 integer values between the
parentheses separated by the commas. The third tuple is comprised of three objects of different
data types – integer, string, and float. At last, we have defined a tuple as a different object,
including another tuple. Moreover, it is not necessary to declare and initialize a tuple using the
parentheses. Let us consider the following example demonstrating the same.
Code:
# Creating a tuple
print(tupleWithoutParentheses)
print(type(tupleWithoutParentheses) )
try:
tupleWithoutParentheses[1] = 9.5
except:
40
print("TypeError: Tuples are immutable data types and cannot be modified.")
Output:
<class 'tuple'>
Explanation:
In the above snippet of code, we have defined a tuple containing several elements separated by
the commas, without the use of parentheses and printed it for the users. For better clarity, we
have returned its type using the type() method. We have also tried modifying the element of the
tuple using the try and except blocks. As a result, the first line displays the elements of the
tuples. The second line displays the type of the variable which is 'Tuple'. At last, we can observe
a TypeError implying the immutability of the tuples.
The Python built-in functions are defined as the functions whose functionality is pre-defined in
Python. The python interpreter has several functions that are always present for use. These
functions are known as Built-in Functions. There are several built-in functions in Python which
are listed below:
The python abs() function is used to return the absolute value of a number. It takes only one
argument, a number whose absolute value is to be returned. The argument can be an integer and
floating-point number. If the argument is a complex number, then, abs() returns its magnitude.
# integer number
integer = -20
# floating number
floating = -20.83
Output:
41
Absolute value of -20 is: 20
The python all() function accepts an iterable object (such as list, dictionary, etc.). It returns true if
all items in passed iterable are true. Otherwise, it returns False. If the iterable object is empty, the
all() function returns True.
k = [1, 3, 4, 6]
print(all(k))
k = [0, False]
print(all(k))
k = [1, 3, 7, 0]
print(all(k))
k = [0, False, 5]
print(all(k))
# empty iterable
k = []
print(all(k))
Output:
True
42
False
False
False
True
The python bin() function is used to return the binary representation of a specified integer. A
result always starts with the prefix 0b.
x = 10
y = bin(x)
print (y)
Output:
0b1010
Python bool()
The python bool() converts a value to boolean(True or False) using the standard truth testing
procedure.
test1 = []
print(test1,'is',bool(test1))
test1 = [0]
print(test1,'is',bool(test1))
test1 = 0.0
print(test1,'is',bool(test1))
test1 = None
print(test1,'is',bool(test1))
43
test1 = True
print(test1,'is',bool(test1))
print(test1,'is',bool(test1))
Output:
[] is False
[0] is True
0.0 is False
None is False
True is True
As the name says, python sum() function is used to get the sum of numbers of an iterable, i.e.,
list.
s = sum([1, 2,4 ])
print(s)
print(s)
Output:
17
Python help() function is used to get help related to the object passed during the call. It takes an
optional parameter and returns help information. If no argument is given, it shows the Python
help console. It internally calls python's help function.
44
Python help() Function Example
# Calling function
# Displaying result
print(info)
Output:
Python Modules
Modular programming is the practice of segmenting a single, complicated coding task into
multiple, simpler, easier-to-manage sub-tasks. We call these subtasks modules. Therefore, we
can build a bigger program by assembling different modules that act like building blocks.
Simplification: A module often concentrates on one comparatively small area of the overall
problem instead of the full task. We will have a more manageable design problem to think
about if we are only concentrating on one module. Program development is now simpler and
much less vulnerable to mistakes.
Flexibility: Modules are frequently used to establish conceptual separations between various
problem areas. It is less likely that changes to one module would influence other portions of
the program if modules are constructed in a fashion that reduces interconnectedness. (We
might even be capable of editing a module despite being familiar with the program beyond
it.) It increases the likelihood that a group of numerous developers will be able to collaborate
on a big project.
Scope: Modules often declare a distinct namespace to prevent identifier clashes in various
parts of a program.
In Python, modularization of the code is encouraged through the use of functions, modules, and
packages.
45
What are Modules in Python?
A document with definitions of functions and various statements written in Python is called a
Python module.
A built-in module, such as the itertools module, is inherently included in the interpreter.
We employ modules to divide complicated programs into smaller, more understandable pieces.
Modules also allow for the reuse of code.
Rather than duplicating their definitions into several applications, we may define our most
frequently used functions in a separate module and then import the complete module.
In Python, we may import functions from one module into our program, or as we say into,
another module. For this, we make use of the import Python keyword. In the Python window, we
add the next to import keyword, the name of the module we need to import. We will import the
module we defined earlier example_module.
46
Class: The class can be defined as a collection of objects. It is a logical entity that has some
specific attributes and methods. For example: if you have an employee class, then it should
contain an attribute and method, i.e. an email id, name, age, salary, etc.
Syntax
class ClassName:
<statement-1>
<statement-N>
Object: The object is an entity that has state and behavior. It may be any real-world object
like the mouse, keyboard, chair, table, pen, etc. Everything in Python is an object, and
almost everything has attributes and methods. All functions have a built-in attribute
__doc__, which returns the docstring defined in the function source code.
When we define a class, it needs to create an object to allocate the memory. Consider the
following example.
Example:
class car:
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
Output:
Toyota 2016
47
In the above example, we have created the class named car, and it has two attributes modelname
and year. We have created a c1 object to access the class attribute. The c1 object will allocate
memory for these values. .
Method: The method is a function that is associated with an object. In Python, a method is
not unique to class instances. Any object type can have methods.
Polymorphism: Polymorphism contains two words "poly" and "morphs". Poly means many,
and morph means shape. By polymorphism, we understand that one task can be performed
in different ways. For example - you have a class animal, and all animals speak. But they
speak differently. Here, the "speak" behavior is polymorphic in a sense and depends on the
animal. So, the abstract "animal" concept does not actually "speak", but specific animals
(like dogs and cats) have a concrete implementation of the action "speak".
Data Abstraction: Data abstraction and encapsulation both are often used as synonyms. Both
are nearly synonyms because data abstraction is achieved through encapsulation. Abstraction
is used to hide internal details and show only functionalities. Abstracting something means
to give names to things so that the name captures the core of what a function or a whole
program does.
48