Python Notes 2022
Python Notes 2022
# for string
variable_name=input(“Enter your name”)
# for integer
variable_name=int(input(“Enter any number:”))
Basic Program code
OUTPUT
Python Character set
It encompasses the following:
Lowercase English letters: a through z
Uppercase English letters: A through Z
Some punctuation and symbols: "$" and "!", to name a
couple
Whitespace characters: an actual space (" "), as well as a
newline, carriage return, horizontal tab, vertical tab, and a
few others
Some non-printable characters: characters such as
backspace, "\b", that can’t be printed literally in the way
that the letter A can
TOKENS
A token is the smallest individual unit in a python
program. All statements and instructions in a program
are built with tokens.
Type of Tokens:
TOKEN: Keywords
TOKEN: Identifier
Identifiers are user-defined names given to
different entities such as constants, variables,
structures, functions, module etc.
TOKEN: Literals / Values
Literals are the constant values or the variable
values used in a Python code.
Python support the following literals:
TOKEN: Punctuators
These are the symbols that used in Python to
organize the structures, statements, and
expressions.
Data types in Python
Data types are the classification or categorization of data items. It
represents the kind of value that tells what operations can be performed on
a particular data. Since everything is an object in Python programming,
data types are actually classes and variables are instance (object) of these
classes.
OPERATORS:
Python Operators in general are used to perform
operations on values and variables.
Comparison(Relational) Operators
Logical Operators
Bitwise Operators
In Python, bitwise operators are used to performing bitwise calculations
on integers. The integers are first converted into binary and then
operations are performed on bit by bit, hence the name bitwise operators.
Membership Operators
Identity Operator
Working of If Condition in Python
with Examples
Working of If ..else Condition in
Python with Examples
Working of elif Condition in Python
with Examples
Working of Nested..if Condition in
Python with Examples
What is while loop in Python?
The while loop in Python is used to iterate over a block
of code as long as the test expression (condition) is
true.
With the while loop we can execute a set of statements
as long as a condition is true. We generally use this
loop when we don't know the number of times to iterate
beforehand.
Syntax of while Loop in Python
Flowchart of while Loop
Example
Print i as long as i is less than 6:
OUTPUT
What is for loop in Python?
The for loop in Python is used to iterate over a sequence
(list, tuple, string, range function) or other iterable
objects. Iterating over a sequence is called traversal.
Syntax of for Loop
Flowchart of for Loop
Example: Python for Loop
Print each fruit in a fruit list:
OUTPUT
What is a Nested Loop in Python?
A nested loop is a loop inside the body of the outer
loop. The inner or outer loop can be any type, such as a
while loop or for loop. For example, the outer for loop can
contain a while loop and vice versa.
The break Statement
With the break statement we can stop the loop before it
has looped through all the items:
OUTPUT
What is String in Python?
A string is a sequence of characters. A character is simply
a symbol. For example, the English language has 26
characters. The Data Type of the text is str( String )
Creation of String
Strings are one of the most common data types in
Python. It is used for storing text. It can be created by
enclosing characters either in single quotation marks or
double quotation marks. It can be assigned to a variable
using = sign.
Access text from string
A character (also called element) of a string can be accessed with it's index
number. In Python, index number starts with 0 in forward direction and -1
in backward direction. The figure below describes the indexing concept of a
string.
What is List in Python?
Lists are used to store multiple items in a single variable.
A list in Python is used to store the sequence of various
types of data. Python lists are mutable type its mean we
can modify its element after it created.
Lists are enclosed in square brackets [ ] and each item is
separated by a comma.
List features
Accessing Values in Lists
Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-
hand side of the assignment operator, and you can add to elements in a list with the
append() method. For example −
Traversing Lists : Two ways
Python List Methods
How to apply List Methods:
my_list = [3, 8, 1, 6, 0, 8, 4]
print(len(my_list))
my_list.append(9)
# Output: 7
print(my_list)
print(my_list.index(8))
# Output: [3, 8, 1, 6, 0, 8, 4, 9]
# Output: 2
my_list.pop(2)
print(my_list.count(8))
# Output: 1
my_list.sort()
my_list.extend([12,15,16])
print(my_list)
print(my_list)
# Output: [0, 1, 3, 4, 6, 8, 8]
# Output: [3, 8, 6, 0, 8, 4, 9, 12, 15, 16]
my_list.reverse()
new_list=my_list.copy()
print(my_list)
print(new_list)
# Output: [8, 8, 6, 4, 3, 1, 0]
# Output: [3, 8, 6, 0, 8, 4, 9, 12, 15, 16]
What is tuple in Python?
Tuples are used to store multiple items in a single
variable.
Tuple is one of 4 built-in data types in Python used to
store collections of data. A tuple is a collection which is
ordered and unchangeable.
Tuples are written with round brackets.
The characteristics of a Python tuple
are:
1. Tuples are ordered, indexed collections of data.
Similar to string indices, the first value in the tuple
will have the index [0], the second value [1], and so on.
2. Tuples can store duplicate values.
3. Once data is assigned to a tuple, the values cannot be
changed.
4. Tuples allow you to store several data items in one
variable. You can choose to store only one kind of
data in a tuple or mix it up as needed.
How to Create and Use Tuples?
In Python, tuples are assigned by placing the values or
"elements" of data inside round brackets "()." Commas
must separate these items.
A tuple may have any number of values and the values
can be of any type.
Here are some examples of declared tuples:
Repeating/ Replicate
You can use * operator to replicate a tuple a specified number of times.
Unpacking Tuples
Packing- Creating tuples from a set of values.
Unpacking- Creating individual values from a tuple’s element.
.
Tuple operation examples
Deleting Tuples
The del statement is used to delete elements and objects. But, since tuples
are immutable as discussed above, individual item of a tuple cannot be
deleted.
.
Tuple Methods or Function
DICTIONARY
Each key is separated from its
value by a colon (:), the items are
separated by commas, and the
whole thing is enclosed in curly
braces. An empty dictionary
without any items is written with
just two curly braces, like this: {}.
Keys are unique within a
dictionary while values may not
be. The values of a dictionary can
be of any type, but the keys must
be of an immutable data type such
as strings, numbers, or tuples.
Accessing Values in Dictionary
To access dictionary elements, you can use the familiar
square brackets along with the key to obtain its value.
Following is a simple example −
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
Print("dict['Name']: ", dict['Name'])
Print("dict['Age']: ", dict['Age'])
When the above code is executed, it produces the
following result −
dict['Name']: Zara
dict['Age']: 7
Updating Dictionary
You can update a dictionary by adding a new entry or a key-
value pair, modifying an existing entry, or deleting an
existing entry as shown below in the simple example −
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
When the above code is executed, it produces the following
result −
dict['Age']: 8
dict['School']: DPS School
Dictionary Methods or Functions
How to use Methods
DIFFERENCES BETWEEN LIST, TUPLE & DICTIONARY
FUNCTION
A function is a block of
organized, reusable code that
is used to perform a single,
related action. Functions
provide better modularity for
your application and a high
degree of code reusing.
As you already know, Python
gives you many built-in
functions like print(), etc. but
you can also create your own
functions. These functions are
called user-defined functions.
Defining a Function
You can define functions to provide
the required functionality. Here are
simple rules to define a function in
Python.
Function blocks begin with the
keyword def followed by the function
name and parentheses ( ( ) ).
Any input parameters or arguments
should be placed within these
parentheses. You can also define
parameters inside these parentheses.
The first statement of a function can be
an optional statement - the
documentation string of the function
or docstring.
The code block within every function
starts with a colon (:) and is indented.
The statement return [expression] exits a
function, optionally passing back an
expression to the caller. A return
statement with no arguments is the same
as return None.
What are Python Modules?
Modules provide us with a way to share reusable
functions. A module is simply a “Python file” which
contains code we can reuse in multiple Python programs.
A module may contain functions, classes, lists, etc.
Modules in Python can be of two types:
Built-in Modules.
User-defined Modules.
Built-in Modules in Python
One of the many superpowers of Python is that it comes
with a “rich standard library”. This rich standard library
contains lots of built-in modules. Hence, it provides a lot
of reusable code.
To name a few, Python contains modules like “os”, “sys”,
“datetime”, “random”.
You can import and use any of the built-in modules
whenever you like in your program. (We’ll look at it
shortly.)
User-Defined Modules in Python
Another superpower of Python is that it lets you take
things in your own hands. You can create your own
functions and classes, put them inside modules and voila!
You can now include hundreds of lines of code into any
program just by writing a simple import statement.
To create a module, just put the code inside a .py file.
Let’s create one.
EXAMPLE
The Python code for a module named aname normally
resides in a file named aname.py. Here's an example of
a simple module, support.py
def print_func( par ):
print "Hello : ", par
return
The import Statement
You can use any Python source file as a module by
executing an import statement in some other Python
source file. The import has the following syntax −
#!/usr/bin/python
# Import module support
import support
# Now you can call defined function that module as follows
support.print_func("Zara")
When the above code is executed, it produces the following result −
Hello : Zara
A module is loaded only once, regardless of the number of times it is
imported. This prevents the module execution from happening over
and over again if multiple imports occur.
The from...import Statement
Python's from statement lets you import specific
attributes from a module into the current namespace.
The from...import has the following syntax −
from modname import name1[, name2[, ... nameN]]
For example, to import the function fibonacci from the
module fib, use the following statement −
from fib import fibonacci
This statement does not import the entire module fib into
the current namespace; it just introduces the item
fibonacci from the module fib into the global symbol table
of the importing module.
The from...import * Statement
It is also possible to import all names from a module
into the current namespace by using the following
import statement −
from modname import *
This provides an easy way to import all the items from a module into the
current namespace; however, this statement should be used sparingly.
Locating Modules
When you import a module, the Python interpreter
searches for the module in the following sequences −
The current directory.
If the module isn't found, Python then searches each
directory in the shell variable PYTHONPATH.
If all else fails, Python checks the default path. On UNIX, this
default path is normally /usr/local/lib/python/.
The module search path is stored in the system
module sys as the sys.pathvariable. The sys.path
variable contains the current directory,
PYTHONPATH, and the installation-dependent
default.
NUMPY ARRAYS
Numpy which stands for Numerical Python which is
the core library for scientific computing in Python. It
provides a high-performance multidimensional array
object, and tools for working with these arrays.
Arrays : A numpy array is a grid of values, all of the
same type, and is indexed by a tuple of nonnegative
integers. The number of dimensions is the rank of the
array; the shape of an array is a tuple of integers giving
the size of the array along each dimension.
What are NumPy and Pandas?
Numpy is an open source Python library used for scientific
computing and provides a host of features that allow a
Python programmer to work with high-performance arrays
and matrices.
In addition, pandas is a package for data manipulation that
uses the DataFrame objects from R (as well as different R
packages) in a Python environment.
3 dtype dtype is for data type. If None, data type will be inferred
# Create DataFrame
df = pd.DataFrame(data)
# own function
def adder(adder1,adder2):
return adder1+adder2
df = pd.DataFrame(d)
print df
print df.pipe(adder,2)
Row or Column Wise Function Application:
apply()
apply() function performs the custom operation for either
row wise or column wise . In below example we will be
using apply() Function to find the mean of values across
rows and mean of values across columns:
import pandas as pd
import numpy as np
import math
#Create a DataFrame
d = {'Score_Math':pd.Series([66,57,75,44,31,67,85,33,42,62,51,47]),
'Score_Science':pd.Series([89,87,67,55,47,72,76,79,44,92,93,69])}
df = pd.DataFrame(d)
print df
print df.apply(np.mean,axis=1)
Element wise Function Application
in python pandas: applymap()
applymap() Function performs the specified operation
for all the elements the dataframe. we will be using the
same dataframe to depict example of applymap()
Function. We will be multiplying the all the elements
of dataframe by 2 as shown below:
import pandas as pd
import numpy as np
import math
# applymap() Function
print df.applymap(lambda x:x*2)
Matplotlib.pyplot
matplotlib.pyplot is a collection of command style functions that make
matplotlib work like MATLAB. Each pyplot function makes some change to a
figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a
plotting area, decorates the plot with labels, etc.
Example:
import matplotlib.pyplot as plt
plt.plot(x,y, color=“Green”)
plt.title(‘Graph Name')
plt.xlim(two values)
plt.xticks(x,[‘A’,’B’,’C’,’D’])
plt.yticks(x,[‘A’,’B’,’C’,’D’])
plt.legend(loc=‘upper left’)
plt.xlabel(‘x-axis name')
plt.ylabel(‘y-axis name')
plt.show()
LINE CHART
A line chart or line graph is a type of chart which
displays information as a series of data points called
‘markers’ connected by straight line segments. It is a
basic type of chart common in many fields.
A line chart is often used to visualize a trend in data
over intervals of time – a time series – thus the line is
often drawn chronologically. In these cases they are
known as run charts.
SYNTAX:
plt.plot(x,y, color=red, marker =‘*’, markersize=5,
markeredgecolor=‘red’)
LINE CHART RESULT
BAR CHART
A bar chart or bar graph is a chart or graph that presents
categorical data with rectangular bars with heights or
lengths proportional to the values that they represent.
The bars can be plotted vertically or horizontally.
A bar graph shows comparisons among discrete
categories. One axis of the chart shows the specific
categories being compared, and the other axis represents
a measured value
SYNTAX:
plt.bar(x,y, width=0.5, color=‘red’ or ‘r’,align='center',
alpha=0.5)
BAR CHART RESULT
SCATTER CHART
Scatter plots are used to plot data points on horizontal and
vertical axis in the attempt to show how much one variable
is affected by another.
Each row in the data table is represented by a marker the
position depends on its values in the columns set on the X
and Y axes.
SYNTAX:
plt.scatter(x,y, s=None, c=None, marker=None)
x,y : Data
s : marker size
c : marker color
marker : Marker style like *,o
SCATTER CHART RESULT
PIE CHART
A Pie Chart can only display one series of data. Pie
charts show the size of items (called wedge) in one
data series, proportional to the sum of the items. The
data points in a pie chart are shown as a percentage of
the whole pie.
SYNTAX:
plt.pie(data, sizes, explode=explode, labels=labels,
autopct='%1.1f%%', shadow=True, startangle=90)
PIE CHART RESULT
HISTOGRAM CHART
A histogram is a great tool for quickly assessing a probability distribution that is intuitively
understood by almost any audience.
Python offers a handful of different options for building and plotting histograms. Most people
know a histogram by its graphical representation, which is similar to a bar graph:
SYNTAX:
plt.hist(x,bins=None, cumulative=False, histtype=‘bar’, align=‘mid’, orientation=‘vertical’)
I. X : data
II. Bins : an integer is given, bins + 1 bin edges are calculated and returned,
consistent
III. Cumulative : If True, then a histogram is computed where each bin gives the counts
in that bin plus all bins for smaller values. The last bin gives the total number of
datapoints .
I. Histtype : {'bar', 'barstacked', 'step', 'stepfilled'}, optional.
II. Align : {'left', 'mid', 'right'}, optional
III. Orientation : {'horizontal', 'vertical'}, optional
BOX PLOT
Boxplots are a measure of how well distributed the data
in a data set is. It divides the data set into three
quartiles.
This graph represents :
1) Minimum,
2) Maximum,
3) Median,
4) Lower Quartile
5) Upper Quartile
Example:
plt.boxplot(x, vert=False, notch=True, showmeans=True, showbox=True)
BOX PLOT RESULT