Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python

Python is a high-level general purpose programming language that supports structured, object-oriented and functional programming paradigms. It has a simple syntax and is used for web development, machine learning, data science and more. The document discusses features of Python like syntax, data types, variables, operators and more.

Uploaded by

Anil Padarthi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python

Python is a high-level general purpose programming language that supports structured, object-oriented and functional programming paradigms. It has a simple syntax and is used for web development, machine learning, data science and more. The document discusses features of Python like syntax, data types, variables, operators and more.

Uploaded by

Anil Padarthi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Python

Python is an object-oriented, high-level programming language with integrated dynamic


semantics for web and application development.

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.

It supports Structured, Object-Oriented and Functional programming paradigms.


Features of Python:
❖ It supports interpretation, there is no need of compiling and running the code
separately as like C, C++ and Java
❖ Simple syntax
❖ Open-source and redistributable
❖ High-level language
❖ Robust( means, it has Exception handling and Memory management techniques
in-built)
❖ Rich Library Support for different purposes like numpy,scipy, matplotlib etc.
❖ Embeddable( python script can embed in any of the languages, either low-level or
high level).
❖ It supports both command line and GUI interfaces. Which means we can run
commands in python shell as well as python IDE.
➢ Python shell supports command level syntax
➢ GUI supports Structured python programming where we can write code,save
and execute.

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.

C:/>pip install numpy


❖ Numpy is a package in python, it is used for working with arrays.
❖ It is also useful when we work with linear algebra, fourier transform, and matrices.

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.

C:/>pip install scipy


❖ Scipy stands for Scientific Python, It gives more utility functions for optimizations, stats
and signal processing.

To check scipy is installed or not


>>> import scipy

C:/>pip install pandas


❖ Pandas is a python library, it is useful when we work with data sets.
❖ It has functions for analyzing, cleaning, exploring and manipulating data.
❖ The word pandas is derived from Panel Data, which means an Econometrics from
multidimensional data, and also called Python Data Analysis.

To Check pandas installed or not


>>> import pandas

C:/>pip install matplotlib


❖ Matplotlib is a python library which is defined as a multi-dimensional data visualization
library built on numpy Array.
❖ It can be used in python scripts, shell, web application, and other graphical user
interface toolkits.

To check matplotlib installed or not


>>> import matplotlib
import matplotlib.pyplot as plt
import numpy as np

xpoints = np.array([0, 6])


ypoints = np.array([0, 250])

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

Data Science and Python:


Good command over Libraries
Learn Statistical Analysis
Mathematical formulas
Data Visualization
Data manipulation
Data Analysis and Interpretation
Learn about Databases
Python Variables:
❖ A Variable is a memory location where we can store values. In python, the data type
will be identified according to the data provided.
❖ Variable names are case sensitive.
➢ It means data type can be identified automatically according to the value we
store into the variable.
>>> name =5
>>>type(name)
<class ‘Int’>

>>>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

❖ Comparison(>, <, >=, <=, ==,!=) (Returns True or False)


x=10, y=20
x>y (it returns true or false as per the values)
❖ Logical (AND, OR,NOT) (Returns True or False)
If we want to check 2 or more conditions at a time
Ex: X=10, Y=15

X==10 and Y>15


X==10 or Y>15

❖ Bitwise
These are used to compare binary numbers.
& AND
| OR
^ XOR
~ NOT
<< LEFT SHIFT
>> RIGHT SHIFT

❖ Identity
❖ Membership

Note: Refer https://www.geeksforgeeks.org/python-operators/

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.

How to write python program in IDLE:


● Open Python IDLE
● Click on NewFile
● After writing the program save it with .py extension
● Click on “Run” from the main menu and then click on Run Module.

How to write addition of two numbers in python?


Ans: To capture values from the runtime, we need to use “input” function
Syntax: a= input()
By using this we will write addition of two numbers

a= int(input(“Enter first value :”)


b= int(input(“Enter Second value : “)
c=a+b
print(“Result from adding two numbers is : “, c)

Best Python IDEs:

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.

We can create a dictionary by using the below method also.


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.
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

Ex: x=’Naresh’ - >


print(x[2])
O/p: r
❖ If we have spaces in between the string we gave, that whitespace is also have an
index.
❖ We can give +ve and +ve indexing also. Incase of -ve indexing value of -ve index starts
in reverse order
NARESH
-6 -5 -4-3-2-1
Ex : a=’Naresh’
print(a[-3])
o/p: e
Slicing:
It relies on indexing. Therefore, slicing only works with sequence types.
Slicing is the extraction of a part of a string, list or tuple. It enables users to access the specific
range of elements by mentioning their indices.
Syntax: Object[start:stop:step]
“Start” specifies the starting index of a slice “Stop” specifies the ending element of a slice.
You can use one of these if you want to skip certain items.
Note: The search will start at index Start(included) and ends at index stop(not included)

Ex: a= “Hello World”


print(a[0:5])
O/p: Hello
❖ If we mention “step” also it will skip the step-1 elements
➢ Ex: print(a[0:9:2]
■ O/p: Hlo Wr
■ It skips 1 element and giving next element.
➢ If we don’t mention the start or end, it will take from starting or up to end of the
string.
■ Ex: print(a[3:])
O/p: lo World
String Operations:

String Concatenation: we can concatenate two strings using “+” Operator.

Ex: str1 = "Naresh"


str2="Kumar"
str3=str1 +str2
print(str3)

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 add values runtime within a message, below is the code


Input & Output Options:
❖ To capture input values while in runtime use “input()” function.
Ex: name=input(“ Enter name :”)
print(name)
Whenever we capture values from runtime, the system will take it as string only. If we want
to capture other than string we just need to typecast to that particular data type.

➔ 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.

➔ If we want to print any thing for multiple times


◆ print(“Hello”*2)
➔ If we want to pass any random value within the print statement, we can use below syntax.

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

Python Math built-in Functions:


The math module is a standard module in Python and is always available. To use
mathematical functions under this module, you have to import the module using import math

Function Description

ceil(x) Returns the smallest integer greater than or equal


to x.

copysign(x, y) Returns x with the sign of y


Function Description

fabs(x) Returns the absolute value of x

factorial(x) Returns the factorial of x

floor(x) Returns the largest integer less than or equal to x

fmod(x, y) Returns the remainder when x is divided by y

frexp(x) Returns the mantissa and exponent of x as the pair


(m, e)

fsum(iterable) Returns an accurate floating point sum of values in


the iterable

isfinite(x) Returns True if x is neither an infinity nor a NaN


(Not a Number)

isinf(x) Returns True if x is a positive or negative infinity

isnan(x) Returns True if x is a NaN

ldexp(x, i) Returns x * (2**i)

modf(x) Returns the fractional and integer parts of x

trunc(x) Returns the truncated integer value of x

exp(x) Returns e**x

expm1(x) Returns e**x - 1

log(x[, b]) Returns the logarithm of x to the base b (defaults


to e)

log1p(x) Returns the natural logarithm of 1+x

log2(x) Returns the base-2 logarithm of x

log10(x) Returns the base-10 logarithm of x

pow(x, y) Returns x raised to the power y


Function Description

sqrt(x) Returns the square root of x

acos(x) Returns the arc cosine of x

asin(x) Returns the arc sine of x

atan(x) Returns the arc tangent of x

atan2(y, x) Returns atan(y / x)

cos(x) Returns the cosine of x

hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y)

sin(x) Returns the sine of x

tan(x) Returns the tangent of x

degrees(x) Converts angle x from radians to degrees

radians(x) Converts angle x from degrees to radians

acosh(x) Returns the inverse hyperbolic cosine of x

asinh(x) Returns the inverse hyperbolic sine of x

atanh(x) Returns the inverse hyperbolic tangent of x

cosh(x) Returns the hyperbolic cosine of x

sinh(x) Returns the hyperbolic cosine of x

tanh(x) Returns the hyperbolic tangent of x

erf(x) Returns the error function at x

erfc(x) Returns the complementary error function at x

gamma(x) Returns the Gamma function at x

lgamma(x) Returns the natural logarithm of the absolute value


of the Gamma function at x
Function Description

pi Mathematical constant, the ratio of circumference


of a circle to it's diameter (3.14159...)

e mathematical constant e (2.71828...)

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.

What is a Data Structure?


Before learning about data structures in python, we should first know what is data? Data is a
piece of information translated into a form that is efficient to translate and process.

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.

We have two types of Data Structures in python.


1) Primitive Data Structures
2) Non-Primitive

Primitive data structures are also called built-in data types (int, float, string, boolean), where
we can store only one type of data.

Non-Primitive data structures are also divided as two types


1. Built-in Data Structures
2. User defined Data structures

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:

1. Built-in Data Structures

● 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.

newList = [ expression(element) for element in oldList if condition ]

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.

We can create a dictionary by using the below method also.


● Tuple in Python - The tuple is also a built-in data structures in python which are
somewhat similar to lists data structures in python. A tuple is an immutable object that
stores the elements in an ordered manner. We cannot change the elements of the
tuple or the tuple itself, once it's assigned whereas we can change the elements of the
list as they are mutable. The tuple in python provides a wide variety of methods and
functions. We can put heterogeneous type values inside the tuples. The most common
associated method of tuples are tuple(), count(), index() etc.
● Sets in Python - The set is also a built in data structures in python. A set is a collection
of unordered values or items. The set in python has similar properties to the set in
mathematics. The set in python provides a wide variety of methods and functions. The
set() function is used to create a set in python. We can put heterogeneous type values
inside the sets. The most common associated method of sets are set(), add(), update(),
remove(), pop(), discard(), clear(), intersection(), union(), set_difference() etc.
❖ 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.

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.

● HashMaps - Hashmap is also not a built-in data structures in python. A hashmap is


also known as a hash table. A hashmap is one of the data structures in python that
maps keys to its value pairs. It is somewhat similar to a dictionary since dictionaries
also store key-value pairs but hashmaps use a function to compute the index value that
stores or holds the elements to be searched. This function or hashing() helps to
retrieve mapped elements in a faster manner than the normal sequential or linear
search. Simply we can say that hash tables store key-value pairs and the key is
generated using a hash function. In python, we use the built-in dictionary data
structures to implement hash maps. The elements of a hashmap are not ordered and
can be changed.
Statements and Indentation:
Instructions written in source code for execution are called statements. A logical statement is
a logical expression where operators compare, evaluate or check whether the input meets the
condition or not.
Multi-line statements in python:
Python allows us to write instructions in one or more lines, we need to give a backslash( \ ),
parentheses( ), braces{ }, square brackets[ ], semicolon ( ; ).

For examples check below git code.


Multi-line statements in one line:
You can also write multiple lines in python by separating each statement with a semicolon.

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.

1. Docstrings Comments in Python

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.

Example of docstring comments in python :

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

2. Single-Line Comments in Python


To write a single-line comment in python you use a hashtag (#) followed by the statement.
Example of single-line comments in python :
#taking string (name) as input and storing it in a variable name

name=input("please enter your name\n")


#taking int (age) as input and storing it in variable age
age=int(input("please enter your age\n"))
#printing name and age
print(f"your name is {name} and your age is {age}")

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.

3. Multi-line comments in Python

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:

a. Using hashtags (#):

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.

b. Using delimiters (“””):

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.

Example of multi-line comments using delimiter:

"""
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.

The flow control statements are divided into three categories


1. Conditional statements
2. Iterative statements.
3. Transfer statements

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.

Sr.No Name of Loop Type & Description


. the loop

1 While loop Repeats a statement or group of statements while a given condition

is TRUE. It tests the condition before executing the loop body.

2 For loop This type of loop executes a code block multiple times and

abbreviates the code that manages the loop variable.

3 Nested We can iterate a loop inside another loop.

loops

Note refer git for examples.

Loop Control Statements:


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.

1 Break statement This command terminates the loop's execution and transfers the

program's control to the statement next to the loop.

2 Continue This command skips the current iteration of the loop. The

statement statements following the continue statement are not executed

once the Python interpreter reaches the continue statement.

3 Pass statement The pass statement is used when a statement is syntactically

necessary, but no code is to be executed.


Functions in Python:

A function is a set of instructions to perform a specific task, enabling the programmer to


modularize a program. All variables created in function definition are local variables, they are
known only to the function in which they are declared. The main aim of creating functions is
code reusability.

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.

Arguments in python functions:


We can pass the arguments while calling the function, which are called parameters or
arguments.
def sum1(a,b):
c=a+b
return c
d=sum1(2,5)
print(d)

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.

Top 5 important Python Functions:

1. Lambda(): It is an anonymous function in python. Because, it has no function


name and syntax but we can create functions and pass the arguments
2. Lambda supports only single line arguments. It is good when we write simple
and single line functions.
a. Syntax:
lambda <arg>:expression
Ex: The below code will give us 1 to 4 numbers after multiplying with 10

is_even_list = [lambda arg=x: arg * 10 for x in range(1, 5)]

# iterate on each lambda function


# and invoke the function to get the calculated value
for item in is_even_list:
print(item())

-> We can use if condition within lambda function also.


Now, I am here to find the given number is even or odd

Result= lambda x:”Even” if x%2==0 else “Odd”

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,

You might also like