You are on page 1of 201

Python Programming

Introduction to Python

 Python is a general-purpose programming language.


 It is high level and object-oriented programming language.
 Python is a very simple programming language so even if you are new to
programming, you can learn python without facing any issues.
 Python is used in all domains
 Web Development
 Software Development
 Game Development
 AI & ML
 Data Analytics

Python is developed by- Guido van Rossum


Object Oriented Programming
OOPs Concepts:

 Class
 Object
 Polymorphism
 Inheritance
 Encapsulation
 Abstraction
 Method
 Message Passing
Object Oriented Programming
Classes and Objects

A class is a user defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of
one type.

It is a basic unit of Object Oriented Programming and represents the real life
entities. Object determines the behavior of the class. When you send a message
to an object, you are asking the object to invoke or execute one of its methods.
Object is just an instance of the real world object or class in the programming
world
Object Oriented Programming
Abstraction

Data Abstraction may also be defined as the process of identifying only the
required characteristics of an object ignoring the irrelevant details. The properties
and behaviors of an object differentiate it from other objects of similar type and
also help in classifying/grouping the objects.

Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the speed of car or applying brakes will stop
the car but he does not know about how on pressing the accelerator the speed is
actually increasing, he does not know about the inner mechanism of the car or
the implementation of accelerator, brakes etc in the car. This is what abstraction
is.
Object Oriented Programming
Encapsulation

Binding of variables and methods together.


Object Oriented Programming
Inheritance
Inheritance is gaining or deriving properties of the parent. Parent
class

Child
class
Object Oriented Programming
Polymorphism
The word polymorphism means having multiple forms. The term Polymorphism
gets derived from the Greek word where poly + morphos where poly means
many and morphos means forms.
Object Oriented Programming
Polymorphism
Real life example of polymorphism: A person at the same time can have different
characteristic. Like a man at the same time is a father, a husband, an employee. So
the same person posses different behaviour in different situations. This is called
polymorphism.
Polymorphism is considered as one of the important features of Object Oriented
Programming. Polymorphism allows us to perform a single action in different
ways. In other words, polymorphism allows you to define one interface and have
multiple implementations. The word “poly” means many and “morphs” means
forms, So it means many forms.

In Java polymorphism is mainly divided into two types:


1. Compile time Polymorphism
2. Runtime Polymorphism
Features of Python Programming

 Python is free and open-source programming language.


 It is high level programming language.
 It is simple and easy to learn.
 It is portable. That means python programs can be executed on various
platforms without altering them.
 It is object-oriented programming language.
 It can be embedded in or C++ programs.
 Python programs are interpreted. (No need to compile).
 It has huge set of library.
 Python has a powerful set of built-in data types and easy to use control
statements.
Installation Procedure

Python can be downloaded from the following URL

http://www.python.org/downloads
Interactive Mode and Script Mode

Python has two basic modes. They are


1. Interactive Mode
2. Script Mode
Interactive Mode
Interactive mode is a command line shell. The user can execute commands and
get the output immediately. The commands are executed via the python shell,
which comes with python installation.
To access the python shell, open the terminal of your operating system and then
type “python”. Press the enter key and the Python shell appear.
Interactive Mode
Interactive Mode

The >>> indicates that the python shell is ready to execute and send your
commands to the python interpreter. The result is immediately displayed on the
python shell.
To run your python statements, just type them and hit the enter key. You will get
the results immediately.
For Example, to print the text “Hello World”

>>> print(“Hello World”)


Hello World
>>>
Interactive Mode

Here are other examples


>>> 10
10
>>> print(5*20)
100
>>>print(“hi”*5)
hihihihihi
>>> name=“Sharma”
>>> age=21
>>> course=“BT and Civil”
Interactive Mode

>>> print(“My name is ”+name+”, aged ”+age+” , taking “+course)


Error
TypeError: Cannot concatenate ‘str’ and ‘int’ objects.
When we do not know that the variable type will be always a string, we need to
explicitly convert it to a string.
>>> print(“My name is ”+name+”, aged ”+str(age)+” , taking “+course)
Interactive Mode

The below example demonstrates how we can execute multiple python


statements in interactive mode.
>>> if 5 > 10:
... print("5 is greater than 10")
... else:
... print("5 is less than 10")
...
5 is less than 10
>>>
Pros and Cons of Interactive Mode

The following are the advantages of running your code in interactive mode:
1.Helpful when your script is extremely short and you want immediate results.
2.Faster as you only have to type a command and then press the enter key to get
the results.
3.Good for beginners who need to understand Python basics.
Script Mode

If we need to write a long piece of python program, script mode is the right
option. In script mode, we have to write a code in a text file then save it with a .py
extension which stands for python. Note that we can use any text editor for this,
including Sublime, Atom, notepad++, etc.

First.py // save the file name Output


a=10
b=20
if a>b:
print("a is greater")
else:
print("b is greater")
Pros and Cons of Script Mode

The following are the advantages of running your code in script mode:
1.It is easy to run large pieces of code.
2.Editing your script is easier in script mode.
3.Good for both beginners and experts.
The following are the disadvantages of using the script mode:
4.Can be tedious when you need to run only a single or a few lines of cod.
5.You must create and save a file before executing your code.
Getting help

You can get the details of command in interactive mode. Just type the help()
command on the shell and then hit enter key.
>>> help()
Values and Types

We need a variable to store the values. Based on the data type different values
can be stored in a variable.
Python is Strongly typed .
Python is dynamically typed.

Strongly Typed
Python will never allow implicit conversion. That means data type is not
automatically converted from one type to another type. Explicit conversion is
required.
>>> a=20
>>> b=“30”
>>> c=a+b
Values and Types

>>> c
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

To avoid this error, string data type is converted into integer.


>>> c=a+int(b)
>>> c
50
Values and Types

Dynamically Typed
We don't have to declare the type of variable while assigning a value to a
variable in Python. Other languages like C, C++, Java, etc.., there is a strict
declaration of variables before assigning values to them. ... It states the kind of
variable in the runtime of the program. So, Python is a dynamically typed
language.

There are five data types in python-


1. Numbers
2. Strings
3. List
4. Tuple
5. Dictionary
Values and Types

1. Numbers
There are four different types of numerical data types used in python. Numeric
data type is used to represent numeric value. Numeric value can be a integer,
floating number or complex numbers.
int – It represents signed integer value. For example, 100, -456.
Long- It represents long integers. These values can be represented in octal or
hexadecimal format. For example, 5689399L, -0x17893L.
complex- This data type is used for representing complex numbers. For example,
3e+46j.
Values and Types

2. Strings
A string is a collection of one or more characters put in a single quote, double-
quote or triple quote. In python there is no character data type.
>>> name=“Rojer”
>>> name
‘Rojer’
3. Lists
List is used to store multiple elements separated by comma and enclosed within
the square brackets[ ]. List elements are ordered (it means that elements are
added at the end of list), changeable (we can add or remove elements from the
list), and allow duplicate values. List elements are indexed , the first index is 0.
Values and Types

3. Lists
>>> Games=[“Cricket”,”Hockey”,”Football”]
>>> Games
['Cricket', 'Hockey', 'Football’]
len() Method
To determine the number of elements in the list
>>> len(Games)
3
type() Method
To find the type of variable used in the program
>>> print(type(Games))
<class 'list'>
Values and Types

3. Lists
To access elements from the list
>>> Games.append(“Kabadi”)
>>> Games
['Cricket', 'Hockey', 'Football', 'Kabadi’]
To access the first element
>>> Games[1] or print(Games[1])
Hockey
Negative Indexing
It means that indexing start from the last item. -1 refers to the last item, -2 refers
to the second last item etc.
Values and Types

3. Lists
>>> Games[-1] or print(Games[-1])
Kabadi
>>> Games[-2] or print(Games[-2])
Football
Range of Elements
To access range of elements from the list, mention the starting index and ending
index. The output will be a new list with specified number of elements.
>>> print(Games[1:2])
['Hockey']
Values and Types

3. Lists
>>> Games
['Cricket', 'Hockey', 'Football', 'Kabadi’]
>>> Games[2:]
['Football', 'Kabadi’]
Remove List (We can specify the element name or index while deleting)
>>> Games.remove(“Kabadi”)
>>> Games
['Cricket', 'Hockey', 'Football']
Values and Types

3. Lists
Iterate or Loop through elements
>>> Games.append("Golf”)
>>> Games.append(“Tennis”)
>>> Games
['Cricket', 'Hockey', 'Football', 'Golf', 'Tennis’]
>>> for x in Games
… print(x)

Cricket
Hockey
Football
Golf
Tennis
Values and Types

3. Lists
Sorting Elements in the List (Ascending or Descending)
>>> Games
['Cricket', 'Hockey', 'Football', 'Golf', 'Tennis’]
>>> Games.sort()
>>> Games
['Cricket', 'Football', 'Golf', 'Hockey', 'Tennis’] // Ascending
>>> Games.sort(reverse=True)
>>> Games
['Tennis', 'Hockey', 'Golf', 'Football', 'Cricket']
Values and Types

3. Lists
Copy List elements to another rlist
>>> Games
['Cricket', 'Hockey', 'Football', 'Golf', 'Tennis’]
>>>L1= Games.copy()
>>>L1
['Cricket', 'Hockey', 'Football', 'Golf', 'Tennis’]
Join two different Lists
>>> Games
['Cricket', 'Hockey', 'Football', 'Golf', 'Tennis’]
>>> L1
['Cricket', 'Hockey', 'Football', 'Golf', 'Tennis’]
Values and Types

3. Lists
Join two different Lists // Approach-1 (Use concatenation operator)
>>> L2=Games+L1
>>> L2
['Tennis', 'Hockey', 'Golf', 'Football', 'Cricket', 'Tennis', 'Hockey', 'Golf', 'Football',
'Cricket’]
Join two different Lists // Approach-2 (Use append() method)
>>> list2
[1, 2, 3]
>>> list1
['x', 'y', 'z']
>>> for x in list2:
... list1.append(x)
...
>>> print(list1)
['x', 'y', 'z', 1, 2, 3]
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the
current list
index() Returns the index of the first element with the specified
value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Values and Types

4. Tuple
Tuple is also a collection data type used to store more elements in a single
variable name. It is unchangeable (Immutable). In tuples, elements are enclosed
in round brackets.
Create a Tuple
>>> t1=(1,2,3) //tuple name is t1
>>> t1
(1, 2, 3)
>>> t2=("a","b","c") // //tuple name is t2
>>> t2
('a', 'b', 'c')
Values and Types

4. Tuple
Access Tuple elements // Use index , inside the square brackets
>>> t2
('a', 'b', 'c')
>>> print( t2[1])
Change Tuple Values
Once tuple is created, we cannot change its values. Because tuples are
immutable. But there is another way, Convert tuple into a list, change the list,
and convert the list back into a tuple.
Values and Types

4. Tuple
>>> t2
('a', 'b', ‘c’) // Elements in tuple-t2
>>> t3=list(t2) // tuple is converted into a list
>>> t3
['a', 'b', 'c’]
>>> t3[1]="Butterfly“ // change the element in list
>>> t3
['a', 'Butterfly', 'c’]
>>> t2=tuple(t3) // Convert the list into tuple
>>> t2
('a', 'Butterfly', 'c')
Values and Types

4. Tuple
Loop through a Tuple
>>> cricketers=("Rohit","kholi","Dawan","Ashwin","Jadeja")
>>> cricketers
('Rohit', 'kholi', 'Dawan', 'Ashwin', 'Jadeja’)
>>> for x in cricketers:
... print(x)
...
Rohit
kholi
Dawan
Ashwin
Jadeja
Values and Types

4. Tuple
Join Tuples
>>> cricketers=("Rohit","kholi","Dawan","Ashwin","Jadeja")
>>> bowlers= ("Kuldip","Bumrah","Ishanth","Pandya")
>>> cricket= cricketers + bowlers
('Rohit', 'kholi', 'Dawan', 'Ashwin', 'Jadeja', 'Kuldip', 'Bumrah', 'Ishanth',
'Pandya')
Values and Types

5. Dictionary
It is used to store data values in key:value pairs. Dictionary is a collection which is
ordered, changeable (mutable) and do not allow duplicate values. Dictionary
uses curly brackets.

>>> shop={"name":"Easybuy","type":"Textiles","year":2006, "year":2006}

>>> print(shop)

{'name': 'Easybuy', 'type': 'Textiles', 'year': 2006}


Values and Types

5. Dictionary
Accessing Elements
>>> print(shop)
{'name': 'Easybuy', 'type': 'Textiles', 'year': 2006}
>>> shop[“year”]
2006
Change Dictionary Elements // Approach-1
>>> shop[“year”]=2012
>>> shop
{'name': 'Easybuy', 'type': 'Textiles', 'year': 2012}
Values and Types

5. Dictionary
Change Dictionary Elements //Approach-2
>>> shop.update({“year”:2018})
>>> shop
{'name': 'Easybuy', 'type': 'Textiles', 'year': 2018}
Add elements into Dictionary
>>> shop[“rate”:”Good”]
>>> shop
{'name': 'Easybuy', 'type': 'Textiles', 'year': 2018, 'rate': 'Good'}
Values and Types

5. Dictionary
Remove elements from Dictionary
>>> shop.pop(“rate”)
'Good'
>>> shop
{'name': 'Easybuy', 'type': 'Textiles', 'year': 2018}
Loop through Dictionary
>>> for x in shop:
... print(x+ "="+str(shop[x]))
...
name=Easybuy
type=Textiles
year=2018
Values and Types

5. Dictionary
Copy a Dictionary // Use copy method
>>> shop
{'name': 'Easybuy', 'type': 'Textiles', 'year': 2018}
>>> shop1=shop.copy()
>>> shop1
{'name': 'Easybuy', 'type': 'Textiles', 'year': 2018}
Values and Types
Dictionary Methods
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not
exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
Type command in Python

The data type of different values can be obtained using the type command. This
function returns the data type of particular element.
>>> type(2)
<class 'int'>
>>> type("Raja")
<class 'str'>
>>> type(3.2)
<class 'float'>
>>> type(True)
<class 'bool'>
Variables, Expressions and Statements

Variable
A variable is a reserved memory location to store value. Variables or containers
for storing data values.
Creating Variable
In python there is no command for creating variable. The variable is created
when we assign a value to it.
>>> x=10
>>> y=“John”
>>> Print(x)
10
>>> print(y)
‘John’
Variables, Expressions and Statements

Variable
Casting
If we want to specify the data type of a variable, then that can be done with
casting.
>>> x=str(10)
’10’
>>> x=float(2)
2.0
Variables are case sensitive.
>>> a=10;
>>> A=“CIVIL-BT” // Both variables are not same
Variables, Expressions and Statements

Expressions
It is the combination of operands and operators.
>>> x=10
>>> y=20
>>> z=x+y
>>> print(z)
Statement
A statement is a instruction/piece of code that is executed by the Python
interpreter.
Variables, Expressions and Statements

Expressions
Two types of statements
1. print
2. assignment
The result of print statement is a value.
The assignment statement do not produce a result.
Example
>>> print(2)
2
>>> x=2
Keywords

The keywords are special words reserved for some purpose. The python has 29
keywords.

and def exec if not return


assert del finally import or try
break elif for in pass while
class else from is print yield
continue except global lambda raise
Keywords

def // Used to define a function


def function1():
print(“Welcome to Python Training”)
>>> function1()
Welcome to Python Training
exec // Used to execute dynamically created program
>>> prog = 'print("The sum of 5 and 10 is", (5+10))’
>>> exec(prog)
The sum of 5 and 10 is 15
Operator Precedence

Operators are special symbols that represent computation like addition and
subtraction. The values the operator uses are called operands.
>>> 5-7
-2
>>> 3*4
12
>>> 5**2 // ** is for exponentiation
25
When more than one operator appears in an expression, the order of evaluation
will change based on the operator precedence rules.
Operator Precedence

>>> 10-4*2
What is the output? (12 or 2)
Answer is : 2
Because , multiplication has higher precedence than subtraction.
Rule Name is : PEMDAS
P- Parentheses have the higher precedence.
E- Exponentiation has the next highest precedence.
M- Multiplication
D- Division
A- Addition
S- Subtraction
Operator Precedence

>>> (10-4)*2
What is the output? (12 or 2)
Answer is : 12
Comments in Python

 Comments are statements that are written in the program for program
understanding purpose.
 In python, we use the hash(#) symbol to start writing a comment.
 It extends up to the new line character.
 Python interpreter ignore comment.
Example
#Example for swapping two numbers
String Methods

String is collection of characters. All string methods return new values. They do
not change the original string. Strings in python are surrounded by either single
quotation marks, or double quotation marks.
>>> print(“Hello”)
‘Hello’
>>> print(‘Hello’)
‘Hello’
>>> dept=“Engineering”
‘Engineering’
String Methods
Looping through a String
We can loop through the characters in a string, with a for loop.
Example
for x in “Engineering”:
print(x)
Output
E
N
G
I
N
E
E
R
I
N
G
String Methods

String Length
To get the length of the string, use the len() method.
>>> dept=“Engineering”
>>> print(len(dept))
11
Check String ( in keyword )
To check particular pattern or character is present in the string, we can use in
keyword.
>>> student=“I am doing Bio-Technology”
>>> print(“Bio” in student)
True
String Methods

Check String( not in keyword)


To check pattern or character is present in the string, we can use in keyword.
>>> student=“I am doing Bio-Technology”
>>> print(“Bio” not in student)
False
String Slicing
We can extract range of characters by using the slice. Specify the start index and
end index, separated by a colon, to return part of the string.
>>> student=“I am doing Bio-Technology”
>>> print(student[0:5])
I am
String Methods

>>> student=“I am doing Bio-Technology”


>>> print(student[2:4])
am
Slice from the Start
>>> print(student[:25])
I am doing Bio-Technology
Slice to the End
>>> print(student[0:])
I am doing Bio-Technology
String Methods

Negative Indexing
>>> print(student[-1:])
y
>>> print(student[-2:])
gy
>>> print(student[-10:])
Technology
String Methods

Modify String
Upper Case
>>> name=“Bana Singh”
>>> print(name.upper())
BANA SINGH
Lower Case
>>>print(name.lower())
bana singh
Remove Whitspace
>>> name=“ Bana Singh “
>>>print(name.strip()) // Removes whitespace from the beginning or end
Bana Singh
String Methods

Modify String
Replace String
>>> name=“Bana Singh”
>>> name
'Bana Singh'
>>> print(name.replace("Bana","Param Vir Chakra"))
Param Vir Chakra Singh
String Methods
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
String Methods

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


String Methods
Method Description
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
String Methods
Method Description
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
String Methods
Method Description
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


String Methods
Method Description
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


String Methods
Method Description
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the
beginning
Modules and Functions

Function is a collection of statements that perform some computation. Every


function is specified by its name. For calling function we can use name of the
function.
>>> def test_fun(): // function definition
print(“We are the students from Bio-Tech and Civil. We will get the
placement in reputed IT Industries.”)

>>> test_fun() // function call


We are the students from Bio-Tech and Civil. We will get the placement in
reputed IT Industries.
Modules and Functions

return value
>>> def area(a,b): //parameter
... return a*b
...
>>> area(2,3) // argument
6
Python Conditionals and if Statements

• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
Python if statement syntax
if test_expression:
statements(s)
Here, the program evaluates the test expression and will execute statement(s)
only if the test expression is True.
If the test expression is False, the statement(s) is not executed.
Python Conditionals and if Statements

Example:
Num=3
If Num>0:
print(“Number positive”)

Python if statement syntax


if test_expression:
Body of if
elif test_expression:
Body of elif
else:
Body of else
Python Conditionals and if Statements

The elif is short for else if. It allows us to check for multiple expressions. If the
condition for if is False, it checks the condition of the next elif block and so on. If
all the conditions are False, the body of else is executed. Only one block among
the several if...elif...else blocks is executed according to the condition.
Example:
num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Python Conditionals and if Statements

Python nested if statement syntax


if boolean_expression:
if boolean_expression:
statement(s)
else:
statement(s)
else:
statement(s)
Any number of these statements can be nested inside one another. Indentation is
the only way to figure out the level of nesting. They can get confusing, so they
must be avoided unless necessary.
Python Conditionals and if Statements

Python nested if statement syntax


Example:
x = 30
y = 10
if x >= y:
print("x is greater than or equals to y")
if x == y:
print("x is equals to y")
else:
print("x is greater than y")
else:
print("x is less than y")

x is greater than or equals to y


x is greater than y
Python Loops

Python Loops
 while loop
 for loop
Loops are used to perform same set of statements again and again.
While loop in Python
The block of statements in the while loop is executed as long as the test condition
is true.
Syntax of while loop
while test_expression:
Body of while
Python Loops

In the while loop, test expression is checked first. The body of the loop is entered
only if the test_expression evaluates to True. After one iteration, the test
expression is checked again. This process continues until the test_expression
evaluates to False.
Python Loops

Example:
n = 10
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
print("The sum is", sum)
Output:
The sum is 55
Python Loops

Example: (Find a list of all even numbers from 1 to 25 and calculate the sum of
even numbers)
n = 25 Output
sum = 0 Even numbers are
2
print("Even numbers are") 4
i=1 6
8
while i <= n:
10
if i%2==0: 12
14
print(i) 16
sum=sum+i 18
20
i = i+1 # update counter 22
24
print("The sum is", sum) The sum is 156
Python Loops

for loop in Python


The python for loop is used to iterate over a sequence (list, tuple, String).
Iterating over a sequence is called traversing.
Syntax of for loop
for val in sequence:
loop body

Here, val is the variable that takes the value of the item inside the sequence on
each iteration. Loop continues until we reach the last item in the sequence. The
body of for loop is separated from the rest of the code using indentation.
Python Loops

Example: (Find a list of all even numbers from 1 to 25 and calculate the sum of
even numbers)
n = 25 Output
sum = 0 Even numbers are
2
print("Even numbers are") 4
6
8
for i in range(n):
10
if i%2==0: 12
14
print(i) 16
sum=sum+i 18
20
i = i+1 # update counter 22
24
print("The sum is", sum) The sum is 156
Python Loops

Example:
Python Loops

Example: (Prime no or not)


n=int(input(""))
i=2
flag=0
while i<=n/2:
if n%i==0:
flag=1
break
i=i+1
if flag==0:
print("prime ",n)
Else:
print(“Not a prime ”, n)
Python Loops

Example: (Prime no or not)


n=int(input(""))
i=2
flag=0
while i<=n/2:
if n%i==0:
flag=1
break
i=i+1
if flag==0:
print("prime ",n)
Else:
print(“Not a prime ”, n)
Python Loops

Example: (Palindrome)
rev=0
n=int(input("Enter any no"))
temp=n
while n>0:
r=n%10
rev=rev*10+r
n=int(n/10)
# print(n)
if rev==temp:
print("Palindrome")
else:
print("No")
Python Loops

Example: (Reverse the number)


rev=0
n=int(input("Enter any no"))
temp=n
while n>0:
r=n%10
rev=rev*10+r
n=int(n/10)
# print(n)
print(rev)
Array in Python

An array is a collection of items that are stored in adjacent memory locations. The
idea is to group together items of the same type. This makes calculating the
position of each element easier by simply adding an offset to a base value, i.e.
the memory location of the array's first element (generally denoted by the name
of the array).
We can use list as array in python.
Also, we can create array using importing module.
>>> import array as arr
>>> a=arr.array('i',[1,2,3,4,5])
>>> a
array('i', [1, 2, 3, 4, 5])
Array in Python

Adding elements into array


>>> a.append(10)
>>> a
array('i', [1, 2, 3, 4, 5, 10]) #added 10
>>> a.append(20) #added 20
>>> a
array('i', [1, 2, 3, 4, 5, 10, 20])
Array in Python

Inserting elements into array


>>> a.insert(5,6)
>>> a
array('i', [1, 2, 3, 4, 5, 6, 10, 20])

>>> a.insert(8,30)
>>> a
array('i', [1, 2, 3, 4, 5, 6, 10, 20, 30])
Array in Python

Accessing elements from array


>>> a
array('i', [1, 2, 3, 4, 5, 6, 10, 20, 30])
>>> print(a[1])
2
>>> print(a[8])
30
Array in Python

Removing an element in array


>>> a.pop(8) # Removed 30 at index 8
30
>>> a
array('i', [1, 2, 3, 4, 5, 6, 10, 20])
>>> a.pop(7) # Removed 20 at index 8
20
>>> a.pop(6) # Removed 10 at index 8
10
>>> a
array('i', [1, 2, 3, 4, 5, 6])
Array in Python

Slicing of array
>>> a[0:2]
array('i', [1, 2])
>>> a[0:3]
array('i', [1, 2, 3])
>>> a[0:4]
array('i', [1, 2, 3, 4])
Array in Python

Questions:
1. Read elements of an array.
2. Add up all the array's elements and print the total.
3. Determine the smallest and largest elements in the array.

a=[2,4,1,6,8,89,100]
Classes and Objects

An object is a collection of data (variables) and methods (functions).


Class is a blueprint for that object.
A class is a user-defined blueprint or prototype from which objects are created.
 Classes are created by using keyword class
 Variables declared inside the class
 Variables are always public and can be accessed using the dot (.) operator.
Syntax for class definition:
class ClassName:
#statement-1
----
---
#statement-n
Classes and Objects

Example:
class Student: # name of the class=Student
... name="Rojer"
... age=21
... def greet(): # method is defined
... print("Welcome back")
...
>>> Student.name # how to call variable name
‘Rojer’
>>> Student.greet() # how to call method
‘Welcome Back’
Classes and Objects

Program
class Student:
name="Teresa"
age=33
def fun1(self):
print("Helped poor people")
name1=“Mother”
print(Student.name1)
s1=Student()
print(s1.name)
print(s1.fun1())
Output
Teresa
Teresa
Helped poor people
Classes and Objects

The _init_() function


It is a reserved method in python classes. This method is called when an object is
created from a class and it allows the class to initialize the attributes of the class.
self
It is used to represent the instance of a class. By using the self keyword, we can
access the attributes and methods of the class in python.
Classes and Objects

Example
class Rectangle:
def __init__(self, length, breadth, unit_cost=0):
self.length = length # varaibles initialization
self.breadth = breadth
self.unit_cost = unit_cost
def get_area(self): #method-1
return self.length * self.breadth
def calculate_cost(self):
area = self.get_area() #method-2
return area * self.unit_cost
r = Rectangle(5, 10, 24) #constructor creation
print("Area of Rectangle: %s sq units" % (r.get_area()))
print("Estimate of Total Area: %s sq units" % (r.calculate_cost()))
Classes and Objects

Output:
Area of Rectangle: 50 sq units
Estimate of Total Area: 1200 sq units

Constructor is created.

_init_() method is called when object is created

Variables initialized

Method 1 is called and returning the value

Method 2 is called and returning the value


Python Inheritance

Inheritance allows us to define a class that inherits all the methods and
properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
Syntax for Python Inheritance:
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
Python Inheritance

Example:
class Student:
def __init__(self,a,b):
self.a=a
self.b=b
def fun1(self):
if self.a<self.b:
print("Smallest number{} ".format(self.a))
else:
print("Smallest number{} ".format(self.b))
class College(Student):
pass
y = College(10,14)
y.fun1()

Output
Smallest number10
Python Lambda

It is a small anonymous function. It will take any number of arguments but can
have only one expression.
The syntax is made up of three components:
1. The Keyword lambda
2. A bound variable
3. A body
Syntax:
lambda argument(s): expression
Example:
>>> x = lambda a: a + 10
>>> print(x(10))
20
Python Lambda

>>> x = lambda a,b: a*b


>>> print(x(10,10))
100
>>> (lambda x: x + 1)(2)
3
>>> lambda x, y: x + y
>>> _(2,4)
6
Python Lambda

# list with lambda


>>> new_list = list(filter(lambda x: (x%2 == 0) , my_list))
>>> print(new_list) Python's filter() is a built-in
function that allows you to
process an iterable and
extract those items that
[4, 6, 8, 12] satisfy a given condition

# map with lambda


Python's map() is a built-in
>>> my_list = [1, 5, 4, 6, 8, 11, 3, 12] function that allows you to
process and transform all
>>> new_list = list(map(lambda x: x * 2 , my_list)) the items in an iterable
>>> print(new_list) without using an explicit for
loop, a technique commonly
known as mapping.
[2, 10, 8, 12, 16, 22, 6, 24]
Python Lambda

Pros
 Good for simple logical operations that are easy to understand. This makes
the code more readable too.
 Good when you want a function that you will use just one time.
Cons
 They can only perform one expression. It’s not possible to have multiple
independent operations in one lambda function.
 Bad for operations that would span more than one line in a normal def
function (For example nested conditional operations). If you need a minute or
two to understand the code, use a named function instead.
 Bad because you can’t write a doc-string to explain all the inputs, operations,
and outputs as you would in a normal def function.
Python Scope

A variable is only available from inside the region it is created. This is


called scope.
Local Scope
A variable created inside a function . Output
Example: 300

def myfunc():
x = 300
print(x)
myfunc()
Python Scope

Global Scope
A variable created outside of a function is global and can be used by anyone
Example:
x = 300
Output
def myfunc(): 300
300
print(x)
myfunc()
print(x)
Python Scope

Global Keyword
If you need to create a global variable, but you are inside the local scope, you can
use the global keyword.
Example
Output
def myfunc(): 300

global x
x = 300
myfunc()
print(x)
Python Scope

Example
x = 300
def myfunc():
global x
Output
x = 200 200

myfunc()
print(x)
Python Scope

Example
x=400
def myfunc():
x = 300
Output
print("Local Variable ",x) Local Variable 300
Global Variable 400
myfunc()
print("Global Variable", x)
Python Module

Module is a file contain set of functions.


To create a module
def welcome(msg):
print(“Mathew, ”+msg)
Save the above file as mymodule.py
To use module
// by using import keyword
import mymodule
mymodule.welcome(“Welcome to Python Forum”)

Output
Mathew, Welcome to Python Forum
Python Module

Variables in Module
Student={
“name”:”Durai”, Save the module
“age”:40, mymodule.py
“country”;”India”
}
Tu use above variables
import mymodule
x=mymodule.Student[“name”]
print(x)
Alias name for module
import mymodule as mx
x=mx.Studemt[“name”]
Exception Handling in Python

An exception is a type of error that occurs during the execution of a program.


However, Python throws an exception while running a program, which must be
handled to prevent your application from crashing.
Python has many built-in exceptions that are raised when your program
encounters an error (something in the program goes wrong).
When these exceptions occur, the Python interpreter stops the current process
and passes it to the calling process until it is handled. If not handled, the program
will crash.
Exception Handling in Python

For example, let us consider a program where we have a function A that calls
function B, which in turn calls function C. If an exception occurs in function C but
is not handled in C, the exception passes to B and then to A.

If never handled, an error message is displayed and our program comes to a


sudden unexpected halt.
Exception Handling in Python

Why should we use exceptions?


1. Exception handling mechanism allows you to separate error-handling code
from normal code.
2. It clarifies the code and enhanced readability.
3. It is a convenient method for handling error messages.
4. In python, we can raise an exception in the program by using the raise
exception method.
Exception Handling in Python

Important Python Errors


Error Type Description
ArithmeticError ArithmeticError act as a base class for all arithmetic
exceptions. It is raised for errors in arithmetic operations.

ImportError ImportError is raised when you are trying to import a module


which does not present. This kind of exception occurs if you
have made typing mistake in the module name or the module
which is not present in the standard path.

IndexError An IndexError is raised when you try to refer a sequence


which is out of range.
KeyError When a specific key is not found in a dictionary, a KeyError
exception is raised.
NameError A NameError is raised when a name is referred to in code
which never exists in the local or global namespace.
Exception Handling in Python

Important Python Errors


Error Type Description
ValueError Value error is raised when a function or built-in operation
receives an argument which may be of correct type but does
not have suitable value.

EOFerror This kind of error raises when one of the built-in functions
(input() or raw_input()) reaches an EOF condition without
reading any data.

ZeroDivisonError This type of error raised when division or module by zero takes
place for all numeric types.

IOError- This kind of error raised when an input/output operation fails.

syntaxError SyntaxErrors raised when there is an error in Python syntax.

IndentationError This error raised when indentation is not properly defined


Exception Handling in Python

try:

lets you test a block


of code for errors

excpet:

lets you handle the


error
Exception Handling in Python

finally:
Execute the code
regardless of the
result of the try-and
except blocks
Exception Handling in Python

Example:
if age>=18:
print("Eligible to Vote")
Error:
Traceback (most recent call last):
File "C:/Users/Jose/Desktop/demo2.py", line 1, in <module>
if age>=18:
NameError: name 'age' is not defined
Exception Handling in Python

Example:
try:
if age>=18:
print("Eligible to Vote")
except:
print("Variable age is not initialized")
Output:
Variable age is not initialized
Exception Handling in Python

Example:
An error generated inside the try block
age=24
will be handled by except block.
try:
if age>=18:
If there is no try block, the program
print("Eligible to Vote")
execution will be stopped suddenly,
except:
and error message displayed.
print("Variable age is not initialized")
Output:
Eligible to Vote
Exception Handling in Python

Example:
try:
if age>=18:
print("Eligible to Vote")
except:
print("Variable age is not initialized")
Output:
Variable age is not initialized
Exception Handling in Python

Example: (Division by Zero Error)


import sys
a=20
try:
a/0
except ArithmeticError as e:
print (e)
#print (sys.exc_type)
print ('This is an example of catching ArithmeticError’)
Output:
division by zero
This is an example of catching ArithmeticError
Exception Handling in Python

Example: (ImportError)
import sys
try:
from exception import myexception
except Exception as e:
print (e)
Output:
No module named 'exception'
Exception Handling in Python

Many Exceptions
We can create as many exception blocks as we like, for example, if we want to run
a special piece of code in response to a specific error:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Output:
Variable x is not defined
Exception Handling in Python

Else
You can use the else keyword to define a block of code to be executed if no errors
were raised:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Output:
Hello
Nothing went wrong
Exception Handling in Python

finally
The finally block, if specified, will be executed regardless if the try block raises an
error or not.
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Output:
Something went wrong
The 'try except' is finished
Exception Handling in Python

Raise an exception
The developer can throw an exception in python if some condition is satisfied.
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")

Output:
Traceback (most recent call last):
File "C:/Users/Jose/Desktop/demo1.py", line 3, in <module>
raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero
Python Excersies

Write a Python function to find the Max of three numbers.

def max_of_three( x, y,z ):


if x > y and x>z:
print("Greatest no is{}, ".format(x))
if y>x and y>z:
print("Greatest no is{}, ".format(y))
else:
print("Greatest no is{}, ".format(z))
print(max_of_three(3, 6, -5))

Greatest no is6,
Python Excersies

Write a Python function to sum all the numbers in a list.

l1=[2,4,6,8]
sum=0
for i in range(0,len(l1)):
sum=sum+l1[i]
print("Addiiton of all the elements in the list ",sum)

Addition of all the element in the list 20


Python Excersies

Write a Python function to multiply all the numbers in a list

l=[2,3,4,5]
x=1
for i in range(0,len(l)):
x=x*l[i]
print("Multiply all the numbers in a list ",x)

Multiply all the numbers in a list 120


Python Excersies

Write a Python program to reverse a string.

def reverse(str):
rstr=""
l=len(str)
while l>0:
rstr=rstr+str[l-1]
l=l-1
return rstr
print(reverse("Amma"))

ammA
Python Excersies

Write a Python function to calculate the factorial of a number (a non-


negative integer).

def fun(x):
p=1
for i in range(x):
p=p+p*i
return p
print("The factorial of 5 is{} ".format(fun(5)))

The factorial of 5 is 120


Python Excersies

Write a Python function to check whether a number falls in a given range.

def test(n):
if n in range(10,20):
print(n, "Within the range {} {}".format(10,20))
else:
print(n, "Not within the range{}{}".format(10,20))
test(19)

19 Within the range 10 20


Python Excersies

Write a Python function that accepts a string and calculate the number of
upper case letters and lower case letter

def test(str):
l=0
u=0
for ch in str:
if ch.isupper():
u=u+1
else:
l=l+1
print("Number of Upper case letters ",u)
print("Number of Lower case letters ",l)
test("MoseS")

Number of Upper case letters 2


Number of Lower case letters 3
Python Excersies

Write a Python function that takes a number as a parameter and check


the number is prime or not.

def test_prime(n):
flag=0
x=2
while x<=n/2:
if n%x==0:
flag=1
break
x=x+1
if flag==0:
print(n, "is prime")
else:
print(n, "is not a prime")
test_prime(5555)

5555 is not a prime


Python Excersies

Write a Python program to print the even numbers from a given list.

def even(l):
print("List of Evene numbers in the list are")
for x in l:
if x%2==0:
print(x)

even([1,2,3,4,5,6,7,8,9])
Python Excersies

Write a Python function that takes a list and returns a new list with
unique elements of the first list.

def unique_list(l):
x=[]
for a in l:
if a not in x:
x.append(a)
return x
print(unique_list([1,2,2,3,3,4,5,6,6,7,8,9,10,10]))

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Searching

Searching in data structure refers to the process of finding the required


information from a collection of items stored as elements in the computer
memory. These sets of items are in different forms, such as an array, linked
list, graph, or tree

Two types of search algorithms


1. Linear Search
2. Binary Search
Searching

Searching in data structure refers to the process of finding the required


information from a collection of items stored as elements in the computer
memory. These sets of items are in different forms, such as an array, linked
list, graph, or tree

Two types of search algorithms


1. Sequential Search
2. Binary Search
Searching

Sequential Search
This is the traditional technique for searching an element in a collection of
elements. In this type of search, all the elements of the list are traversed one
by one to find if the element is present in the list or not. One example of such
an algorithm is a linear search. This is a straightforward and basic algorithm.
Algorithm:
Step 1: Declare the list or array of elements.

10 7 1 3 -4 2 20
Searching

Sequential Search
Algorithm:
Step 2: Lets search for the element 3?
Step 3: Start from the beginning of the array or list.
Step 4: Compare or check the first element of the array. Is it 3?
No. Then move to the next element. Again, repeat the same
process until the last element is reached.
Step 5: If element is found , return the index of the element. Otherwise just
display that element is not found.
Searching

Sequential Search

10 7 1 3 -4 2 20

X=3 (Searching element)

X!=10 thus we move to the next element.

10 7 1 3 -4 2 20
Searching

Sequential Search

10 7 1 3 -4 2 20

X=3 (Searching element)

X!=7 thus we move to the next element.


Searching

Sequential Search

10 7 1 3 -4 2 20

X=3 (Searching element)

X!=1 thus we move to the next element.


Searching

Sequential Search

10 7 1 3 -4 2 20

X=3 (Searching element)

X==3 Here the condition is satisfied. Just return


the position and come out.
Searching

Sequential Search (Algorithm) Case 1:


l=[4,10,16,24,32,46,76,112,144,182] Enter an element to search
print("Enter an element to search") 23
Element is not found
x=int(input(""))
pos=0 Case 2:
Enter an element to search
for i in range(len(l)): 46
if x==l[i]: Element is found at 6
pos=i+1
break
if pos==0:
print("Element is not found")

else:
print("Element is found at ", pos)
Searching
Binary Search
Step 1: In binary search divide the sorted array into tow parts.
Mid=(first+last)/2

Step 2: Now we will get the index number of middle element.

Step 3: Check whether the number present at this index is equal to the
number(to be search or not).

Step 4: If it is equal, then stop searching. Return the value of that index.

Step 5: If not, whether the given number is greater than or less than the
number present at the middle index or not.

Step 6: If it is greater than number present at the middle index , then skip
the lower part and process the upper part using the same logic as used from
the first step.
replace first index by (middle+1)
Searching
Binary Search
Step 7: If the number is small, then skip the upper part, and process the
lower part using the same logic .
replace last index by (middle-1)

Step 8: Continue checking until the value is found or the interval becomes 0.
Searching
Binary Search
Searching
Binary Search
Searching
Binary Search
Searching
Binary Search
Searching
Binary Search
l=[4,10,16,24,32,46,76,112,144,182]
print("Enter an element to search")
x=int(input(""))
first=0
last = len(l)-1
while( first<=last):
mid = (first + last)//2
if l[mid] == x :
print("The element is available at Index No." ,mid);
break;
else:
if x< l[mid]:
last = mid - 1
else:
first = mid + 1
Searching
Binary Search
Output:
Case 1:
Enter an element to search
4
The element is available at Index No. 0
Case 2:
Enter an element to search
100
>>>
Python String Formatting

Python uses C-style string formatting to create new, formatted strings. The "%"

operator is used to format a set of variables enclosed in a "tuple" (a fixed size list),

together with a format string, which contains normal text together with "argument

specifiers", special symbols like "%s" and "%d".

Let's say you have a variable called "name" with your user name in it, and you would

then like to print(out a greeting to that user.)

>>> name="Rojer"

>>> print("Hello,%s!"%name)

Hello,Rojer!
Python String Formatting

To use two or more argument specifiers, use a tuple (parentheses):

>>> name="John"

>>> age=25

>>> print("%s is %d years old"%(name,age))

John is 25 years old


Python String Formatting

Any object which is not a string can be formatted using the %s operator as well.

>>> list1=[2,3,4,5,6]

>>> print("A list:%s"%list1)

A list:[2, 3, 4, 5, 6]
Python String Formatting

Here are some basic argument specifiers you should know:


%s - String (or any object with a string representation, like numbers)

%d - Integers

%f - Floating point numbers

%.<number of digits>f - Floating point numbers with a fixed amount of


digits to the right of the dot.

%x/%X - Integers in hex representation (lowercase/uppercase)


Python String Formatting

Exercise

You will need to write a format string which prints out the data using the

following syntax: Hello John Doe. Your current balance is $53.44.

>>> data = ("John", "Doe", 53.44)

Solution
Python String Formatting

>>> print("Hello %s %s. Your current balance is $%f"%(data[0],data[1],data[2]))

Hello John Doe. Your current balance is $53.440000

>>> print("Hello %s %s. Your current balance is $%.2f"%(data[0],data[1],data[2]))

Hello John Doe. Your current balance is $53.44


Numpy Arrays

Numpy arrays are great alternatives to Python Lists.

Some of the key advantages of Numpy arrays are that

 they are fast

 easy to work with

 give users the opportunity to perform calculations across entire arrays


Example

>>> import numpy as np

>>> a = np.arange(15).reshape(3, 5)

>>> a

array([[ 0, 1, 2, 3, 4],

[ 5, 6, 7, 8, 9],

[10, 11, 12, 13, 14]])

>>> a.shape

(3, 5)
Example

>>> a.ndim
2
>>> a.dtype
dtype('int32')
>>> a.itemsize
4
>>> a.size
15
>>> b = np.array([6, 7, 8])
>>> b
array([6, 7, 8])
Example - Array creation

>>> a = np.array([2, 3, 4])


>>> a
array([2, 3, 4])
>>> a = np.array(1, 2, 3, 4) # WRONG
>>> a = np.array([1, 2, 3, 4]) # RIGHT
Array transforms sequences of sequences into two-dimensional arrays
>>> b = np.array([(1.5, 2, 3), (4, 5, 6)])
>>> b
array([[1.5, 2. , 3. ],
[4. , 5. , 6. ]])
Example - Array creation

The type of the array can also be explicitly specified at creation


time:
>>> c = np.array([[1, 2], [3, 4]], dtype=float)
>>> c
array([[1., 2.],
[3., 4.]])
Example - Array creation

The function zeros creates an array full of zeros, the function ones
creates an array full of ones, and the function empty creates an
array whose initial content is random and depends on the state of
the memory. By default, the dtype of the created array is float64,
but it can be specified via the key word argument dtype.
>>> np.zeros((3, 4))
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
Example - Array creation

>>> np.ones((3, 4))


array([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
>>> np.ones((2, 3), dtype=np.int16)
array([[1, 1, 1],
[1, 1, 1]], dtype=int16)
Example - Array creation

>>> np.ones((2, 3,4), dtype=np.int16)


array([[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]],

[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]], dtype=int16)
Example - Array creation

To create sequences of numbers, NumPy provides the arange


function which is analogous to the Python built-in range, but
returns an array.
Printing Arrays
>>> a = np.arange(6) #Single dimensional
>>> a
array([0, 1, 2, 3, 4, 5])
Example - Array creation

>>> b = np.arange(12).reshape(4, 3) # two dimensional


>>> b
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
Basic Operations

a = np.array([20, 30, 40, 50])


b = np.arange(4)
b
array([0, 1, 2, 3])
c=a-b
c
array([20, 29, 38, 47])
Basic Operations

>>> b
array([0, 1, 2, 3])
>>> b*2
array([0, 2, 4, 6])
>>> b**2
array([0, 1, 4, 9], dtype=int32)
>>> a<35
array([ True, True, False, False])
>>> a
array([20, 30, 40, 50])
Basic Operations

>>> b
array([0, 1, 2, 3])
>>> b*2
array([0, 2, 4, 6])
>>> b**2
array([0, 1, 4, 9], dtype=int32)
>>> a<35
array([ True, True, False, False])
>>> a
array([20, 30, 40, 50])
Basic Operations

>>> A
array([[1, 1],
[0, 1]])
>>> B = np.array([[2, 0],
... [3, 4]])
>>> B
array([[2, 0],
[3, 4]])
>>> A*B
array([[2, 0],
[0, 4]])
>>> A@B
array([[5, 4],
[3, 4]])
Numpy Arrays

In the following example, you will first create two Python lists. Then, you
will import the numpy package and create numpy arrays out of the newly
created lists.
>>> height = [1.87, 1.87, 1.82, 1.91, 1.90, 1.85]
>>> weight = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]
>>> import numpy as np
>>> np1=np.array(height)
>>> np2=np.array(weight)
Print out the type of np1
>>> print(type(np1))
<class 'numpy.ndarray'>
Numpy Arrays

Element-wise calculations
Now we can perform element-wise calculations on height and weight. For
example, you could take all 6 of the height and weight observations above,
and calculate the BMI for each observation with a single equation. These
operations are very fast and computationally efficient. They are particularly
helpful when you have 1000s of observations in your data.
>>> bmi = np1/ np2** 2
>>> print(bmi)
[0.0002805 0.00019663 0.0002006 0.00022093 0.00025582 0.00023647]
Numpy Arrays

Exercise
First, convert the list of weights from a list to a Numpy array. Then, convert
all of the weights from kilograms to pounds. Use the scalar conversion of 2.2
lbs per kilogram to make your conversion. Lastly, print the resulting array of
weights in pounds.
>>> weight_kg = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]
>>> import numpy as np
>>> ap1=np.array(weight_kg)
>>> wlbs=ap1*2.2
>>> print(wlbs)
[179.63 214.544 209.55 204.556 189.596 194.59 ]
Pandas Basics

Pandas is a high-level data manipulation tool developed by Wes McKinney. It


is built on the Numpy package and its key data structure is called the
DataFrame. DataFrames allow you to store and manipulate tabular data in
rows of observations and columns of variables.

There are several ways to create a DataFrame. One way way is to use a
dictionary. For example:
Pandas Basics

>>> dict = {"country": ["Brazil", "Russia", "India", "China", "South Africa"],


"capital": ["Brasilia", "Moscow", "New Dehli", "Beijing", "Pretoria"],
"area": [8.516, 17.10, 3.286, 9.597, 1.221], "population": [200.4, 143.5,
1252, 1357, 52.98] }
>>> import pandas as pd
>>> brics=pd.DataFrame(dict)
>>> print(brics)
country capital area population
0 Brazil Brasilia 8.516 200.40
1 Russia Moscow 17.100 143.50
2 India New Dehli 3.286 1252.00
3 China Beijing 9.597 1357.00
4 South Africa Pretoria 1.221 52.98
>>>
Pandas Basics

As you can see with the new brics DataFrame, Pandas has assigned a key for
each country as the numerical values 0 through 4. If you would like to have
different index values, say, the two letter country code, you can do that
easily as well.
>>> brics.index=["BR","RU","IN","CH","SA"]
>>> print(brics)
country capital area population
BR Brazil Brasilia 8.516 200.40
RU Russia Moscow 17.100 143.50
IN India New Dehli 3.286 1252.00
CH China Beijing 9.597 1357.00
SA South Africa Pretoria 1.221 52.98
>>>
Pandas Basics

Another way to create a DataFrame is by importing a csv file using Pandas.


Now, the csv cars.csv is stored and can be imported using pd.read_csv:
import pandas as pd
# Import the cars.csv data:
carscars = pd.read_csv('cars.csv’)
# Print out carsprint(cars)
Infytq Questions and Answers

Which of the following operators cannot be used on sets?

Explanation: Python sets don't have an implementation for the +


operator. You can use | for set union and & for set intersection.
In python sets
- is difference
^ is symmetric difference
== is equality operator
Infytq Questions and Answers

What is the output of code below?

Explanation:
== is equality operator which gives True if both are equal otherwise
False
Infytq Questions and Answers

What is the output of code below?

Explanation:
Cannot append elements to tuple because tuples are immutable
Infytq Questions and Answers
Set is
What is the output of code below statement? mutable
and has no
duplicate
elements

Explanation:
In sets True is evaluated to 1. now x becomes {1,1,(\"a\",\"b\",\"a\")}
after removing duplicates length of x is 2.
Infytq Questions and Answers

What is the output of code below?


Iteration
start from
index 1

Explanation:
The all() function returns True if all items in an iterable are true,
otherwise it returns False.In case of dictionaries it checks keys.
Infytq Questions and Answers

What is the output of code below?


5%2=1
3*7=21
1+21=22

Explanation:
The eval() function evaluates the specified expression, if the
expression is a legal Python statement, it will be executed.
eval() function used to evaluate infix expression.
Infytq Questions and Answers

What is the output of code below?


>>> mylist = iter(["Bumrah", "Virat", "Hardik"])
>>> x = next(mylist)
>>> x

Explanation:
Next() gives the next iterator in given list.
Infytq Questions and Answers

What is the output of code below?

a) 8 b) 4096 c) 32 d) 0

Explanation:
Python number method pow() returns x to the power of y. If the
third argument (z) is given, it returns x to the power of y
modulus z, i.e. pow(x, y) % z.
.
Infytq Questions and Answers

Which of the following method is used to add elements to a list


at a particular index?

Explanation:
insert() function is used to add elements at particular index.
Infytq Questions and Answers

What is the output of code below?

Explanation:
x=st.split(\’a\’) x becomes ,
x=[\’C\’, \’dbury D\’, \’iry Milk\’]
length of x is 3.
Infytq Questions and Answers
What is the output of code below?
st=”Happy Christmas and Happy new
year”
if(st.startswith(“Happy”)):
x=st.rsplit(“Happy”)
print(len(x))

Explanation:
rstrip()-splits string at specified separator and returns string
startswith()-returns true if the string starts with specified value.
Infytq Questions and Answers
What is the output of code below?
Infytq Questions and Answers
Q1: Input: a string of comma separated numbers. The numbers 5 and 8
are present in the listAssume that 8 always comes after 5.

Case 1: num1 = add all numbers which do not lie between 5 and 8 in the
input.
Case 2: num2= numbers formed by concatenating all numbers from 5 to 8.
Output: sum of num1 and num2
Example: 1) 3,2,6,5,1,4,8,9
Num1 : 3+2+6+9 =20
Num2: 5148
output: 5248+20 = 5168
Infytq Questions and Answers

array = list(map(int,input().split(",")))
#print(array[:array.index(5)])
#print(array[array.index(8) + 1:])
number1 = sum(array[:array.index(5)]) + sum(array[array.index(8) + 1:])
#print(number1)
l = array[array.index(5):array.index(8) + 1]
#print(l)
number2=""
for i in l:
number2=number2+str(i)
print(int(number2)+number1)

You might also like