Python
Python
Python is a high-level general purpose language, and it is widely used for web development,
Machine learning, Data Science, Data Analytics, Testing and many more. It is being used for
many purposes so it is called “General purpose language”.
It was created by Gudio van Russam in the early 1980’s and further developed by Python
Software Foundation.
Python Installation:
We can install python from python.org by downloading the latest version of it. We can set
python path while installing or after installation also.
Python Path:
C:\Program Files\Python311\Scripts\
C:\Program Files\Python311\
We need to set both the paths in Environment variables.
Once We complete the installation, to check python installed or not
C:/> python - -version
To start python shell
C:/>py
>>>print(“Hello Naresh”)
❖ To verify python path in linux is
➢ $which python3
Once we install python, we need to check whether the pip has been installed or not by using
the below command.
Pip is an acronym of “Preferred Installer Program”, Pip installs packages to python library.
C:/> pip - -version
Later, we need to install the list of libraries using the commands below.
Once installation of numpy is completed, to check whether the library is installed or not.
C:/> python
>>>import numpy as np
If we don’t get any error means it is installed successfully.
Ex:
>>>import numpy as np
>>>a=np.array([[1,2,3],[5,7,9],[10,15,21]],dtype = ‘float’)
>>>print(“Array Created is \n”, a)
In the above example, np is an object of numpy library we can give any name instead of np.
plt.plot(xpoints, ypoints)
plt.show()
Output:
What is Anaconda?
Anaconda Python is a free, open-source platform that allows you to write and execute code in
the programming language Python.
Python Advanced concepts:
OOP (Object Oriented Programming)
Methods
Functional Programming
Inheritance
Decorators
Lambda Functions
Classes
Regular Expressions
Github
>>>name=”Naresh”
>>>type(name)
<class ‘str’>
We don’t need to define variables separately of which type. Python will take care of the data
type once we provide the data to a variable.
❖ There are several ways to write variable names
➢ Camel Case
➢ Pascal Case
➢ Snake Case
❖ A variable should start its name with a letter or with an underscore(“_”) and cannot
start with numbers.
➢ There are two types of assigning values to variable:
■ Assigning single value
>>>a=10
>>>name=”Naresh”
■ Assigning multiple values.
>>>a=b=c=10
>>>x,y,z=10,20,”Naresh”
>>>type(a)
Int
>>>type(z)
Str
>>>id(Variable_Name)
Returns a unique identification number of a variable.
❖ Object referencing
x=y=z=10
Here python won’t allocate a value of 10 to each of the three variables, all three variables are
referencing the object “10”.
Tokens:
A Token is a smallest individual unit of a python program. All statements and instructions in
a program are built with tokens. If anything we write in python that will come under any one
of these tokens. Various type of tokens are there:
1. Keywords
2. Identifiers
3. Literals
4. Operators
Operators: Operators are special symbols that are used to carry out Arithmetic and logical
Operations. Various types of operators are:
❖ Arithmetic (+,-, *, /, %)
A+b, a-b, c/d
❖ Assignment (=, +=, -=, *=, /=, |=)
A=10,
x+=2 which means x=x+2
❖ Bitwise
These are used to compare binary numbers.
& AND
| OR
^ XOR
~ NOT
<< LEFT SHIFT
>> RIGHT SHIFT
❖ Identity
❖ Membership
Keywords:
❖ Python keywords are special reserved words. They have some specific task.
❖ They convey a special meaning to the interpreter.
❖ Each keyword has a special meaning and operation.
❖ We never use these keywords as variables.
Ex: print, int, float etc
Python keywords are :
Identifiers:
An identifier is the name used to identify a variable, function, class or an object, whereas a
variable is a name that points to a memory location.
Especially, identifiers used within the function or incremental value in loop controls etc. where
we don’t store a value particularly.
Rules:
❖ No special char is used except underScore( _ ), can be as an identifier
❖ Keywords should not be used as identifiers
❖ Python is case sensitive, “Var” and “var” both refer to different identifiers
❖ The first char can be an alphabet or can be underscore ( _ ) but not any other digit or
symbol.
Example:
Var = 7
Here Var is an identifier.
Literals:
A Literal is a raw data given to a variable.
Types:
String Literals :
name1= “Naresh” print(name1)
name1=’Naresh’ print(name1)
text1=’hello\ print(text1)
World’
multiline=’’’st1 print(multiline)
St2
st3’’’
Numeric Literals
Boolean Literals : Boolean values (True or False)
Special Literals : There is a special literal called “None”, in other programming languages it is
called NULL.
Jupyter Notebook
Visual Studio
Sublime Text
Py Charm
IDLE
Spyder Notebook
Data Types in python:
We have two types of data types in python.
Numbers:
❖ To know the length of a string
❖ >>>len(stringName)
❖ To know the part of a string it is called slicing by using slicing operator( “ : “)
➢ >>>string[position]
➢ Ex: >>> str=”abcdefghi”
>>>str[5]
It will return 5th character starting from ‘0”
>>>str[1:4]
O/P: bcd
Str[:5]
O/P: abcde
>>>str[4:]
O/P: fghi
>>>str[:-1]
O/P : abcdefgh
>>>str[:-2]
O/P : abcdefg
❖ To replace a string
>>>str.replace(‘f’,’g’)
O/P: abcdegghi
❖ The advantage of the tuple is immutable, means once the value is assigned to a tuple
then the reassignment of the variable value is not allowed.
➢ For ex: for a tuple named “weeks” below are the reassignment tries.
➢ Tuples are assigned using brackets or without brackets. They way of assigning
tuples is shown in below example image.
Lists:
❖ Lists are also same as tuples but the major difference is, Lists are immutable
means we can change the value of Lists.
❖ Lists are assigned using square brackets (“ [ ] “)
❖ We can append other values to the lists also using the append function.
❖ We can store different type of values to it also, like student details
❖ We can store list inside a list also, it is called nested list.
Dictionaries :
❖ Dictionaries are unordered collection of items, we can create (key,value) pairs using
Dictionary
❖ We can access the value by calling it’s key.
❖ Dictionaries are assigned by using “{ }”.
❖ We can access the value of a key which is not available in the dictionary also, because
if we want to search by a key, which is available or not we don't know, at that time we
can try like below, if the key is not available it will display the value which we have
given otherwise it will display the value from the dictionary.
❖ Set is also an unordered collection of data but the values in it are distinct. The Set will
not store duplicate values in it.
❖ There are two ways to create sets.
Arithmetic Operators:
A natural thing to want to do with numbers is perform arithmetic. We've seen the + operator
for addition, and the * operator for multiplication. Python also has us covered for the rest of
the basic buttons on your calculator:
Indexing in Python:
❖ Indexing in python is a way to refer to individual items in an iterable variable by its
position.
❖ In other words, we can directly access the individual elements of our choice by using
index. In python, we give the index by using square brackets ( “[ ] “).
❖ In python, index will starts with 0th Position.
NARESH
012 3 4 5
If we want to add any space,tab or new line between the strings we can specify like below
example.
We can concatenate ‘n’ number of strings using “+” Operator and we can add any special
character in between them.
❖ If want to assign multi line string to a variable, we can do by using Triple Quotes.
Below example shows it.
We have many built-in string functions in python, some of them are below;
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs()Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where
it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of
where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of
where it was found
rindex() Searches the string for a specified value and returns the last position of
where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
➔ If we want to allocate multiple values at runtime also we can do it by using map() and split()
functions. We can observe the functionality below.
Note: We can pass any separator in split() function like below, I have passed “,” as separator.
Note: Here “f” will be used to format that inside the print statement there is a need to pass a
value and it is defined as “ {name}”.
➔ We can pass multiple values within the print statement using format() function.
a,b=10,20
print(“value of a ={},b={}”.format(a,b))
➔ We can pass the multiple values by using their index also using format() function. Usually
index numbers in format() will start from Zero(0).
We can pass variable within print using format() function also
Function Description
Some of the important math functions from above list are demonstrated below.
Binary number Operations:
How to convert number to binary
-ve Binary number representation
Data Structures in Python
Overview
The data structures in python are a meaningful way of arranging, and storing the data in the
computer for efficient utilization and processing depending upon the situation.
The data structures in python are nothing but a meaningful way of arranging, and storing the
data in the computer for efficient utilization and processing depending upon the situation.
The data structure is one of the most fundamental topics of any programming language. The
data structures in python language can be broadly divided into two categories.
Primitive data structures are also called built-in data types (int, float, string, boolean), where
we can store only one type of data.
The main difference between primitive and non-primitive DS is, we can store only one
particular type of data in Primitive types whereas we can store different types of data at a
type in Non-Primitive DS.
We have four built-in (general) data structures in python namely - lists, dictionaries, tuples,
and sets. Apart from these, we have some user-defined data structures in python like stacks,
queues, trees, linked lists, graphs, hashmaps. Let us broadly discuss data structures in
python, the types of data structures in python in detail.
Types of Data Structures in Python
As we have discussed, the data structures in python can be broadly divided into two
categories, the first one being the built-in data structures in python, and the second one being
user-defined data structures in python. The data structures in Python are:
● List in Python - The Lists is a built-in data structures in python that stores the data in
the sequential form. Lists can be treated as dynamic arrays. List data structures in
python can contain duplicate elements as each element is identified by a unique
number/ position known as an index. The list in python provides a wide variety of
methods and functions. We can put heterogeneous type values inside the lists. The
most common associated methods of lists are list(), append(), insert(), extend(), sort(),
reverse(), remove(), pop(), clear() etc.
❖ Lists are also the same as tuples but the major difference is, Lists are immutable
means we can change the value of Lists.
❖ Lists are assigned using square brackets (“ [ ] “)
❖ We can append other values to the lists also using the append function.
❖ We can store heterogeneous types of data in Lists
❖ The indexing in the list starts from “Zero(0)” to and so on.
❖ We can do Positive and Negative indexing.
❖ Positive indexing is also called Forward Indexing, starts from “0”
❖ Negative indexing is also called Backward Indexing, starts from -1.
❖ We can store different type of values to it also, like student details
❖ We can store list inside a list also, it is called nested list.
We can access the data from the list using positive and negative indexing also.
We can create a list by using range(), and we need to use list() function for typecasting.
We can add values to the existing list using append(), insert() functions.
-> By using append(), we can add an element to the existing list at the end of the list
and we can add only one item at a time.
-> By using insert(), we can add an element at our favorite position.
By using extend(), we can add multiple elements to the existing list at a time.
-> we can merge one list to another list or we can give elements at a time.
-> To remove elements from the list, we need to use remove() to remove the elements and
we need to pass either index or the exact value inside the remove().
-> By using pop(), we can remove the last element from the list
-> we can also apply indexing and slicing techniques on the list.
-> If we want to reverse the order of elements in a list, we use reverse() or we can use reverse
indexing also.
-> If we want to sort the elements in a list, we use sort().
-> If we want to clear the elements in a list, we use clear().
-> If we want to count the no’of occurrences of a particular element in the list, we use
count(x) and we need to pass list element.
Ex: Write a python program to create a list of squares of 1 to 10, odd number squares 1 to
10.
List Comprehension:
One of the language’s most distinctive features is the list comprehension, which you can use
to create powerful functionality within a single line of code. However, many developers
struggle to fully leverage the more advanced features of a list comprehension in Python.
Some programmers even use them too much, which can lead to code that’s less efficient and
harder to read.
Python List comprehension provides a much more short syntax for creating a new list based
on the values of an existing list.
Which means, we can write a single line of code and create a list by this technique.
In the above example we have written code to create a list of odd number squares between 1
to 10, it has 5 lines. Below is the code by using list comprehension for the same in one line.
● Dictionary in Python - The dictionary is also a built-in data structures in python that
stores data in the form of key-value pairs. The dictionary data structures in python
have an attribute called the “key”. The key is the attribute that helps us locate the data
or value in the memory. The dictionary in python provides a wide variety of methods
and functions. The keys are always unique within a dictionary. The values of the
Python dictionary may or may not be unique. We can put heterogeneous type values
inside the dictionaries. The most common associated methods of dictionaries are get(),
keys(), values(), items(), update(), pop(), clear() etc.
❖ Dictionaries are unordered collection of items, we can create (key,value) pairs using
Dictionary
❖ We can access the value by calling it’s key.
❖ Dictionaries are assigned by using “{ }”.
❖ We can access the value of a key which is not available in the dictionary also, because
if we want to search by a key, which is available or not we don't know, at that time we
can try like below, if the key is not available it will display the value which we have
given otherwise it will display the value from the dictionary.
Sets:
❖ Set is also an unordered collection of data but the values in it are distinct. The Set will
not store duplicate values in it.
❖ There are two ways to create sets.
2. User-Defined Data Structures
● Stack in Data Structure - Stack is not a built i- data structures in python. Stack is a
user-defined data structures in python that are used to store data in the Last In First
Out (LIFO) manner. In stacks, the insertion and deletion are done at one end, where the
end is generally called the top. Since the last element inserted is served and removed
first, the stack data structures in python are also known as the Last Come First Served
data structure. The most common associated method of stacks are push(), pop(),
peek(), isEmpty(), isFull(), size() etc.
● Queue in Python - Queue is also not a built-in data structures in python. The queue is a
user-defined data structure in python that is used to store data in the First In First Out
(FIFO) manner. In queues, the insertion and deletion are done at different ends, where
the insertion is done at the rear end and the deletion is done at the front end. So, the
data which is inserted first will be removed from the queue first. Since the first element
inserted is served and removed first, the queue data structures in python are also
known as the First Come First Served data structure. The most common associated
method of queues are enqueue(), dequeue(), front(), rear(), empty() etc.
● Tree Data Structure - Tree is also not a built-in data structures in python. A tress can
be defined as a collection of objects or elements or entities known as nodes. These
nodes are linked together to represent a hierarchy. The top node of the hierarchy is
known as the root node. In trees, each node contains some data and also contains
references to its child node(s). A root node can never have a parent node. the nodes
that do not have any child nodes are termed leaf nodes. A tress can be of various types
such as a binary tree, binary search tree, AVL tree, Red-Black tree, etc.
● Linked List - Linked List is also not a built-in data structures in python. A linked list is a
linear structure of data consisting of nodes. Each node of a linked list contains some
data and also contains references (pointer to address) to the next node. The first node
of a linked list is called the Head node, which helps us to access the entire linked list.
The last node of the linked list is called the Tail node, which resembles or marks the
end of the linked list. Since the last node marks the end of the linked list, it points to a
NULL value or None! A linked list can be of various types such as singly linked list,
doubly linked list, circular linked list, doubly circular linked list, etc.
● Graph Data Structure - Graph is also not a built-in data structures in python. A graph is
a non-linear structure of data consisting of nodes that are connected to other nodes of
the graph. The node of the graph is also known as vertex (V). A node can represent
anything such as any location, port, houses, buildings, landmarks, etc. They are
anything that we can represent to be connected to other similar things. Edges (E) are
used to connect the vertices. The edges represent a relationship between various
nodes of a graph. A graph can be of various types such as a directed graph, undirected
graph, directed acyclic graph, directed cyclic graph, etc.
Indentation:
In python, indentation is very important, if we wanted to execute some block of statements
like if, if-else etc.. we are giving indentation to execute the block of statements if the condition
is true.
When defining a module, function, class, or method in Python we have to explain what the
code is. In such situations, you use Docstrings to help anyone using the code or working on the
code understand it better.
def findfactorial(num):
"""
This function takes input num which is an integer and finds the factorial of the number
"""
factorial = 1
if num < 0:
print(f" {num} is negative and negative numbers do not have factorials")
elif num == 0:
print(f"The factorial of {num} is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print(f"The factorial of {num} is {factorial}")
num=int(input("enter a number\n"))
findfactorial(num)
Output:
enter a number
5
The factorial of 5 is 120
Output:
please enter your name
apple
please enter your age
20
your name is apple and your age is 20
The example above shows how comments are written in python. You will notice that the
comment is not visible when the code is executed.
There may be situations when comment text does not fit into one line, in such cases you use
multi-line comments. Multi-line comments can be written using two methods:
Just like in single-line comments, you can use the hashtag to write multi-line comments. Each
time you start a new comment you add a hashtag at the beginning.
Example of multi-line comments using hashtag:
#swapping two numbers
#store first number in input a
#store second number in input b
#set temp =a
#set a=b
#set b=temp
a=100
b=200
print(f"the value of a is {a} and the value of b is {b}",sep="\n")
temp=a
a=b
b=temp
print(f"the value of a is {a} and the value of b is {b}",sep="\n")
Output:
the value of a is 100 and the value of b is 200
the value of a is 200 and the value of b is 100
The example above shows the use of a hashtag to write comments. Here we have used the
comments to write the algorithm used to swap two numbers. The execution of the algorithm is
shown in the output.
Sometimes when multiple lined statements need to be written to comments, hashtags may
not be helpful. It will cause a break inflow of the statements. In such situations, you can use
delimiters for writing comments.
"""
when you use delimiters
to write multiple lined
comments, this is how
it looks.more.
"""
print("PythonGeeks")
Output:
PythonGeeks
Control Statements in Python:
Control statements are the statements that change the flow of execution of statements based
on a condition.
Control statements are designed to serve the purpose of modifying a loop's execution from its
default behavior. Based on a condition, control statements are applied to alter how the loop
executes.
If Condition:
Case statement:
The switch is a construct that can be used to implement a control flow in a program. It can be
used as an alternative to the if-else statements or the elif ladder when we have a single
variable/ an expression that we use to make the decision.
Using this instead of the multiple if-else statements makes the code look cleaner, quicker, and
more readable. It works by executing the code block under a corresponding case that is
satisfied.
Syntax:
match term:
case pattern-1:
action-1
case pattern-2:
action-2
=
=
=
case pattern-n:
Action-n
case _:
Action-default
Loops:
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.
2 For loop This type of loop executes a code block multiple times and
loops
1 Break statement This command terminates the loop's execution and transfers the
2 Continue This command skips the current iteration of the loop. The
Syntax:
def fun_name(arg):
Statements
return value
Example:
def my_fun():
print(“This is my function”)
return 0
Note: Without any function call, the function definition will not give any output.
We have a rich set of in-built python functions . If we want to use them we just need to import
them and use them accordingly.
Types of Arguments:
1.Default Arguments: Sometimes, we don’t need to pass all the arguments as some may have
default values in it.
Ex: def circle_rad(pi=3.14, r):
return(pi+(r**2))
circle_rad(3)
O/p: 28.26
In the above example, pi value is always the same. So, we don’t need to pass it.
The pi value in the above function is the Default argument.
Note: Non-default argument must be initiated first and followed by Default argument.
def cir_rad(r,pi=3.14) is correct.
Arbitrary Arguments:
Sometimes, we may not have the clarity to pass the no’of arguments so at that time we
pass different no’of arguments at different function calls. So, these arguments are called
Arbitrary Arguments.
This can be achieved by Asterisk(*) symbol.
def add_numbers(*nums):
result=0
for num in numbers:
result=result+num
return result
Refer to the git url for examples.
The above expression returns Even or odd as per the if condition. If the
condition is true, it will return “Even” else it returns “Odd”.
→ If we want to pass the value the lambda functions,