Professional Documents
Culture Documents
Ppts DT
Ppts DT
2
Writing a Program in Python
We will be using the software Google Colaboratory also known as
Google Colab
The opening window will be shown something as below
In this window we will start writing the code
3
Writing a Program in Python
In the home scree, there are three buttons:
File Button
Code Button
Run Button
File Button
Code Button
Run Button
4
Writing a Program in Python
In the home scree, there are three buttons:
File Button: Press File New Notebook. A blank window as shown below will appear
Code Button: Press the Code Button before writing the code/ or to select the option to write the code.
Run Button: The Run Button is used to execute the program after you have completed the code.
File Button
Code Button
Run Button
5
Writing a Program in Python
Lets try and start writing the first code:
Type: 1+1
Press the Run Button
6
Writing a Program in Python
Lets try and start writing the first code:
Type: 1+1
Press the Run Button
7
Writing a Program in Python
Lets try and start writing the first code:
Type: 1+1
Press the Run Button
Python has evaluated the expression and now it is displaying the result (2).
Now we can use the Code button to write the next code.
This is what we have done. But is this the actual process that is taking place.
8
Writing a Program in Python
Lets try and start writing the first code:
Type: 1+1
Press the Run Button
Python has evaluated the expression and now it is displaying the result (2).
Now we can use the Code button to write the next code.
This is what we have done. But is this the actual process that is taking place.
Normally every Python program is a loop following the series of steps:
Python reads the code entered at the prompt.
Python evaluates the code.
Python prints the result and wait for more inputs
This complete process is known as “Read, Evaluate Print loop” also known as REPL.
9
Writing a Program in Python
Lets try and start writing the first code:
Type: 1+1
Press the Run Button
Python has evaluated the expression and now it is displaying the result (2).
Now we can use the Code button to write the next code.
This is what we have done. But is this the actual process that is taking place.
Normally every Python program is a loop following the series of steps:
Python reads the code entered at the prompt.
Python evaluates the code.
Python prints the result and wait for more inputs
This complete process is known as “Read, Evaluate Print loop” also known as REPL.
10
Writing a Program in Python
Lets try the code that we have taken as an example in the previous class, wherein we
have to print the phrase: Hello, World
For this we need to type: print followed by a set of parenthesis with the text ‘Hello,
World’ and press the Run Button
Something as follows
11
Writing a Program in Python
Now we have written two programs so far.
So, what are the differences between these two programs.
12
Brief Introduction to Concept of Functions
In the first program we have directly given two numerical inputs and an output was
given.
In the second program, we printed the desired word/ phrase.
Some important points in second code.
The word print followed by parenthesis: print()
print() is a function.
Function in a code performs some specialized task.
In the second code we invoked/ called the function print() to get the output, Hello, World
In this function whatever is written within inverted commas “” will be displayed on the screen.
It also denotes, that what ever we have written on then screen is text and nothing else.
13
Variable Declaration and Print
In Python, variables are names that can be assigned a value and then used to refer to
that value throughout your code. Variables are fundamental to programming for two
reasons:
Variables keep values accessible: For example, you can assign the result of some time-consuming operation to
a variable so that your program doesn’t have to perform the operation each time you need to use the result.
Variables give values context: The number 28 could mean lots of different things, such as the number of
students in a class, the number of times a user has accessed a website, and so on. Giving the value 28 a name
like num_students makes the meaning of the value clear .
14
Variable Declaration and Print
A variable is something that can hold a varying value.
For ex: a = 30. Here letter ‘a’ is a variable. Its present value is 30 and it can hold any
value.
So let’s see how can we declare variable and print its value
a = 300 #Assignment; No output will be shown at the moment
a # The statement will print the value of a
300
This will be the required output. Similarly
b = “Shayam” # Assignment, No output will be shown at the moment
b # This statement will print the value of variable b
‘Shayam’
15
Variable Declaration and Print
What is the difference between the variable ‘a’ and variable ‘b’.
16
Variable Declaration and Print
What is the difference between the variable ‘a’ and variable ‘b’.
Here variable ‘a’ is an integer type variable, whereas, variable ‘b’ is string type.
So integer type variable holds numerical values on which we can perform calculations.
String type variables are unable to perform normal mathematical operations.
17
Variable Declaration and Print
Here as well we can use the print() function to print both the variables together.
A=300
A
B=“Shayam”
B # So if I will run the code till here, it will print only the value of B
Print(A,B) # If I will use the print statement, it will print both the values.
18
Variable Declaration and Print
Let’s see: Problem 1 Let’s see: Problem 2
A=300 A=“300”
B=400 B=“400”
C=A+B C=A+B
C C
What will be the output? What will be the output?
19
Variable Declaration and Print
Let’s see: Problem 1 Let’s see: Problem 2
A=300 A=“300”
B=400 B=“400”
C=A+B C=A+B
C C
What will be the output? What will be the output?
Output: 700 Output: ‘300400’
20
Variable Declaration and Print
Problem 1
A=300
B=400
C=A+B
C
What will be the output?
Output: 700
Here the ‘+’ sign is known as the operator which is working on the operands ‘A’ and ‘B’
Since it is performing an arithmetic operation, therefore, it is called Arithmetic operator.
21
Errors
Many a times while writing a program, mistakes can happen.
These mistakes in a program is called an Error.
Basically, in the start we will encounter two basic types of errors:
Syntax Errors
Runtime Errors
22
Errors
Many a times while writing a program, mistakes can happen.
These mistakes in a program is called an Error.
Basically, in the start we will encounter two basic types of errors:
Syntax Errors
Runtime Errors
Syntax Error:
This type of error occurs when you write a code that is not allowed in Python language.
For ex.
print(“Hello, World)
If we run the above statement then the system will give error as following:
23
Errors
Syntax Error:
This type of error occurs when you write a code that is not allowed in Python language.
For ex.
print(“Hello, World)
If we run the above statement then the system will give error as following:
There are two parts of this error:
In first part it is showing in red color that there is error in line 1 print(“Hello, World)
The second part shows that it’s a syntax error. EOL here stands for End of Line.
Thus, the message tells us that, Python got to the end of line while reading the string literal.
It also tells that string literal must be terminated with a quotation marks, otherwise everything after the
first quotation marks including the parenthesis is part of the string.
24
Errors
Many a times while writing a program, mistakes can happen.
These mistakes in a program is called an Error.
Basically, in the start we will encounter two basic types of errors:
Syntax Errors
Runtime Errors
Runtime Error:
Syntax error occurs before a program starts running.
But the run time error occurs while a program is running.
Lets see an example:
print(Hello, World)
This will show error as following
25
Errors
Many a times while writing a program, mistakes can happen.
These mistakes in a program is called an Error.
Basically, in the start we will encounter two basic types of errors:
Syntax Errors
Runtime Errors
Runtime Error:
Syntax error occurs before a program starts running.
But the run time error occurs while a program is running.
Lets see an example:
print(Hello, World)
This will show error as following
26
Errors
Runtime Error:
Syntax error occurs before a program starts running.
But the run time error occurs while a program is running.
Lets see an example:
print(Hello, World)
When we write this wrong statement, the text color changes.
Whenever, such error occurs, Python stops executing the program and displays several lines of text called
traceback.
This traceback shows useful information about the error.
Best way to read the tracebacks is bottom up.
The last line of the traceback tells you the name of the error and the error message.
In the present case a NameError occurred because the name Hello is not defined anywhere.
The second to last line shows the code that produced that error.
In the present code there is only one line, so one can guess the error is in that line. But for large codes, this information is
helpful.
The third to last line tells the name of the file and the line number, so that one can go to the spot in the code where the error
occurred.
27
Different types of Operators in Python
Similar to C, C++ and Java, there are a wide variety of operators used in
Python.
Arithmetic Operators
Bitwise Operators
28
Assignment Operator
Values are assigned to variable names using a special symbol called the assignment
operator ‘=’.
The ‘=’ operator takes the value to its right and assign it to the variable name on the left.
For example:
greeting = “Hello World”
print(greeting)
In this case the output will be:
29
Assignment Operator
Values are assigned to variable names using a special symbol called the assignment
operator ‘=’.
The ‘=’ operator takes the value to its right and assign it to the variable name on the left.
For example:
greeting = “Hello World”
print(greeting)
In this case the output will be:
Thus, we have created a variable named greeting and assigned it the value “Hello
World”
If we would have not used line 1 and directly used line 2, it will show error.
It is important to note that these variable names are case sensitive.
Thus, the variable greeting is different from the variable Greeting 30
Assignment Operator
It is important to note that these variable names are case sensitive.
Thus, the variable greeting is different from the variable Greeting. Ex.
greeting = “Hello World”
print(Greeting)
Output will be:
31
Assignment Operator
It is important to note that these variable names are case sensitive.
Thus, the variable greeting is different from the variable Greeting. Ex.
greeting = “Hello World”
print(Greeting)
Output will be:
32
Rule for Valid Variable Names
Variable names can be as long or as short as you like, but there are a few rules that you
must follow.
Variable names may contain uppercase and lowercase letters (A–Z, a–z), digits (0–9),
and underscores (_),
But they cannot begin with a digit.
For example, each of the following is a valid Python variable name:
String1
_a1p4a
list_of_names
The following aren’t valid variable names because they start with a digit:
9lives
99_balloons 33
Rule for Valid Variable Names
In addition to English letters and digits, Python variable names may contain valid Unicode characters.
Unicode is a standard for digitally representing characters used in most of the world’s writing systems.
This include letters such as é and ü, and even Chinese, Japanese, and Arabic symbols.
Since all the systems cannot show these characters, it is good idea to avoid these.
Use descriptive names: These are basically used in complex problems.
There we use proper long name to variable instead of simple single variable.
Ex. ‘Sum’ for addition of two numbers instead of letter ‘s’.
Variable Naming Convention: In many programming languages, it’s common to write variable names in
mixedCase.
In this system, you capitalize the first letter of every word except the first and leave all other letters in
lowercase.
For example, numStudents and listOfNames are written in mixedCase.
34
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations such as addition, subtraction and so on.
‘-’ Subtraction:
‘*’: Multiplication,
‘/’: Division,
‘%’: Modulus)
35
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations such as addition, subtraction and so on.
‘-’ Subtraction:
‘*’: Multiplication,
‘/’: Division,
‘%’: Modulus
36
Basic Arithmetic Operators
Use of basic arithmetic operations in coding: Addition
A=220
B=16
C=A+B
print (A, “+”, B, “=”, C)
So the output will be
37
Basic Arithmetic Operators
Use of basic arithmetic operations in coding: Addition
A=220
B=16
C=A+B
print (A, “+”, B, “=”, C)
So the output will be
38
Basic Arithmetic Operators
Use of basic arithmetic operations in coding: Subtraction
A=220
B=16
C=A-B
print (A, “-”, B, “=”, C)
So the output will be
39
Basic Arithmetic Operators
Use of basic arithmetic operations in coding: Subtraction
A=220
B=16
C=A-B
print (A, “-”, B, “=”, C)
So the output will be
40
Basic Arithmetic Operators
Use of basic arithmetic operations in coding: Multiplication
A=220
B=16
C=A*B
print (A, “*”, B, “=”, C)
So the output will be
41
Basic Arithmetic Operators
Use of basic arithmetic operations in coding: Multiplication
A=220
B=16
C=A*B
print (A, “*”, B, “=”, C)
So the output will be
42
Basic Arithmetic Operators
Use of basic arithmetic operations in coding: Division
A=220
B=16
C=A/B
print (A, “/”, B, “=”, C)
So the output will be
43
Basic Arithmetic Operators
Use of basic arithmetic operations in coding: Modulus
A=220
B=16
C=A%B
print (A, “%”, B, “=”, C)
So the output will be
44
Basic Arithmetic Operators
Use of basic arithmetic operations in coding: Modulus
A=220
B=16
C=A%B
print (A, “%”, B, “=”, C)
So the output will be
45
Basic Arithmetic Operators
Use of basic arithmetic operations in coding: Modulus
A=220
B=16
C=A%B
print (A, “%”, B, “=”, C)
So the output will be
46
Difference Between ‘/’ and ‘//’ Operator
Both these operators are used to perform division operation.
A=220
B=16
C=A/B
D=A//B
print (A, “/”, B, “=”, C, “and”, A, “//”, B, “=”, D)
So the output will be
47
Difference Between ‘/’ and ‘//’ Operator
Both these operators are used to perform division operation.
A=220
B=16
C=A/B
D=A//B
print (A, “/”, B, “=”, C, “and”, A, “//”, B, “=”, D)
So the output will be
48
Use of ‘**’: Power Operator
Both these operators are used to perform division operation.
A=9
B=2
C=A**B
print (A, “**”, B, “=”, C)
So the output will be
49
Bitwise Operators
In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral at the
level of its individual bits.
It is a fast and simple action, basic to the higher level arithmetic operations and directly supported by the
processor.
For example if we write:
A=1
B=2
A ANDB = ???
50
Bitwise Operators
In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral at the
level of its individual bits.
It is a fast and simple action, basic to the higher level arithmetic operations and directly supported by the
processor.
For example if we write:
A=1
B=2
A ANDB = ???
51
Bitwise Operators
Following Bitwise operators are used in Python
AND (&)
OR (|)
Not (~)
XOR (^)
52
Bitwise Operators
AND (&)
This operator will perform the AND operation according to the truth table:
Example:
A=0
B=1
D=1
C=A&B
print (A, “&”, B, “=”, C)
Output will be:
56
Bitwise Operators
Shift Right (>>)
This operator will perform the shift right operation: i.e. new bit enters from left and old bit falls off from
right.
A>>B means shift the bits of A towards
right by B number of Bits.
Example:
A=10 # 1010
B=1 #Shift right by 1 bit
C=A>>B # 0101 = 5
print (A, “>>”, B, “=”, C)
Output will be:
57
Bitwise Operators
Shift Left (<<)
This operator will perform the shift left operation: i.e. new bit enters from right and old bit falls off from
left.
A<<B means shift the bits of A towards
right by B number of Bits.
Example:
A=4 # 0100
B=1 #Shift right by 1 bit
C=A>>B # 1000 = 8
print (A, “<<”, B, “=”, C)
Output will be:
58
Input from Users
In this user can provide the input during the runtime condition.
Ex.
a=input(“Enter Anything:”)
print (a)
print(“Your input is:”, a)
59
Input from Users
In this user can provide the input during the runtime condition.
Ex.
a=int(input(“Enter Number:”))
print (a)
print(“Your input is:”, a)
60
If Else Conditional Check
Following Bitwise operators are used in Python
A=int(input(“Enter First Number:”))
B=int(input(“Enter Second Number:”))
if a>b
print(A, “>”, B)
else:
print(A, “<”, B)
61
Else If Else Statement
Ex.
A=input(“Enter First No.:”)
B=input(“Enter Second No.”)
if A==B:
print(“A==B”)
elif A>B:
print(“A>B”)
else:
print(“A<B”)
62
Logical Operators
Use of AND
Ex.
A=10
B=20
if A==10 and B==20:
print(“Accepted”)
elif a>=b:
print(“Rejected”)
else:
print(“On Hold”)
63
Logical Operators
Use of AND
Ex.
A=0
B=0
Print(A and B)
64
Logical Operators
Use of OR
Ex.
A=10
B=20
if A==10 or B==20:
print(“Accepted”)
else:
print(“Rejected”)
65
Logical Operators
Use of Or
Ex.
A=0
B=0
Print(A or B)
66
Logical Operators
Use of NOT
Ex.
A=True
Print( not A)
67
Identity Operators
There are two identity operators: ‘is’ and ‘is not’
Ex.
A=10
B=20
Print(A is A)
A=10
B=20
Print(A is not A)
A=10
B=20
Print(A is B)
68
Membership Operator
These are: ‘in’ and ‘not in’
A=[10, 20, 30]
print (10 in A)
69
File handling in Python
• Read a file and print its content line by line
• First create a file abc.txt and write some lines
• Ex
70
File handling in Python
• Another method to read a file
• First create a file abc.txt and write some lines
• Ex.
71
File handling in Python
• Absolute path
• First create a file abc.txt and write some lines
• Ex.
72
File handling in Python
• Write the file 1 to 20
• Download the file and check the output
• Ex.
73
File handling in Python
• Another method to write a file 1 to 20
• Download the file and check the output
• Ex.
74
File handling in Python
• Read from one file convert it to upper case and write to other file
• First create a file abc.txt and write some lines.
• Create second file.
75
File handling in Python
• Appending to a file
• Download the file and check the contend of ‘o.txt’ file.
• Ex.
76
File handling in Python
• Read an image
• Download one image (mountain.jpg)
• Ex.
77
File handling in Python
• Write one image to other
• Download two image (mountain.jpg and river.jpg )
• Ex.
78
Plotting Graphs In Python
• Graphs are used to represent data information and data in visual format.
• These can be of wide varying range such as:
Line Graph
Bar Graph
Pi Chart, etc.
• In Python, graphs can be easily plotted by utilizing "matplotlib" library and utilizing various
functions such as "plt.plot", "plt.show", etc.
• Matplotlib is a comprehensive library for creating static, animated and interactive visualization in
Python.
79
Importing matplotlib
There are a sequence of steps required for plotting the graph. These are:
• The primary task is to import the matplotlib library.
• It can be performed by following statement:
import matplotlib.pyplot as plt
Here in this line import is the keyword that is used to call the particular
library and all its associated functions.
Thereafter, it is followed by the name of the library that needs to be
called.
80
Plotting graph using matplotlib
• Once the particular library is called, one can start plotting the graphs.
81
Plotting graph using matplotlib
82
Plotting graph using matplotlib
• Plot multiples lines
83
Plotting graph using matplotlib
• Plot a bar chart
• Ex.
84
Plotting graph using matplotlib
• Plot multiple bar plot
Ex.
85
Plotting graph using matplotlib
• Plot Scatter plot
Ex.
86
Plotting graph using matplotlib
• Pie chart plot
• Ex.
87
Plotting graph using matplotlib
88
Data Manipulation using pandas
Pandas is an open-source Python Library providing high-performance data manipulation and
analysis tool using its powerful data structures
Working with data file (csv)
• First step is to import pandas
89
Data Manipulation using pandas
90
Data Manipulation using pandas
• Show bottom 5 rows of the dataset
91
Data Manipulation using pandas
• Get all column names of the dataset
92
Data Manipulation using pandas
Get the datatype of each column
93
Data Manipulation using pandas
Get the dimension of the dataset
94
Data Manipulation using pandas
• Get the statistical summary of the dataset
95
Data Manipulation using pandas
• Transposing the dataset
96
Data Manipulation using pandas
• Accessing data from dataset - using loc - Column Names
97
Data Manipulation using pandas
• Accessing data from dataset - using iloc - Column position
98
Data Manipulation using pandas
• To get unique values in a Column (factors)
99
Data Manipulation using pandas
• To get unique count in a Column
100
Data Manipulation using pandas
• IsNull: This returns true or false depending on the status of the cell
101
Data Manipulation using pandas
• Aggregate of all the values which are null
102
Data Manipulation using pandas
• Drop NA values (delete rows)
103
Data Manipulation using pandas
104
Data Manipulation using pandas
• Drop the columns where there are null values
105
Data Manipulation using pandas
• Fill the null values with '0‘
106
Data Manipulation using pandas
• Replace Values
107
Data Manipulation using pandas
108
Numpy_Basics
• NumPy is the fundamental package for scientific computing in Python.
• First step is to import pandas
109
Numpy_Basics
• Replace value in list and array
110
Numpy_Basics
• A nparray filled with all ones
111
Numpy_Basics
• A nparray filled with all zeros
112
Numpy_Basics
• Create nparray of n integer
113
Numpy_Basics
• Creates np array of n elements, equally spaced between start and end
114
Numpy_Basics
• Create 1 dimensional from random integer
115
Numpy_Basics
• Create n dimensional array from random numbers between 0 and 1
116
Numpy_Basics
Create array from random numbers between a and b
117
Numpy_Basics
• Difference between list and numpy indexing
118
THANK YOU
For queries
Email: amandeep.ece@cumail.in
119