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

Python Programming

Python programming

Uploaded by

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

Python Programming

Python programming

Uploaded by

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

PYTHON PROGRAMMING

D R . G A U R A V S I N G A L
PYTHON
PROGRAMMING
LANGUAGE
• Python is a high-level, general-purpose programming
language.
• It emphasizes code readability with the use of significant
indentation.
• It supports multiple programming paradigms, including
structured, object-oriented and functional programming.
• It is often described as a "batteries included" language due to
its comprehensive standard library.
I M P O R T I N G PAC K A G E / M O D U L E S
• A package is a container that contains various functions to perform specific tasks.
• For example, the math package includes the sqrt() function to perform the square root of a number.
• Some examples of package:
• NumPy.
• pandas.
• Matplotlib.
• Seaborn.
• scikit-learn.
• Requests.
• urllib3.
• NLTK.
I M P O R T S U B - PAC K A G E
• We can import modules from packages using the dot (.)
operator.
• For example, if we want to import the start module in the above
example, it can be done as follows:
import Game.Level.start
• Now, if this module contains a function named select_difficulty(),
we must use the full name to reference it.
Game.Level.start.select_difficulty(2)
DATA T Y P E
Data Types

• Data type is the classification of the type of values that can be assigned
to variables.
• Dynamically typed languages, the interpreter itself predicts the data type
of the Python Variable based on the type of value assigned to that
variable.
>>> x = 2
▪ x is a variable and 2 is its value >>> type(x)
int
▪ x can be assigned different values; >>> x = 2.3
hence, its type changes accordingly >>> type(x)
float
8
Data Types (Numbers)
The number data type is divided into the following five data types:

>>> a = 2
• Integer >>> type(a)
• Long Integer (removed from py3) >>> a = 0x19
int
>>> type(a)
• Floating-point Numbers >>> a = 2.5
int
>>> type(a)
• Complex Numbers float
>>> a = 2 + 5j
>>>type(a)
>>> a = 0o11
Complex
>>> type(a)
int

10
Data Types (String)
• Python string is an ordered collection of characters which is used to
represent and store the text-based information. Strings are stored as
individual characters in a contiguous memory location. It can be
accessed from both directions: forward and backward.

>>> a = “Bennett”
>>> print(a)
Bennett
>>> a = ‘University’
>>> print(a)
University

11
Data Types (String)
• Characters of string can be individually accessed using a method called
indexing.
• Characters can be accessed from both directions: forward and
backward.
• Forward indexing starts form 0, 1, 2…. Whereas, backward indexing
starts form −1, −2, −3…
>>> a = “Bennett University”
>>> print(a[5])
t
>>> print(a[-1])
y
>>> print(a[-5])
r
12
st= ‘python’

print(st[1:5]) # ytho

print(st[ :6]) # python

Some
print(st[1: ]) # ython

print(st[:]) # python

Examples print(st[1:10])

print(st[-2:])
# python

# on

print(st[:-3]) #pyt

print(st[1:5:2]) #yh

print(st[ ::-2]) #nhy

13
Data Types (List)
Unlike strings, lists can contain any sort of objects: numbers,
strings, and even other lists. Python lists are:

• Ordered collections of arbitrary objects >>> a = [2,3,4,5]


• Accessed by offset >>> b =
• Arrays of object references [“Bennett”,
“University”]
• Of variable length, heterogeneous, and arbitrarily nestable
>>> print(a,b)
• Of the category, mutable sequence >>>
• Data types in which elements are stored in the index basis [2,3,4,5][‘Bennett’,
with starting index as 0
’University’]
• Enclosed between square brackets ‘[]’

15
Data Types (List)
• Much similar to strings, we can use the index number to access items in
lists as shown below.
• Accessing a List Using Reverse Indexing
• To access a list in reverse order, we have to use indexing from −1, −2…. Here,
−1 represents the last item in the list.
>>> a = [“Bennett”, “University”, “Computer”]
>>> print(a[0])
Bennett
>>> print(a[-1])
Computer
>>> print(a[1])
University
16
Lists
Data Types (Tuples)
• Tuple data type in Python is a collection of various immutable Python
objects separated by commas.
• Tuples are generally used for different Python Data Types.
• A Python tuple is created using parentheses around the elements in the
tuple. Although using parentheses is only optional, it is considered a
good practice to use them.
>>> a = (1,2,3,4)
>>> print(a)
(1,2,3,4)
>>> a = (‘ABC’,’DEF’,’XYZ’)
>>>print(a)
(ABC,DEF,XYZ)
18
Data Types (Tuple)
• To access an element of a tuple, we simply use the index of that
element. We use square brackets.
• Reverse Indexing by using indexes as −1, −2, −3, and so on, where −1
represents the last element.
• Slicing that is, extract some elements from the tuple.
>>> a = (1,2,3,4) >>> a = (1,2,3,4)
>>> print(a[1]) >>> print(a[-1])
2 4
>>> a = (‘ABC’,’DEF’,’XYZ’) >>> a = (‘ABC’,’DEF’,’XYZ’)
>>>print(a[2]) >>>print(a[1:])
XYZ (DEF, XYZ)
19
Tuples
Data Types (Set)
• It is an unordered collection of elements which means that a set is a
collection that stores elements of different Python Data Types.
• In Python sets, elements don’t have a specific order.
• Sets in Python can’t have duplicates. Each item is unique.
• The elements of a set in Python are immutable. They can’t accept
changes once added.
>>> myset = {“bennett”, “computer”, “science”}
>>>print(myset)
{'bennett', 'computer', 'science’}
>>>myset = set((“bennett”, “computer”, “science”))

21
Data Types (Dictionary)
• Yet another unordered collection of elements.
• Difference between dictionary and other unordered Python data types
such as sets lies in the fact that unlike sets, a dictionary contains keys
and values rather than just elements.
• Unlike lists the values in dictionaries are accessed using keys and not by
their positions

>>>dict1 ={“Branch”:”computer”,”College”:”Bennett”,”year”:2020}
>>>print (dict1)
{‘Branch’:’computer’,’College’:’Bennett’,’year’:2020}
>>>di = dict({1:’abc’,2:’xyz})
22
Data Types (Dictionary)
• The keys are separated from their respective values by a colon (:) between
them, and each key–value pair is separated using commas (,).
• All items are enclosed in curly braces.
• While the values in dictionaries may repeat, the keys are always unique.
• The value can be of any data type, but the keys should be of immutable
data type, that is
• Using the key inside square brackets like we used to use the index inside
square brackets.
>>>dict1 ={“Branch”:”computer”,”College”:”Bennett”,”year”:2020}
>>>print (dict1[year])
2020
23
Datatype Conversion
• As a matter of fact, we can do various kinds of conversions between
strings, integers and floats using the built-in int, float, and str functions
>>> x = 10 >>> y = "20" >>> z = 30.0
>>> float(x) >>> float(y) >>> int(z)
10.0 20.0 30
>>> str(x) >>> int(y) >>> str(z)
'10' 20 '30.0'
>>> >>> >>>

integer ➔ float string ➔ float float ➔ integer


integer ➔ string string ➔ integer float ➔ string

24
Explicit and Implicit Data Type Conversion

• Data conversion can happen in two ways in Python


1. Explicit Data Conversion (we saw this earlier with the int, float, and str built-in functions)
2. Implicit Data Conversion
• Takes place automatically during run time between ONLY numeric values
• E.g., Adding a float and an integer will automatically result in a float value
• E.g., Adding a string and an integer (or a float) will result in an error since string is
not numeric
• Applies type promotion to avoid loss of information
• Conversion goes from integer to float (e.g., upon adding a float and an integer) and
not vice versa so as the fractional part of the float is not lost.

25
Implicit Data Type Conversion:
Examples
>>> print(2 + 3.4)
▪ The result of an expression that involves
5.4
a float number alongside (an) integer
>>> print( 2 + 3)
number(s) is a float number
5
>>> print(9/5 * 27 + 32)
80.6
>>> print(9//5 * 27 + 32)
59
>>> print(5.9 + 4.2)
10.100000000000001
>>>
26
Implicit Data Type Conversion:
Examples
>>> print(2 + 3.4)
▪ The result of an expression that involves
5.4
a float number alongside (an) integer
>>> print( 2 + 3)
number(s) is a float number
5
>>> print(9/5 * 27 + 32)
▪ The result of an expression that involves
80.6
values of the same data type will not result
>>> print(9//5 * 27 + 32)
in any conversion
59
>>> print(5.9 + 4.2)
10.100000000000001
>>>
27
Loops in
Python

28
Iterative Control
(Loop)
• An iterative control statement is a control statement that allows
for the repeated execution of a set of statements.

• Due to their repeated execution, iterative control structures are


commonly referred to as “loops.

• Loop Statements:
• While
• For
• Nested loop
While Statement
(indefinite loop)
• A while statement is an iterative control statement that repeatedly executes a set of
statements based on a provided Boolean expression (condition).
Example 1

• Find all even numbers from 0 to n. where, n is


given by user.
Example 2

Print all even numbers between n to m. m


should be greater than n.
Example 3

Write a program to take numbers from the user


until he enter 0 as input. then print sum of all
entered number.
Example 4

• Write an efficient program to determine sum of


N natural numbers where N is given by user.
For Loop Loop to read
(definite loop) sequence

• A for loop is used for iterating over a


sequence (that is either a list, a tuple, a
dictionary, a set, or a string). Can
execute a set of statements, once for
each item in a list, tuple, set etc.

Syntax:
for iterating_var in sequence:
statements(s)
• Example:
Sequences
• Sequence of character - 'QWERTYUIOPASDFGHJKL’
• Sequence of words - ['abc','def','efg','ijk’]
• Sequence of numbers - [1,2,3,4,5,6,7,8,9]
• Sequence of mix data – [‘Suvi’, 4, “LKG”, “Bennett University”, 98.5]

Sequence of numbers can also be generated as:


• range(start, end, difference)
• range(3) = (0,1,2)
• range(1,5) = (1,2,3,4)
• range(3,9,2) = (3, 5, 7)
• range(9,2,-1) = (9,8,7,6,5,4,3)
• range(9,2,1) = []
For Loop: What will be the output?
1. 4.

2. 5.

3.
For Loop: Answers to Previous Questions
1 2 3 4 5
• Let one grain of wheat be placed on the first square of a chessboard, two
grains on the second square, four grains on the third square, eight grains on the
fourth square, and so on until all square are filled in chessboard. what will be
the total weight in ton of grains on whole 8×8 chessboard? If 15432 grains in one
kg and 907.18 kg in one ton then.

Problem
Exercise 2
• Loop inside a loop a is called nested loop.

• Example:

Nested
Loop
Nested Loop: What will be the output?
1.

2.

3.
Find all prime numbers between given
two numbers
Find first 100 prime numbers start from 2.
Infinite loop

• An infinite loop is an iterative


control structure that never
terminates (or eventually
terminates with a system error).
• Infinite loops are generally the
result of programming errors.
• For example: if the condition of
a while loop can never be false,
an infinite loop will result when
executed.
Loop Control Statements
• Break Statement: Terminates the loop statement and transfers execution to the statement
immediately following the loop.
• Continue Statement: Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.

• Pass Statement: The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to execute.
Example: Output:
Use of pass in if: for letter in 'Python’: Current Letter : P
a = 33 if letter == 'h’: Current Letter : y
b = 200 pass Current Letter : t
if b > a: print('This is pass block’) This is pass block
pass print('Current Letter :', letter) Current Letter : h
print(“Loop Ended!“) Current Letter : o
Current Letter : n
Loop Ended
Break and Continue: Examples
• Break Statement:
Ex.1: fruits = ["apple", "banana", "cherry"] Ex.2: fruits = ["apple", "banana", "cherry"]
for x in fruits: for x in fruits:
print(x) Output: if x == "banana":
if x == "banana": apple break
break banana print(x)

• Continue Statement:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana": Output:
continue apple
print(x) cherry
MCQs
1. A while loop continues to iterate until its 5. The terms definite loop and indefinite loop
condition becomes false. are used to indicate whether,
a) TRUE a) A given loop executes at least once
b) FALSE
b) The number of times that a loop is
2. A while loop executes zero or more times. executed can be determined before the
a) TRUE loop is executed.
b) FALSE c) Both of the above
3. All iteration can be achieved by a while loop.
a) TRUE 6. A Boolean flag is,
b) FALSE a) A variable
4. An infinite loop is an iterative control b) Has the value True or False
structures that, c) Is used as a condition for control
a) Loops forever and must be forced to statements
terminate
d) All of the above
b) Loops until the program terminates with a
system error
c) Both of the above
Labs
• https://colab.research.google.com/drive/1qiRRXsZ6KwGsFmYF6WmMh_GK1oi
xLHTR?usp=sharing
• To understand more about the following topics:
• List:
https://colab.research.google.com/drive/1oreu8OTv_ROnYTnDUXYSaArGHnxLsa8e
• Dictionary:
https://colab.research.google.com/drive/1WSzIlkwOJ5PdIiC3vdysX11g3wpypg1V
• Sets:
https://colab.research.google.com/drive/1_XEHA0sSAhwl8bGDiWgR8yuVigvmBtoh?usp=shar
ing
• Tuple:
https://colab.research.google.com/drive/16U04OB-
sBUHh2B_84YRManw2ruIMBsmK?usp=sharing#scrollTo=ZLuOqXg30Be8

49
MCQs: Answers
1. A while loop continues to iterate until its 5. The terms definite loop and indefinite loop
condition becomes false. are used to indicate whether,
a) TRUE a) A given loop executes at least once
b) FALSE
b) The number of times that a loop is
2. A while loop executes zero or more times. executed can be determined before the
a) TRUE loop is executed.
b) FALSE c) Both of the above
3. All iteration can be achieved by a while loop.
a) TRUE 6. A Boolean flag is,
b) FALSE a) A variable
4. An infinite loop is an iterative control b) Has the value True or False
structures that, c) Is used as a condition for control
a) Loops forever and must be forced to statements
terminate
d) All of the above
b) Loops until the program terminates with a
system error
c) Both of the above
Next Sessions

51
NumPy
• NumPy is a library for numerical computing in Python. It provides fast
and efficient multidimensional array operations.

• Arrays can be used to perform various operations such as arithmetic


operations, matrix operations, and statistical operations.

52
Pandas
• Pandas is a library for data manipulation and analysis in Python. It
provides a fast and efficient way to work with structured data.

53
Data Frames
• Data frames can be used to perform various operations such as filtering,
sorting, and grouping.

54
Matplotlib

55

You might also like