SlideShare a Scribd company logo
A Brief Introduction
to
Python
By.
Deepak Teja. P
Agenda
 What is a programming language ? & why we use it ?
 Different Programming languages.
 What is Python…?
 History of Python
 Scope of Python
 Applications of Python?
 Installing Python IDE
 What can I do with python
 A Sample Code.
What is a programming language ?
& why we use it ?
Different Programming languages.
 High Level Language
- High level languages are written in a form that is
close to our human language, enabling to programmer
to just focus on the problem being solved.
- No particular knowledge of the hardware is needed
as high level languages create programs that are
portable and not tied to a particular computer or micro
chip. These programmer friendly languages are called
‘high level’ as they are far removed from the machine
code instructions understood by the computer.
- It considers only Business logics but memory
issues are taken care by garbage collector
 Low level language
- Low-level languages are written to meet the needs
of particular computer architecture and hardware
requirements. Machine code is low level because it runs
directly on the processor. Low-level languages are
appropriate for writing operating systems or firmware for
micro-controllers.
-It considers only Memory issues
Note: Business logic is the programming that manages communication
between an end user interface and a database. The main components
of business logic are business rules and workflows.
Examples
 High Level Language
◦ Java, Python, Pascal, COBOL, FORTRAN,
BASIC
 Middle Level Language
◦ C,
 Low Level Language
◦ Assembly language (Assembler, Forth)
What is Python…?
 Python is a general purpose
programming language that is
often applied in scripting roles.
 So, Python is programming
language as well as scripting
language.
 Python is also called as Interpreted
language
Differences between program and
scripting language
 Basically, all scripting languages are
programming languages. The theoretical
difference between the scripting language
and programming language is that in case
of programming language we need to save
the program then compile and then run it,
but in script language like java script we
have to save the code and then direct run it
we need not to compile the script language
program.
History of Python
Guido van Rossum
 Developed in 1991
 Originally Started in 1989
 Developed by Guido Van Rosbum in
Netherlands
 Name python came from a comic show
“Monty’s python flying circus comic show”
telecasted in BBC-Netherlands from 1967
to 1974
Versions of Python
 Version 1.0 to 1.x
 25 October 1996- 5 September 2000.
 Version 2.0 to 2.x
 16 October 2000- 02 March 2019
 Version 3.0 to 2.x
 3 December 2008- 25 March 2019.
Applications of Python
 Web Applications
 Desktop GUI (graphical user interface)
Applications
 Software Development
 Scientific and Numeric
 Business Applications
 Embedded System development
 IoT Development
 Windows Azur
 Devops
 Network Applications
 Game Development, Etc.,
 Advantages Python
◦ Less code
◦ Simple Syntax
◦ Faster Execution
 Features of Python
◦ Easy to Read
◦ Easy to Maintain
◦ Easy to learn
Installation of Python
 Python is pre-installed on most Unix
systems, including Linux and MAC
OS X
 But for in Windows Operating Systems
, user can download from the
https://www.python.org/downloads/
 From the above link download latest
version of python IDE and install,
recent version is 3.7.3 but most of
them uses version 2.7.7 only
Who uses python
 Google makes extensive use of Python
in its web search system, and
employs Python’s creator.
 Intel, Cisco, Hewlett-Packard, Seagate,
Qualcomm, and IBM use Python for
hardware testing.
 ESRI (Environmental Systems Research Institute)
uses Python as an end-user
customization tool for its popular GIS
mapping products.
 The YouTube video sharing service is
largely written in Python.
What we can do with Python
 Graphical User Interface Programming
Internet Scripting
 Gaming, Images, XML , Robot and
more
 System programming
 Component Integration Database
Programming
Python Code Execution
PVM is which help to execute the python program.
PVM: Python Virtual Machine
 More to Discuss:
-Python is a case sensitive language
-Difference between Command prompt &
IDLE
IDLE(Interactive development
environment)
-Example of Python Program
What are operators in python?
 Operators are special symbols in
Python that carry out arithmetic or
logical computation. The value that the
operator operates on is called the
operand.
Operators in Python
 Arithmetic Operators
◦ +, -, *, /, %, //
 Comparison/Relational Operators
◦ <, >, <=, >=, ==, !=
 Logical Operators
◦ AND, OR, NOT
 Bit Wise Operators
◦ &, | , ~, x, ^
 Assignment Operators
◦ ==, *=, +=, -=, /=
 Difference between %, // & /
5 / 2 will return 2.5 and 5 // 2 will return 2 . The
former is floating point division, and the latter is floor
division, sometimes also called integer division.
% : Gives the reminder of the two numbers.
Example:
x= 4
y= 2
print(x%y)
print(x//y)
print(x/y)
 Output:
◦ 0
◦ 2
◦ 2.0
Comparison/Relational
Operators
 Comparison or Relational operators are used to
compare two things or to find the relation between
two entities.
 == Equals to
 != Not equals
 Example:
x=4
y=3
print(x==y)
print(x!=y)
Output:
False
True
Logical gates
 AND gate  OR gate
 Not gate  ExOR gate
Logical Operators
 And:
True if both the operands are true x and
y
 Or:
True if either of the operands is true x or
y
 Not:
True if operand is false (complements
the operand)
Example:
x=1
y=0
print(x and y)
print(x or y)
print(not x)
Output:
0
1
False
Bit Wise Operators
 & : And
 |: OR
 ~ : Complement/NOT
 ^ : XOR
 >> : Right Shift
 << : Left Shift
 Note: Bit wise operator first converts given
number into a binary number and performs
the operations
Example of Bit Wise operator
a = 10
b = 4
Print bitwise AND operation
print(a & b)
Print bitwise OR operation
print(a | b)
Print bitwise NOT operation
print(~a)
Print bitwise XOR operation
print(a ^ b)
Print bitwise right shift operation
print(a >> 2)
print bitwise left shift operation
print(a << 2)
Output
0
14
-11
14
2
40
Difference between Logical & Bit
wise operators
Example :
x=1
y=0
a=True
b=False
print(x and y)
print(x or y)
print(not x)
print(not y)
print(not a)
print(not b)
print(x&y)
print(x|y)
print(a & b)
print(a | b)
print(~x)
Output:
0
1
0
1
False
True
0
1
False
True
Assignment Operators
 == or =
 +=
 -=
 *=
 /=
Number conversions
S.No Type Python Number Representation
in output
1 Binary Bin 2 0b
2 Octal Oct 8 0o
3 Hexadecimal hex 16 0x
Decimal Conversions
 To convert Octal, Hexadecimal, Binary
to decimal we can use below
statement.
 Binary to Decimal
◦ print(int(“Binary number”,2))
 Octal to Decimal
◦ print(int(“Octal”,8))
 Hexadecimal to Decimal
◦ print(int(“Hexadecimal”,16))
Variables
 variable is a
◦ name.
◦ refers to a value.
◦ holds the data
◦ name of the memory location.
Note: To find the memory location of a variable we can
use below statement
>>>X=10
>>>print(id(x))
Properties of variable
 Every variable has a,
◦ Type
◦ Value
◦ Scope
◦ Location
◦ Life time
 Creating variable
◦ In python, to create a variable we need to
specify, The name of the variable
◦ Assign a value to name of the variable.
 Variables names,
Should not give as keywords
names, otherwise we will get error.
 We can assign multiple variables to
multiple values in single line.
 Example:
>>> a, b, c = 1, 2, 3
>>> print(a, b, c)
Output:
1 2 3
Data types
 A data type represents the type of the
data stored into a variable or memory
Note: We use type() in-built or predefined function in python.
Different types of data types
 There are two type of data types.
◦ Built-in data types:
 The data types which are already available in
python are called built-in data types.
◦ User defined data types:
 Data types which are created by programmer
Built-in data types
1. Numeric types
◦ int
◦ float
◦ complex
2. bool (boolean
type)
◦ True
◦ False
3. None
4. Str (string)
5. bytes
6. bytearray
7. list
8. set
9. tuple
10. dict
11. range
More to Discuss
 Exponential values in integers.
◦ 2E2 or 2e2
◦ Comparing complex numbers
◦ Case sensitivity in complex
values/numbers
◦ Adding Boolean values
◦ Printing none values
◦ How to create a string
Bytes
 bytes data type
◦ bytes data type represents group of numbers
just like an array
◦ bytes data type can store the values which
are from 0 to 256.
◦ bytes data type cannot store negative
numbers.
To create a byte data type
◦ First, we need to create list.
◦ The created list we need to pass to bytes()
function as a parameter
 Note: bytes data type is immutable means we cannot
modify or change the bytes object.
How to create a bytes
 To create a bytes first we need to create a list with [ ] a
variable name
 Then assign the created list to another variable by
stating it as byte as below
 Example:
>>>a= [1,2,3,4,5,]
>>>b= bytes(a)
>>>print(b)
>>>print(type(a))
 Output:
[1,2,3,4,5,]
<class 'bytes'>
bytearray data type
 bytearray is same as bytes data type,
but bytearray is mutable means we
can modify the content of bytearray
data type.
 The created list we need to pass as
bytearray() parameter
How to create a bytearray()
 First, we need to create list.
 The created list we need to pass as
bytearray() parameter
 It is as same as creating a bytes()
>>>x = [10, 20, 30, 40, 15]
>>>y = bytearray(x)
>>>print(type(y))
>>>print(y)
Output:
<class bytearray>
[10, 20, 30, 40, 15]
Modifying bytearray()
 We can modify the bytearray as it is a
mutable list as below
>>>x=[10,20,30,40,50]
>>>y=bytearray(x)
>>>print(y)
>>>y[3]=99
>>>print(y)
Output:
[10,20,30,40,50]
<class bytearray>
List
 We can create list data structure by
using square brackets [ ]
 list can store different data types
 list is mutable.
 Examples of list:
◦ [1,2,3,4,5]
◦ [1,2,’3x’,’x’,’y’,-2]
◦ [1,2,'3x','x','y',-2,{1,2,3,4}]
Python has a set of built-in
methods.
 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
append()
>>>a=['apple','boy','cat']
>>>a. append('dog')
>>>print(a)
O/p: apple, boy cat,dog
clear()
>>>a=['apple','boy','cat']
>>>a.clear()
>>>print(a)
O/p: [ ]
Copy()
>>>a=['apple','boy','cat']
>>>b=a. copy()
>>>print(b)
O/p:
apple, boy, cat
Count():
>>>a=[1,2,3,3,3,3,3,3,5,6]
>>>b=a.count(3)
>>>print(b)
O/p:
6
Extend()
>>>a=['apple','boy','cat']
>>>b=['dog','egg']
>>>a.extend(b)
>>>print(a)
O/p:
['apple','boy','cat‘, 'dog','egg']
Index()
>>>a=['apple','boy','cat']
>>>b=a.index('boy')
>>>print(b)
O/p:
1
sort()
>>>cars = ['Ford', 'BMW', 'Volvo']
>>>cars.sort()
>>>print(cars)
O/p:
[‘BMW’, ‘Ford’,’Volvo’]
reverse()
>>>fruits = ['apple', 'banana', 'cherry']
>>>fruits.reverse()
>>>print(fruits)
O/p:
[‘cherry’, ‘banana’, ’apple’]
remove()
>>>fruits = ['apple', 'banana', 'cherry']
>>>fruits.remove("banana")
>>>print(fruits)
O/p:
[‘apple’,’cherry’]
Pop():
>>>fruits = ['apple', 'banana', 'cherry']
>>>fruits.pop(1)
>>>print(fruits)
O/p:
[‘apple’, ‘cherry’]
Insert():
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
print(fruits)
O/p:
[‘apple’, ’orange’,’banana’,’cherry’]
tuple
 We can create tuple data structure by
using parenthesis ()
 tuple can store different data types.
 tuple is immutable.
 Examples of tuple:
 (1,2,3,4)
Examples of tuple
Creating a tuple
>>>a=(1,2,3,4,5)
>>>print(a)
>>>print(type(a))
O/p:
(1,2,3,4)
<class ‘tuple’>
Access Tuple Items
>>>a=("apple","boy","cat")
>>>print(a)
>>>print(a[1])
O/p:
Boy
Checking the presence of tuple
>>>a=("apple","boy","cat")
>>>if "apple" in a:
>>>print("yes apple is there in the given tuple")
O/p:
Yes apple is there in the given tuple
To print length of tuple
>>>a=(“apple”,”boy”,”dog”)
>>>print(len(a))
O/p:
3
Tuple as a constructor:
>>>a=tuple(("apple","boy","cat"))
>>>print(a)
>>>print(type(a))
O/p:
(“apple”,”boy”,”cat”)
<class “tuple”>
 Methods in tuples:
Count()
Index()
More to Discuss
1. Can we add elements into a tuple
2. Can we remove elements from the
tuple
3. Can we delete entire tuple
range()
 We can create a range of values by
using range() function
 The range datatype represents a
sequence of numbers.
 range data type is immutable, means
we cannot modify once it created.
 range data type values can be print by
using for loop.
Example of range()
>>>a=range(5)
>>>print(a)
>>>for x in a:
>>>print(x)
Output:
range(0, 5)
0
1
2
3
4
Note: We can create a list of values with range data
type
Program Creating list of values
>>>a=list(range(1, 10))
>>>print(a)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
 By using index, we can access
elements present in the range data
type
>>>a=range(1, 10)
>>>print(a[0])
>>>print(a[1])
Output:
1
2
 A set is a collection which is unordered
and un-indexed. In Python sets are
written with curly brackets { }.
 You cannot access items in a set by
referring to an index, since sets are
unordered the items has no index.
 But you can loop through the set items
using a for loop, or ask if a specified
value is present in a set, by using the
“in” keyword.
 Once a set is created, you cannot
change its items, but you can add new
Set
Add Items
 To add one item to a set use the add() method.
 To add more than one item to a set use the update() method.
 Example:
>>>a={"apple","boy","cat"}
>>>print(type(a))
>>>a.add("dog")
>>>print(a)
>>>a.update(["nanna","flask"])
>>>print(a)
O/p:
<class,set”>
{‘apple’,’boy’,’cat’,’dog’}
{‘apple’,’boy’,’cat’,’dog’, ‘nanna’, ‘flask’}
 Printing a set:
>>>a={“apple”,”boy”,”cat”}
>>>print(a)
O/p:
Cat
Apple
Boy
To print the output in a sequence:
>>>a={“apple”,”boy”,”cat”}
>>>for x in a
>>>print(a)
O/p:
apple
boy
cat
 To find the presence of an element:
>>>a={“apple”,”boy”,”cat”}
>>>print(“boy” in a)
O/p:
True
 We can find the length of “set” by
using “len()”
 We can perform remove() & discard(),
both are same
>>>a={“apple”,”boy”,”cat”}
>>>a.remove(“apple”)
>>>a.discard(“cat”)
>>>print(a)
O/p:
boy
 pop()
We can perform pop() also but as the
set() is unordered so it will delete the
last element of the set
>>>a={"apple","boy","cat","dog"}
>>>a.pop()
>>>print(a)
O/p:
Boy
Cat
dog
 We can also perform clear(), del() on the set
as below
>>>a={"apple","boy","cat","dog"}
>>>a.clear()
>>>print(a)
O/p:
{ }
Del():
>>>a={"apple","boy","cat","dog"}
>>>del a
>>>print(a)
O/p:
error
Methods in set{ }
 add(): Adds an element to the set
 clear(): Removes all the elements from the set
 copy(): Returns a copy of the set
 difference(): Returns a set containing the difference between two or more sets
 difference_update(): Removes the items in this set that are also included in
another, specified set
 discard(): Remove the specified item
 intersection(): Returns a set, that is the intersection of two other sets
 intersection_update():Removes the items in this set that are not present in other,
specified set(s)
 isdisjoint(): Returns whether two sets have a intersection or not
 issubset(): Returns whether another set contains this set or not
 issuperset(): Returns whether this set contains another set or not
 pop(): Removes an element from the set
 remove(): Removes the specified element
 symmetric_difference(): Returns a set with the symmetric differences of two sets
 symmetric_difference_update(): inserts the symmetric differences from this set
and another
 union(): Return a set containing the union of sets
 update(): Update the set with the union of this set and othersTest
Copy
>>>a={“apple”,”boy”,”cat”}
>>>b=a.copy()
>>>print(b)
O/p:
{“apple”,”boy”,”cat”}
Difference
>>>a={“apple”,”boy”,”cat”}
>>>b={“man”,”nest”,”apple”}
>>>z=a.difference(b)
O/p:
“man”,”nest”
Difference_update()
>>>a={“apple”,”boy”,”cat”}
>>>b={“man”,”nest”,”apple”}
>>>a.difference_update(b)
O/p:
“man”,”nest”
Intersection()
>>>a={"apple", "boy","cat"}
>>>b={"man","nest","apple" }
>>>z=a.intersection(b)
>>>print(z)
O/p:
apple
Intersection_update():
>>>a={"apple", "boy","cat"}
>>>b={"man","nest","apple" }
>>>a.intersection_update(b)
>>>print(a)
O/p:
{“apple”}
isdisjoint()
>>>a={"apple", "boy","cat"}
>>>b={"man","nest","apple" }
>>>z=a.isdisjoint(b)
>>>print(z)
O/p:
False
issubset()
>>> a={‘a’,’b’,’c’,’d’,’e’,’f’}
>>> b={‘a’,’b’,’c’}
>>> d=b.issubset(a)
print(d)
O/p:
True
Issuperset():
>>>x = {"f", "e", "d", "c", "b", "a"}
>>> y = {"a", "b", "c"}
>>> z = x.issuperset(y)
>>> print(z)
O/p:
True
symmetric_difference():
>>>x = {"apple", "banana", "cherry"}
>>>y = {"google", "microsoft", "apple"}
>>>z = x.symmetric_difference(y)
>>>print(z)
O/p:
{"google", "microsoft",
“banana”,”cherry”}
Can also use the pop(), method to remove an item,
but this method will remove the last item.
Remember that sets are unordered, so you will not
know what item that gets removed.
 The return value of the pop() method is the
removed item.
Remove the last item by using the pop() method:
>>>a = {"apple", "banana", "cherry"}
>>>x = a.pop()
>>>print(x)
>>>print(a)
O/p:
{“apple”,”boy”}
symmetric_difference_update():
>>>x = {"apple", "banana", "cherry"}
>>>y = {"google", "microsoft", "apple"}
>>>x.symmetric_difference_update(y)
>>>print(x)
O/p:
{'google', 'cherry', 'microsoft', 'banana'}
union():
>>>x = {"apple", "banana", "cherry"}
>>>y = {"google", "microsoft", "apple"}
>>>z = x.union(y)
>>>print(z)
O/p:
{'banana', 'apple', 'google', 'microsoft', 'cherry'}
update():
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.update(y)
print(x)
O/p:
{'microsoft', 'cherry', 'apple', 'google', 'banana'}
Dictionary
 A dictionary is a collection which is
unordered, changeable and indexed. In
Python dictionaries are written with curly
brackets,{ } and they have keys and
values.
 Example:
>>>x={1:10}
>>>print(x)
>>>print(type(x))
O/p:
{1,10}
<class ‘dict’>
Can access the items of a dictionary by referring to its key
name, inside square brackets:
A={“animal”:”cat”, ”fruit”: “apple”, ”flower”:”Rose”}
print(type(a))
print(a[“flower”])
O/p:
<class “dict”>
Rose
Change Values:
A={“animal”:”cat”, ”fruit”: “apple”, ”flower”:”Rose”}
print(type(a))
print(a[“flower”])
A[“fruit”]=“Banana”
O/p:
<class “dict”>
{“animal”:”cat”, ”fruit”: “Banana”, ”flower”:”Rose”}
Print all key names in the dictionary, one by one:
>>>a={“animal”:”cat”, ”fruit”: “apple”, ”flower”:”Rose”}
>>>print(type(a))
>>>For x in a:
>>>print(x)
O/p:
<class “dict”>
animal
Fruit
flower
Printing all values in the dictionary, one by one:
>>>a={“animal”:”cat”, ”fruit”: “apple”, ”flower”:”Rose”}
>>>print(type(a))
>>>For x in a:
>>>print(a[x])
O/p:
Cat
Apple
Rose
We can also use the values() function to return values of a dictionary:
>>>a={"fruit": "apple", "animal": "cat","flower": "Rose"}
>>>print(a)
>>>for x in a.values():
>>> print(x)
O/p:
Apple
Cat
Rose
To print the complete “dict” we can also use below method:
>>>a={"fruit": "apple", "animal": "cat","flower": "Rose"}
>>>print(a)
>>>for x,y in a:
>>> print(x,y)
O/p:
{"fruit": "apple", "animal": "cat", "flower": "Rose"}
{"fruit": "apple", "animal": "cat", "flower": "Rose"}
We can also find the length of the dictionary:
>>>a={"fruit": "apple", "animal": "cat","flower":
"Rose"}
>>>print(a)
Print(len(a))
O/p:
3
To find the availability of elements in given dict:
>>>a={"fruit": "apple", "animal": "cat","flower":
"Rose"}
>>>if "animal" in a:
>>> print("Yes it is there")
O/p:
Yes it is there
Adding elements into given dict:
>>>a={"fruit": "apple", "animal": "cat","flower": "Rose"}
>>>print(a)
>>>a["color"]="Red"
>>>print(a)
O/p:
{“Color”: “Red, ”"fruit": "apple", "animal": "cat", "flower": "Rose“}
Deleting/Removing elements from dict:
>>>a={"fruit": "apple", "animal": "cat","flower": "Rose"}
>>>print(a)
>>>a["color"]="Red"
>>>print(a)
>>>a.pop("animal")
>>>print(a)
O/p:
{“Color”: “Red, ”"fruit": "apple", "animal": "cat", "flower": "Rose“}
{“Color”: “Red, ”"fruit": "apple", "flower": "Rose“}
Deleting an element from “dict” using del():
>>>a={"fruit": "apple", "animal": "cat","flower": "Rose"}
>>>print(a)
>>>del a[“flower”]
>>>print(a)
O/p:
{"fruit": "apple", "animal": "cat"}
To delete entire dict using del():
>>>a={"fruit": "apple", "animal": "cat","flower": "Rose"}
>>>print(a)
del a
print(a)
O/p:
Type Error
To copy a dict:
a={"fruit": "apple", "animal": "cat","flower": "Rose"}
print(a)
d=a.copy()
print(d)
O/p:
a={"fruit": "apple", "animal": "cat","flower": "Rose"}
a={"fruit": "apple", "animal": "cat","flower": "Rose"}
To clear a dict:
a={"fruit": "apple", "animal": "cat","flower": "Rose"}
print(a)
a.clear()
print(a)
O/p:
{ }
Python has a set of built-in
methods that you can use on
dictionaries. clear(): Removes all the elements from the dictionary
 copy(): Returns a copy of the dictionary
 fromkeys(): Returns a dictionary with the specified keys and
values
 get(): Returns the value of the specified key
 items(): Returns a list containing the 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
fromkeys():
>>>x=('man','can','van')
>>>y=0
>>>a=dict.fromkeys(x,y)
>>>print(a)
O/p:
{man:0,can:0,van:0}
get():
x={“animal”: “Zebra”, ”Flower”:”Rose”,”Color”:
“Red”}
y=x.get(“color”)
Print(y)
O/p:
Red
items():
>>>x={'flower':"Rose",'color':"Red",'animal':"rat"
}
>>>y=x.items()
>>>print(y)
O/p:
[('color', 'Red'), ('flower', 'Rose'), ('animal', 'rat')]
keys():
car = { "brand": "Ford", "model": "Mustang",
"year": 1964}
x = car.keys()
print(x)
O/p:
dict_keys(['brand', 'model', 'year'])
pop():
>>>x={'flower':"Rose",'color':"Red",'animal':"rat"}
>>>print(x)
>>>x.pop("animal")
>>>print(x)
O/p:
{'flower':"Rose",'color':"Red"}
popitem():
Remove the last item from the dictionary:
>>>x={'flower':"Rose",'color':"Red",'animal':"rat"}
>>>print(x)
>>>x.popitem( )
>>>print(x)
O/p:
{'flower': 'Rose', 'animal': 'rat'}
>>>car = { "brand": "Ford","model":
"Mustang","year": 1964}
>>>x = car.setdefault("color", "White")
>>>print(x)
O/p:
White
Update():
>>>a={"animal":"cow","flower":"lilly","food":"idly
"}
>>>a.update({"name":"archi"})
>>>print(a)
O/p:
{"animal":"cow","flower":"lilly","food":"idly“,
"name":"archi"}
Membership Operators
 Membership operators are useful to check whether
the given object is available in collection
(sequence) or not. (It may be string, list, set, tuple
and dict)
 There are two membership operators,
◦ In
◦ not in
Example:
x=[1,2,3,4,5]
print(10 in x)
print(1 in x)
print(1 not in x)
print(100 not in x)
Keywords in python
 The words which are reserved to do
specific functionality is called
reserved keywords words.
 Totally we have 33 keywords in python
 These are also case sensitive
 All are small letters except
 True
 False
 None
 Note: We cannot use a keyword as variable name,
function name or any other identifier.
List of Keywords
 False
 class
 finally
 is
 return
 None
 continue
 for
 lambda
 try
 True
 def
 from
 nonlocal
 while
 and
 del
 global
 not
 with
 as
 elif
 for
 yield
 assert
 else
 import
 pass
 break
 except
 in
 raise
Keyword: None
 None is a special constant in Python that represents the
absence of a value or a null value.
 It is an object of its own data type, the None Type. We cannot
create multiple None objects but can assign it to variables.
These variables will be equal to one another.
 Example:
>>> x = None
>>> y = None
>>> x == y
Output:
True
Functions in Python:
 What is a function?
 What is the use of a function
 Types of Function
What is a function & use of a
function
 A function is a set of statements that
take inputs, do some specific
computation and produces output. The
idea is to put some commonly or
repeatedly done task together and
make a function, so that instead of
writing the same code again and again
for different inputs, we can call the
function.
Types of Function
 Python provides built-in functions like
print(), etc. but we can also create our
own functions. These functions are
called user-defined functions.
 That means python has two types of
functions
1.User defined
2. Built-in function
Syntax of Function:
 def function_name(parameters):
"""docstring"""
 statement(s)
 Example of a function:
>>>def greet(name):
"""This function greets to the person
passed in as parameter""“
>>>print("Hello, " + name + ". Good
morning!")
greet(“Deepak”)
O/p:
Hello Deepak Good morning
Parameters
 Parameters are specified after the function name, inside
the parentheses. We can add as many parameters as
you want, just separate them with a comma.
Ex:
>>>def classing(num):
>>>print(num+ " " "one")
>>>classing("one")
>>>classing("two")
>>>classing("three")
O/p:
One one
two one
three one
Default Parameter Value:
 If we call the function without parameter, it uses the
default value:
>>>def apple(country="India"):
>>>print("I am from" " " +country)
>>>apple("Japan")
>>>apple("Nepal")
>>>apple()
>>>apple("Bhutan")
O/p:
I am from Japan
I am from Nepal
I am from India
I am from Bhutan
Passing a List as a Parameter:
 We can send any data types of parameter to a function
(string, number, list, dictionary etc.), and it will be
treated as the same data type inside the function.
>>>def my_number(number):
>>>for x in number:
>>>print(x)
>>>integers=[1,2,3,4,5]
>>>my_number(integers)
O/p:
1
2
3
4
5
Return Value:
 To let a function return a value, use the return statement
 Example:
def multiplication(number):
return 10*number
print(multiplication(1))
print(multiplication(2))
print(multiplication(3))
print(multiplication(4))
O/p:
10
20
30
40
Recursion:
 Python also accepts function recursion, which
means a defined function can call itself.
 Recursion is a common mathematical and
programming concept. It means that a
function calls itself. This has the benefit of
meaning that you can loop through data to
reach a result.
 The developer should be very careful with
recursion as it can be quite easy to slip into
writing a function which never terminates, or
one that uses excess amounts of memory or
processor power. However, when written
correctly recursion can be a very efficient and
mathematically-elegant approach to
programming.
Agenda:
 Conditions.
 Loops
 Oops
 Examples
Conditions in Python
 If condition
 If else condition
 If elif else condition
 Nested condition
If condition:
 We use “If condition” to check either a
condition is true or False. To move to
the next statement if the give condition
is satisfied .
 Syntax:
if expression:
Statement
else:
Statement
 Example:1
def fun():
X=10
Y=20
If x<y:
Print(“y is greater”)
O/p:
Y is greater
Example:2
Def fun():
X=30
Y=20
If x<y:
Print(y is greater)
O/p:
??????
If else:
Example:1
def fun():
X=10
Y=20
If x<y:
Print(“y is greater”)
Else:
Print(“x is greater”)
Fun()
O/p:
y is greater
Example:2
def fun():
X=20
Y=20
if x<y:
Print(“ x is greater”)
Else x>y:
Print(“y is greater”)
O/p:
????
If else elif:
def fun():
X=20
Y=20
if x<y:
Print(“ y is greater”)
elif x>y:
Print(“x is greater”)
Else:
Print(“both are equal”)
Fun()
O/p:
Both are equal
If else if:
 def fun(name):
 name=input("please enter your name: ")
 if name=="Deepak":
 print("Hai deepak How are you doing")
 elif name=="John":
 print("Hai John How are you doing")
 elif name=="Bob":
 print("Hai Bob How are you doing")
 elif name=="Cat":
 print("Hai Cat How are you doing")
 else:
 print("Hai" +name+ "How are you
doing")
 fun("name")
Nested if:
 There may be a situation when we
want to check for another condition
after a condition resolves to true. In
such a situation, we can use the
nested ifconstruct.
 In a nested if construct,we can have
an if...elif...else construct inside
another if...elif...else construct.
Syntax:
 if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
else:
statement(s)
Example:
age= int(input("please enter your age: "))
if age >= 18:
weight=int(input("what is your weight: "))
if weight==150:
print("over weight")
elif weight== 120:
print("little less than over weight")
elif weight==100:
print("noraml weight")
elif weight==50:
print("less weight")
else:
print(“sorry please enter age more than or equal to 18")
O/p:
????
For loop in python:
 A for loop is used for repeating over a
sequence in any of the a list, a tuple, a
dictionary, a set, or a string.
 This is less like the for keyword in
other programming languages, and
works more like an iterator method as
found in other object-orientated
programming languages.
 With the for loop we can execute a
set of statements, once for each item
in a list, tuple, set etc.
Example:1
X=range(6)
For a in x:
Print(a)
O/p:
0
1
2
3
4
5
Example:2
x=["apple","boy","cat","do
g"]
for a in x:
print(a)
O/p:
Apple
Boy
Cat
dog
Example: 1
a="banana"
for x in a:
print(x)
O/p:
???
The break Statement
 With the break statement we can stop the loop before it has looped
through all the items
Example:2
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
O/p:
Apple
Banana
 Exit the loop when x is "banana", but
this time the break comes before the
print
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
O/p:
Apple
Banana
Example:
x=["apple","boy","cat","dog"]
for a in x:
print(a)
if a=="cat":
break
 O/p:
apple
boy
cat
Continue statement:
 With the continue statement we can stop
the current iteration of the loop, and
continue with the next
Example:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
O/p:
Apple
cherry
While in python:
 A while loop statement in Python
programming language repeatedly
executes a target statement as long
as a given condition is true.
Syntax:
while expression:
statement(s)
 Example:
num=0
while num<=9:
print("number is:
",+num)
num=num+1
print("end of loop")
O/p:
('number is: ', 0)
end of loop
('number is: ', 1)
end of loop
('number is: ', 2)
end of loop
('number is: ', 3)
end of loop
('number is: ', 4)
end of loop
('number is: ', 5)
end of loop
('number is: ', 6)
end of loop
('number is: ', 7)
end of loop
('number is: ', 8)
end of loop
('number is: ', 9)
end of loop
What is OOPS in python:
 Object Oriented programming is a programming
style that is associated with the concept of Class,
Objects and various other concepts revolving
around these two, like Inheritance,
Polymorphism, Abstraction, Encapsulation etc.
 OOP is designed in such a way that one should
focus on an object while programming and not
the procedure. An object can be anything that we
see around us. It can be a human (that has some
properties like - name, address, DOB and so on),
a chair (portrayed by size, material, cost etc), a
school (depicted by place, student strength,
results) etc.
 Object oriented programming brings
programming close to real life, as we are always
dealing with an object, performing operations on
it, using it's methods and variables etc.
Concepts of OOP in python:
 Class
 Object
 Inheritance
 Encapsulation
 Abstraction
 Polymorphism
Class:
A Class is a logical grouping of data and
functions. It gives the freedom to
create data structures that contains
arbitrary content and hence easily
accessible.
Object:
A unique instance of a data structure
that's defined by its class. An object
comprises both data members (class
variables and instance variables) and
methods.
Inheritance:
The transfer of the characteristics of a
class to other classes that are derived
from it.
Polymorphism:
The word polymorphism means having
many forms. In programming,
polymorphism means same function
name (but different signatures) being
uses for different types.
 Encapsulation:
Encapsulation is defined as wrapping up
of data and information under a single
unit. In Object Oriented Programming,
Encapsulation is defined as binding
together the data and the functions that
manipulates them.
Abstraction:
Abstraction means displaying only
essential information and hiding the
details. Data abstraction refers to
providing only essential information
about the data to the outside world,
hiding the background details or
implementation.
Class:
Syntax of a class: 1
Class class_name():
statements
Printing the class
Example:
Class Myclass():
a=10
Print(Myclass)
O/p:
10
Syntax of a class:2
class MyClass:
variable1 = something
variable2 = something
def function1(self, parameter1, ...):
self.variable1 = something else
self.variable3 = something function
statements...
def function2(self, parameter1, ...):
self.variable2 = something else
function2 statements...
Note: It's a mandatory parameter for every function
defined in a class. self represents the current active
object of the class, using which the function of the class
is called.
 Inheritance in Python
If we have a class Parent and another class Child and we want the class Child to
inherit the class Parent, then:
Example:
# Parent class
class Parent:
# class variable
a = 10;
b = 100;
# some class methods
def doThis():
Statements
def doThat():
statements
# Child class inheriting Parent class
class Child(Parent):
# child class variable
x = 1000;
y = -1;
# some child class method
def doWhat():
statements
def doNotDoThat():
statements
 Creating an Object:
class MyClass:
x = 5
p1 = MyClass()
print(p1.x)
Here pl is an object
 Identity: Identity refers to some piece of
information that can be used to identify
the object of a class. It can be the name
of the student, the company name of the
car, etc.
 Properties: The attributes of that object
are called properties. Like age, gender,
DOB for a student; or type of engine,
number of gears for a car.
 Behavior: Behavior of any object is
equivalent to the functions that it can
perform. In OOP it is possible to assign
some functions to objects of a class.
Taking the example forward, like a
student can read/write, the car can
 Sample code for creating class & Object:
class Apollo:
# define a variable
destination = "moon"
# defining the member functions
def fly(self):
print ("Spaceship flying...“)
def get_destination(self):
print ("Destination is: " + self.destination)
# 1st object
objFirst = Apollo()
# 2nd object
objSecond = Apollo()
# lets change the destination for objFirst to mars
objFirst.destination = "mars"
# objFirst calling fly function
objFirst.fly()
# objFirst calling get_destination function
objFirst.get_destination()
# objSecond calling fly function
objSecond.fly()
# objSecond calling get_destination function
objSecond.get_destination()
Polymorphism
 Polymorphism, or Poly + Morph,
means "many forms. Precisely,
Polymorphism is the property of any
function or operator that can behave
differently depending upon the input
that they are fed with.
 Polymorphism can be achieved in tow
different forms, they are:
:Over riding & Over loading
 Overloading:
For example, consider a function add(), which
adds all its parameters and returns the result.
In python we will define it as,
Example:
def add(a, b):
print("addition of two numbers is: ", a+b)
add(3,4)
def add(a, b, c):
print("addition of three numbers is: ",
a+b+c)
add(3,4,5)
# to add 4 numbers
def add(a, b, c, d):
print("addition of four numbers is: ",
a+b+c+d)
add(3,4,5,6)
 Method Overriding:
 Python method overriding occurs
simply defining in the child class a
method with the same name of a
method in the parent class. When you
define a method in the object you
make the latter able to satisfy that
method call, so the implementations of
its ancestors do not come in play.
class Parent(object):
def __init__(self):
self.value = 5
def get_value(self):
return self.value
class Child(Parent):
def get_value(self):
return self.value + 1
Polymorphism:
Sample code:
def add(x, y, z = 0):
return x + y+z
print(add(2, 3))
print(add(2, 3, 4))
O/p:
5
9
 Example of polymorphism:
class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi the primary language of India.")
def type(self):
print("India is a developing country.")
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
Object_ind = India()
Object_usa = USA()
for country in (object_ind, object_usa):
country.capital()
country.language()
country.type()
Example of Inheritance
class Person(object):
def __init__(self, name):
self.name = name
def getName(self):
return self.name
def isEmployee(self):
return False
class Employee(Person):
def isEmployee(self):
return True
emp = Person("Geek1") print(emp.getName(),
emp.isEmployee())
emp = Employee("Geek2") # An Object of Employee
print(emp.getName(), emp.isEmployee())
EXAMPLES
Some Examples on Data visualization
using Pandas, Numpy &
matplotlib.pyplot
 NumPy: (Numerical Python)
It is a core library for scientific
computing
in python, It provides a higher
performance multidimensional array
object & tools for working with these
arrrays.
Pandas:
Pandas takes data from .csv, .tsv or
SQL database files & creates a python
object with rows and columns called
data frames that looks very similar to
table in a statistical Software
matplotlib.pyplot:
Matplotlib.pyplot is a library used to
create 2D graphs & plots by using
python scripts. It has a module named
pyplot which makes things easy for
plotting by providing feature to control
line styles font properties formatting
axes etc.,
import numpy
x=numpy.array([5,4,3,4])
y=numpy.array([1,2,3,4])
z=x-y
print(z)
O/p:
4,2,0,0
import pandas
import numpy
import matplotlib.pyplot as dee
myarray=numpy.array([[1,2,3,4,5],[6,7,8,9,
0]])
rowname=["a","b"]
columnname=["m","n","o","p","q"]
x=pandas.DataFrame(myarray,
index=rowname, columns=columnname)
print(x)
O/p:
m n o p q
a 1 2 3 4 5
b 6 7 8 9 0
Python for plotting graphs:
 Example:
import pandas
import numpy
import matplotlib.pyplot as dee
x=numpy.array([1,2,3,4,5])
y=numpy.array([3,4,5,6,7])
dee.scatter(x,y)
dee.xlabel(“x-axis”)
dee.ylabel(“y-axis”)
dee.show()
O/p:
Plotting graphs:
import pandas
import matplotlib.pyplot as dee
import numpy
url="https://archive.ics.uci.edu/ml/machi
ne-learning-databases/iris/iris.data"
name=['sl','sw','pl','pw','class']
data=pandas.read_csv(url,
names=name)
data.plot(kind='box', subplots=True,
layout=(1,4))
dee.show()
Reading a CSV file:
url="https://archive.ics.uci.edu/ml/machine
-learning-databases/iris/iris.data"
name=['sl','sw','pl','pw','class']
data=pandas.read_csv(url, names=name)
print(data
import pandas
from sklearn import model_selection
from sklearn.linear_model import LinearRegression
url =
"https://raw.githubusercontent.com/jbrownlee/Datasets/master/housing.data"
names = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX',
'PTRATIO', 'B', 'LSTAT', 'MEDV']
dataframe = pandas.read_csv(url, delim_whitespace=True, names=names)
array = dataframe.values
X = array[:,0:13]
Y = array[:,13]
seed = 7
kfold = model_selection.KFold(n_splits=10, random_state=seed)
model = LinearRegression()
scoring = 'neg_mean_squared_error'
results = model_selection.cross_val_score(model, X, Y, cv=kfold,
scoring=scoring)
print(results.mean())

More Related Content

What's hot

Python second ppt
Python second pptPython second ppt
Python second ppt
RaginiJain21
 
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Edureka!
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
Tahani Al-Manie
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
Edureka!
 
Python programming
Python programmingPython programming
Python programming
Megha V
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Agung Wahyudi
 
Python programming
Python  programmingPython  programming
Python programming
Ashwin Kumar Ramasamy
 
Variables in python
Variables in pythonVariables in python
Variables in python
Jaya Kumari
 
Basics of python
Basics of pythonBasics of python
Basics of python
Jatin Kochhar
 
Python
PythonPython
Python
Aashish Jain
 
Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming
KrishnaMildain
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Yi-Fan Chu
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python
Jaganadh Gopinadhan
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
primeteacher32
 
Python introduction
Python introductionPython introduction
Python introduction
Jignesh Kariya
 
Chapter 06 constructors and destructors
Chapter 06 constructors and destructorsChapter 06 constructors and destructors
Chapter 06 constructors and destructors
Praveen M Jigajinni
 
Python programming introduction
Python programming introductionPython programming introduction
Python programming introduction
Siddique Ibrahim
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaPython Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Edureka!
 
Python - An Introduction
Python - An IntroductionPython - An Introduction
Python - An Introduction
Swarit Wadhe
 

What's hot (20)

Python second ppt
Python second pptPython second ppt
Python second ppt
 
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
 
Python programming
Python programmingPython programming
Python programming
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python programming
Python  programmingPython  programming
Python programming
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
 
Basics of python
Basics of pythonBasics of python
Basics of python
 
Python
PythonPython
Python
 
Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Python introduction
Python introductionPython introduction
Python introduction
 
Chapter 06 constructors and destructors
Chapter 06 constructors and destructorsChapter 06 constructors and destructors
Chapter 06 constructors and destructors
 
Python programming introduction
Python programming introductionPython programming introduction
Python programming introduction
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaPython Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
 
Python - An Introduction
Python - An IntroductionPython - An Introduction
Python - An Introduction
 

Similar to Python introduction towards data science

Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
natnaelmamuye
 
python ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institutepython ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institute
Scode Network Institute
 
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfpython-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
KosmikTech1
 
Python Programming-1.pptx of python by computer
Python Programming-1.pptx of python by computerPython Programming-1.pptx of python by computer
Python Programming-1.pptx of python by computer
sharanyarashmir5
 
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
manikamr074
 
unit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptxunit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptx
usvirat1805
 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualize
IruolagbePius
 
Introduction of Python
Introduction of PythonIntroduction of Python
Introduction of Python
ZENUS INFOTECH INDIA PVT. LTD.
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
Mohd Sajjad
 
Python unit1
Python unit1Python unit1
PYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdfPYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdf
Ramakrishna Reddy Bijjam
 
Python Session - 2
Python Session - 2Python Session - 2
Python Session - 2
AnirudhaGaikwad4
 
Welcome to python workshop
Welcome to python workshopWelcome to python workshop
Welcome to python workshop
Mukul Kirti Verma
 
python introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptxpython introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptx
ChandraPrakash715640
 
Python Introduction
Python IntroductionPython Introduction
Python Introduction
vikram mahendra
 
Python by Rj
Python by RjPython by Rj
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
samiwaris2
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
Akanksha Bali
 
python presentation
python presentationpython presentation
python presentation
VaibhavMawal
 
Python PPT.pptx
Python PPT.pptxPython PPT.pptx
Python PPT.pptx
JosephMuez2
 

Similar to Python introduction towards data science (20)

Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
 
python ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institutepython ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institute
 
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfpython-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
 
Python Programming-1.pptx of python by computer
Python Programming-1.pptx of python by computerPython Programming-1.pptx of python by computer
Python Programming-1.pptx of python by computer
 
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
 
unit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptxunit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptx
 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualize
 
Introduction of Python
Introduction of PythonIntroduction of Python
Introduction of Python
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
 
Python unit1
Python unit1Python unit1
Python unit1
 
PYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdfPYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdf
 
Python Session - 2
Python Session - 2Python Session - 2
Python Session - 2
 
Welcome to python workshop
Welcome to python workshopWelcome to python workshop
Welcome to python workshop
 
python introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptxpython introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptx
 
Python Introduction
Python IntroductionPython Introduction
Python Introduction
 
Python by Rj
Python by RjPython by Rj
Python by Rj
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
 
python presentation
python presentationpython presentation
python presentation
 
Python PPT.pptx
Python PPT.pptxPython PPT.pptx
Python PPT.pptx
 

Recently uploaded

一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单
enxupq
 
一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理
一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理
一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理
mbawufebxi
 
Opendatabay - Open Data Marketplace.pptx
Opendatabay - Open Data Marketplace.pptxOpendatabay - Open Data Marketplace.pptx
Opendatabay - Open Data Marketplace.pptx
Opendatabay
 
1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx
1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx
1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx
Tiktokethiodaily
 
Empowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptxEmpowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptx
benishzehra469
 
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
ahzuo
 
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
slg6lamcq
 
一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单
ewymefz
 
Adjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTESAdjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTES
Subhajit Sahu
 
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdfCriminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP
 
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
pchutichetpong
 
Sample_Global Non-invasive Prenatal Testing (NIPT) Market, 2019-2030.pdf
Sample_Global Non-invasive Prenatal Testing (NIPT) Market, 2019-2030.pdfSample_Global Non-invasive Prenatal Testing (NIPT) Market, 2019-2030.pdf
Sample_Global Non-invasive Prenatal Testing (NIPT) Market, 2019-2030.pdf
Linda486226
 
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
ahzuo
 
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
ewymefz
 
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Subhajit Sahu
 
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
u86oixdj
 
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
slg6lamcq
 
Machine learning and optimization techniques for electrical drives.pptx
Machine learning and optimization techniques for electrical drives.pptxMachine learning and optimization techniques for electrical drives.pptx
Machine learning and optimization techniques for electrical drives.pptx
balafet
 
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
ewymefz
 
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
yhkoc
 

Recently uploaded (20)

一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单
 
一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理
一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理
一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理
 
Opendatabay - Open Data Marketplace.pptx
Opendatabay - Open Data Marketplace.pptxOpendatabay - Open Data Marketplace.pptx
Opendatabay - Open Data Marketplace.pptx
 
1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx
1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx
1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx
 
Empowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptxEmpowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptx
 
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
 
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
 
一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单
 
Adjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTESAdjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTES
 
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdfCriminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdf
 
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
 
Sample_Global Non-invasive Prenatal Testing (NIPT) Market, 2019-2030.pdf
Sample_Global Non-invasive Prenatal Testing (NIPT) Market, 2019-2030.pdfSample_Global Non-invasive Prenatal Testing (NIPT) Market, 2019-2030.pdf
Sample_Global Non-invasive Prenatal Testing (NIPT) Market, 2019-2030.pdf
 
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
 
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
 
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
 
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
 
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
 
Machine learning and optimization techniques for electrical drives.pptx
Machine learning and optimization techniques for electrical drives.pptxMachine learning and optimization techniques for electrical drives.pptx
Machine learning and optimization techniques for electrical drives.pptx
 
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
 
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
 

Python introduction towards data science

  • 2. Agenda  What is a programming language ? & why we use it ?  Different Programming languages.  What is Python…?  History of Python  Scope of Python  Applications of Python?  Installing Python IDE  What can I do with python  A Sample Code.
  • 3. What is a programming language ? & why we use it ?
  • 4. Different Programming languages.  High Level Language - High level languages are written in a form that is close to our human language, enabling to programmer to just focus on the problem being solved. - No particular knowledge of the hardware is needed as high level languages create programs that are portable and not tied to a particular computer or micro chip. These programmer friendly languages are called ‘high level’ as they are far removed from the machine code instructions understood by the computer. - It considers only Business logics but memory issues are taken care by garbage collector
  • 5.  Low level language - Low-level languages are written to meet the needs of particular computer architecture and hardware requirements. Machine code is low level because it runs directly on the processor. Low-level languages are appropriate for writing operating systems or firmware for micro-controllers. -It considers only Memory issues Note: Business logic is the programming that manages communication between an end user interface and a database. The main components of business logic are business rules and workflows.
  • 6. Examples  High Level Language ◦ Java, Python, Pascal, COBOL, FORTRAN, BASIC  Middle Level Language ◦ C,  Low Level Language ◦ Assembly language (Assembler, Forth)
  • 7. What is Python…?  Python is a general purpose programming language that is often applied in scripting roles.  So, Python is programming language as well as scripting language.  Python is also called as Interpreted language
  • 8. Differences between program and scripting language  Basically, all scripting languages are programming languages. The theoretical difference between the scripting language and programming language is that in case of programming language we need to save the program then compile and then run it, but in script language like java script we have to save the code and then direct run it we need not to compile the script language program.
  • 10.  Developed in 1991  Originally Started in 1989  Developed by Guido Van Rosbum in Netherlands  Name python came from a comic show “Monty’s python flying circus comic show” telecasted in BBC-Netherlands from 1967 to 1974
  • 11. Versions of Python  Version 1.0 to 1.x  25 October 1996- 5 September 2000.  Version 2.0 to 2.x  16 October 2000- 02 March 2019  Version 3.0 to 2.x  3 December 2008- 25 March 2019.
  • 12. Applications of Python  Web Applications  Desktop GUI (graphical user interface) Applications  Software Development  Scientific and Numeric  Business Applications  Embedded System development  IoT Development  Windows Azur  Devops  Network Applications  Game Development, Etc.,
  • 13.  Advantages Python ◦ Less code ◦ Simple Syntax ◦ Faster Execution  Features of Python ◦ Easy to Read ◦ Easy to Maintain ◦ Easy to learn
  • 14. Installation of Python  Python is pre-installed on most Unix systems, including Linux and MAC OS X  But for in Windows Operating Systems , user can download from the https://www.python.org/downloads/  From the above link download latest version of python IDE and install, recent version is 3.7.3 but most of them uses version 2.7.7 only
  • 15. Who uses python  Google makes extensive use of Python in its web search system, and employs Python’s creator.  Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware testing.  ESRI (Environmental Systems Research Institute) uses Python as an end-user customization tool for its popular GIS mapping products.  The YouTube video sharing service is largely written in Python.
  • 16. What we can do with Python  Graphical User Interface Programming Internet Scripting  Gaming, Images, XML , Robot and more  System programming  Component Integration Database Programming
  • 17. Python Code Execution PVM is which help to execute the python program. PVM: Python Virtual Machine
  • 18.  More to Discuss: -Python is a case sensitive language -Difference between Command prompt & IDLE IDLE(Interactive development environment) -Example of Python Program
  • 19. What are operators in python?  Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.
  • 20. Operators in Python  Arithmetic Operators ◦ +, -, *, /, %, //  Comparison/Relational Operators ◦ <, >, <=, >=, ==, !=  Logical Operators ◦ AND, OR, NOT  Bit Wise Operators ◦ &, | , ~, x, ^  Assignment Operators ◦ ==, *=, +=, -=, /=
  • 21.  Difference between %, // & / 5 / 2 will return 2.5 and 5 // 2 will return 2 . The former is floating point division, and the latter is floor division, sometimes also called integer division. % : Gives the reminder of the two numbers. Example: x= 4 y= 2 print(x%y) print(x//y) print(x/y)  Output: ◦ 0 ◦ 2 ◦ 2.0
  • 22. Comparison/Relational Operators  Comparison or Relational operators are used to compare two things or to find the relation between two entities.  == Equals to  != Not equals  Example: x=4 y=3 print(x==y) print(x!=y) Output: False True
  • 23. Logical gates  AND gate  OR gate  Not gate  ExOR gate
  • 24. Logical Operators  And: True if both the operands are true x and y  Or: True if either of the operands is true x or y  Not: True if operand is false (complements the operand)
  • 25. Example: x=1 y=0 print(x and y) print(x or y) print(not x) Output: 0 1 False
  • 26. Bit Wise Operators  & : And  |: OR  ~ : Complement/NOT  ^ : XOR  >> : Right Shift  << : Left Shift  Note: Bit wise operator first converts given number into a binary number and performs the operations
  • 27. Example of Bit Wise operator a = 10 b = 4 Print bitwise AND operation print(a & b) Print bitwise OR operation print(a | b) Print bitwise NOT operation print(~a) Print bitwise XOR operation print(a ^ b) Print bitwise right shift operation print(a >> 2) print bitwise left shift operation print(a << 2) Output 0 14 -11 14 2 40
  • 28. Difference between Logical & Bit wise operators Example : x=1 y=0 a=True b=False print(x and y) print(x or y) print(not x) print(not y) print(not a) print(not b) print(x&y) print(x|y) print(a & b) print(a | b) print(~x) Output: 0 1 0 1 False True 0 1 False True
  • 29. Assignment Operators  == or =  +=  -=  *=  /=
  • 30. Number conversions S.No Type Python Number Representation in output 1 Binary Bin 2 0b 2 Octal Oct 8 0o 3 Hexadecimal hex 16 0x
  • 31. Decimal Conversions  To convert Octal, Hexadecimal, Binary to decimal we can use below statement.  Binary to Decimal ◦ print(int(“Binary number”,2))  Octal to Decimal ◦ print(int(“Octal”,8))  Hexadecimal to Decimal ◦ print(int(“Hexadecimal”,16))
  • 32. Variables  variable is a ◦ name. ◦ refers to a value. ◦ holds the data ◦ name of the memory location. Note: To find the memory location of a variable we can use below statement >>>X=10 >>>print(id(x))
  • 33. Properties of variable  Every variable has a, ◦ Type ◦ Value ◦ Scope ◦ Location ◦ Life time  Creating variable ◦ In python, to create a variable we need to specify, The name of the variable ◦ Assign a value to name of the variable.
  • 34.  Variables names, Should not give as keywords names, otherwise we will get error.  We can assign multiple variables to multiple values in single line.  Example: >>> a, b, c = 1, 2, 3 >>> print(a, b, c) Output: 1 2 3
  • 35. Data types  A data type represents the type of the data stored into a variable or memory Note: We use type() in-built or predefined function in python.
  • 36. Different types of data types  There are two type of data types. ◦ Built-in data types:  The data types which are already available in python are called built-in data types. ◦ User defined data types:  Data types which are created by programmer
  • 37. Built-in data types 1. Numeric types ◦ int ◦ float ◦ complex 2. bool (boolean type) ◦ True ◦ False 3. None 4. Str (string) 5. bytes 6. bytearray 7. list 8. set 9. tuple 10. dict 11. range
  • 38. More to Discuss  Exponential values in integers. ◦ 2E2 or 2e2 ◦ Comparing complex numbers ◦ Case sensitivity in complex values/numbers ◦ Adding Boolean values ◦ Printing none values ◦ How to create a string
  • 39. Bytes  bytes data type ◦ bytes data type represents group of numbers just like an array ◦ bytes data type can store the values which are from 0 to 256. ◦ bytes data type cannot store negative numbers. To create a byte data type ◦ First, we need to create list. ◦ The created list we need to pass to bytes() function as a parameter  Note: bytes data type is immutable means we cannot modify or change the bytes object.
  • 40. How to create a bytes  To create a bytes first we need to create a list with [ ] a variable name  Then assign the created list to another variable by stating it as byte as below  Example: >>>a= [1,2,3,4,5,] >>>b= bytes(a) >>>print(b) >>>print(type(a))  Output: [1,2,3,4,5,] <class 'bytes'>
  • 41. bytearray data type  bytearray is same as bytes data type, but bytearray is mutable means we can modify the content of bytearray data type.  The created list we need to pass as bytearray() parameter
  • 42. How to create a bytearray()  First, we need to create list.  The created list we need to pass as bytearray() parameter  It is as same as creating a bytes() >>>x = [10, 20, 30, 40, 15] >>>y = bytearray(x) >>>print(type(y)) >>>print(y) Output: <class bytearray> [10, 20, 30, 40, 15]
  • 43. Modifying bytearray()  We can modify the bytearray as it is a mutable list as below >>>x=[10,20,30,40,50] >>>y=bytearray(x) >>>print(y) >>>y[3]=99 >>>print(y) Output: [10,20,30,40,50] <class bytearray>
  • 44. List  We can create list data structure by using square brackets [ ]  list can store different data types  list is mutable.  Examples of list: ◦ [1,2,3,4,5] ◦ [1,2,’3x’,’x’,’y’,-2] ◦ [1,2,'3x','x','y',-2,{1,2,3,4}]
  • 45. Python has a set of built-in methods.  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
  • 46. append() >>>a=['apple','boy','cat'] >>>a. append('dog') >>>print(a) O/p: apple, boy cat,dog clear() >>>a=['apple','boy','cat'] >>>a.clear() >>>print(a) O/p: [ ]
  • 47. Copy() >>>a=['apple','boy','cat'] >>>b=a. copy() >>>print(b) O/p: apple, boy, cat Count(): >>>a=[1,2,3,3,3,3,3,3,5,6] >>>b=a.count(3) >>>print(b) O/p: 6
  • 49. sort() >>>cars = ['Ford', 'BMW', 'Volvo'] >>>cars.sort() >>>print(cars) O/p: [‘BMW’, ‘Ford’,’Volvo’] reverse() >>>fruits = ['apple', 'banana', 'cherry'] >>>fruits.reverse() >>>print(fruits) O/p: [‘cherry’, ‘banana’, ’apple’]
  • 50. remove() >>>fruits = ['apple', 'banana', 'cherry'] >>>fruits.remove("banana") >>>print(fruits) O/p: [‘apple’,’cherry’] Pop(): >>>fruits = ['apple', 'banana', 'cherry'] >>>fruits.pop(1) >>>print(fruits) O/p: [‘apple’, ‘cherry’]
  • 51. Insert(): fruits = ['apple', 'banana', 'cherry'] fruits.insert(1, "orange") print(fruits) O/p: [‘apple’, ’orange’,’banana’,’cherry’]
  • 52. tuple  We can create tuple data structure by using parenthesis ()  tuple can store different data types.  tuple is immutable.  Examples of tuple:  (1,2,3,4)
  • 53. Examples of tuple Creating a tuple >>>a=(1,2,3,4,5) >>>print(a) >>>print(type(a)) O/p: (1,2,3,4) <class ‘tuple’>
  • 54. Access Tuple Items >>>a=("apple","boy","cat") >>>print(a) >>>print(a[1]) O/p: Boy Checking the presence of tuple >>>a=("apple","boy","cat") >>>if "apple" in a: >>>print("yes apple is there in the given tuple") O/p: Yes apple is there in the given tuple
  • 55. To print length of tuple >>>a=(“apple”,”boy”,”dog”) >>>print(len(a)) O/p: 3 Tuple as a constructor: >>>a=tuple(("apple","boy","cat")) >>>print(a) >>>print(type(a)) O/p: (“apple”,”boy”,”cat”) <class “tuple”>
  • 56.  Methods in tuples: Count() Index() More to Discuss 1. Can we add elements into a tuple 2. Can we remove elements from the tuple 3. Can we delete entire tuple
  • 57. range()  We can create a range of values by using range() function  The range datatype represents a sequence of numbers.  range data type is immutable, means we cannot modify once it created.  range data type values can be print by using for loop.
  • 58. Example of range() >>>a=range(5) >>>print(a) >>>for x in a: >>>print(x) Output: range(0, 5) 0 1 2 3 4
  • 59. Note: We can create a list of values with range data type Program Creating list of values >>>a=list(range(1, 10)) >>>print(a) Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
  • 60.  By using index, we can access elements present in the range data type >>>a=range(1, 10) >>>print(a[0]) >>>print(a[1]) Output: 1 2
  • 61.  A set is a collection which is unordered and un-indexed. In Python sets are written with curly brackets { }.  You cannot access items in a set by referring to an index, since sets are unordered the items has no index.  But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the “in” keyword.  Once a set is created, you cannot change its items, but you can add new Set
  • 62. Add Items  To add one item to a set use the add() method.  To add more than one item to a set use the update() method.  Example: >>>a={"apple","boy","cat"} >>>print(type(a)) >>>a.add("dog") >>>print(a) >>>a.update(["nanna","flask"]) >>>print(a) O/p: <class,set”> {‘apple’,’boy’,’cat’,’dog’} {‘apple’,’boy’,’cat’,’dog’, ‘nanna’, ‘flask’}
  • 63.  Printing a set: >>>a={“apple”,”boy”,”cat”} >>>print(a) O/p: Cat Apple Boy To print the output in a sequence: >>>a={“apple”,”boy”,”cat”} >>>for x in a >>>print(a) O/p: apple boy cat
  • 64.  To find the presence of an element: >>>a={“apple”,”boy”,”cat”} >>>print(“boy” in a) O/p: True
  • 65.  We can find the length of “set” by using “len()”  We can perform remove() & discard(), both are same >>>a={“apple”,”boy”,”cat”} >>>a.remove(“apple”) >>>a.discard(“cat”) >>>print(a) O/p: boy
  • 66.  pop() We can perform pop() also but as the set() is unordered so it will delete the last element of the set >>>a={"apple","boy","cat","dog"} >>>a.pop() >>>print(a) O/p: Boy Cat dog
  • 67.  We can also perform clear(), del() on the set as below >>>a={"apple","boy","cat","dog"} >>>a.clear() >>>print(a) O/p: { } Del(): >>>a={"apple","boy","cat","dog"} >>>del a >>>print(a) O/p: error
  • 68. Methods in set{ }  add(): Adds an element to the set  clear(): Removes all the elements from the set  copy(): Returns a copy of the set  difference(): Returns a set containing the difference between two or more sets  difference_update(): Removes the items in this set that are also included in another, specified set  discard(): Remove the specified item  intersection(): Returns a set, that is the intersection of two other sets  intersection_update():Removes the items in this set that are not present in other, specified set(s)  isdisjoint(): Returns whether two sets have a intersection or not  issubset(): Returns whether another set contains this set or not  issuperset(): Returns whether this set contains another set or not  pop(): Removes an element from the set  remove(): Removes the specified element  symmetric_difference(): Returns a set with the symmetric differences of two sets  symmetric_difference_update(): inserts the symmetric differences from this set and another  union(): Return a set containing the union of sets  update(): Update the set with the union of this set and othersTest
  • 72. issubset() >>> a={‘a’,’b’,’c’,’d’,’e’,’f’} >>> b={‘a’,’b’,’c’} >>> d=b.issubset(a) print(d) O/p: True Issuperset(): >>>x = {"f", "e", "d", "c", "b", "a"} >>> y = {"a", "b", "c"} >>> z = x.issuperset(y) >>> print(z) O/p: True
  • 73. symmetric_difference(): >>>x = {"apple", "banana", "cherry"} >>>y = {"google", "microsoft", "apple"} >>>z = x.symmetric_difference(y) >>>print(z) O/p: {"google", "microsoft", “banana”,”cherry”}
  • 74. Can also use the pop(), method to remove an item, but this method will remove the last item. Remember that sets are unordered, so you will not know what item that gets removed.  The return value of the pop() method is the removed item. Remove the last item by using the pop() method: >>>a = {"apple", "banana", "cherry"} >>>x = a.pop() >>>print(x) >>>print(a) O/p: {“apple”,”boy”}
  • 75. symmetric_difference_update(): >>>x = {"apple", "banana", "cherry"} >>>y = {"google", "microsoft", "apple"} >>>x.symmetric_difference_update(y) >>>print(x) O/p: {'google', 'cherry', 'microsoft', 'banana'}
  • 76. union(): >>>x = {"apple", "banana", "cherry"} >>>y = {"google", "microsoft", "apple"} >>>z = x.union(y) >>>print(z) O/p: {'banana', 'apple', 'google', 'microsoft', 'cherry'} update(): x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} x.update(y) print(x) O/p: {'microsoft', 'cherry', 'apple', 'google', 'banana'}
  • 77. Dictionary  A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets,{ } and they have keys and values.  Example: >>>x={1:10} >>>print(x) >>>print(type(x)) O/p: {1,10} <class ‘dict’>
  • 78. Can access the items of a dictionary by referring to its key name, inside square brackets: A={“animal”:”cat”, ”fruit”: “apple”, ”flower”:”Rose”} print(type(a)) print(a[“flower”]) O/p: <class “dict”> Rose Change Values: A={“animal”:”cat”, ”fruit”: “apple”, ”flower”:”Rose”} print(type(a)) print(a[“flower”]) A[“fruit”]=“Banana” O/p: <class “dict”> {“animal”:”cat”, ”fruit”: “Banana”, ”flower”:”Rose”}
  • 79. Print all key names in the dictionary, one by one: >>>a={“animal”:”cat”, ”fruit”: “apple”, ”flower”:”Rose”} >>>print(type(a)) >>>For x in a: >>>print(x) O/p: <class “dict”> animal Fruit flower Printing all values in the dictionary, one by one: >>>a={“animal”:”cat”, ”fruit”: “apple”, ”flower”:”Rose”} >>>print(type(a)) >>>For x in a: >>>print(a[x]) O/p: Cat Apple Rose
  • 80. We can also use the values() function to return values of a dictionary: >>>a={"fruit": "apple", "animal": "cat","flower": "Rose"} >>>print(a) >>>for x in a.values(): >>> print(x) O/p: Apple Cat Rose To print the complete “dict” we can also use below method: >>>a={"fruit": "apple", "animal": "cat","flower": "Rose"} >>>print(a) >>>for x,y in a: >>> print(x,y) O/p: {"fruit": "apple", "animal": "cat", "flower": "Rose"} {"fruit": "apple", "animal": "cat", "flower": "Rose"}
  • 81. We can also find the length of the dictionary: >>>a={"fruit": "apple", "animal": "cat","flower": "Rose"} >>>print(a) Print(len(a)) O/p: 3 To find the availability of elements in given dict: >>>a={"fruit": "apple", "animal": "cat","flower": "Rose"} >>>if "animal" in a: >>> print("Yes it is there") O/p: Yes it is there
  • 82. Adding elements into given dict: >>>a={"fruit": "apple", "animal": "cat","flower": "Rose"} >>>print(a) >>>a["color"]="Red" >>>print(a) O/p: {“Color”: “Red, ”"fruit": "apple", "animal": "cat", "flower": "Rose“} Deleting/Removing elements from dict: >>>a={"fruit": "apple", "animal": "cat","flower": "Rose"} >>>print(a) >>>a["color"]="Red" >>>print(a) >>>a.pop("animal") >>>print(a) O/p: {“Color”: “Red, ”"fruit": "apple", "animal": "cat", "flower": "Rose“} {“Color”: “Red, ”"fruit": "apple", "flower": "Rose“}
  • 83. Deleting an element from “dict” using del(): >>>a={"fruit": "apple", "animal": "cat","flower": "Rose"} >>>print(a) >>>del a[“flower”] >>>print(a) O/p: {"fruit": "apple", "animal": "cat"} To delete entire dict using del(): >>>a={"fruit": "apple", "animal": "cat","flower": "Rose"} >>>print(a) del a print(a) O/p: Type Error
  • 84. To copy a dict: a={"fruit": "apple", "animal": "cat","flower": "Rose"} print(a) d=a.copy() print(d) O/p: a={"fruit": "apple", "animal": "cat","flower": "Rose"} a={"fruit": "apple", "animal": "cat","flower": "Rose"} To clear a dict: a={"fruit": "apple", "animal": "cat","flower": "Rose"} print(a) a.clear() print(a) O/p: { }
  • 85. Python has a set of built-in methods that you can use on dictionaries. clear(): Removes all the elements from the dictionary  copy(): Returns a copy of the dictionary  fromkeys(): Returns a dictionary with the specified keys and values  get(): Returns the value of the specified key  items(): Returns a list containing the 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
  • 87. items(): >>>x={'flower':"Rose",'color':"Red",'animal':"rat" } >>>y=x.items() >>>print(y) O/p: [('color', 'Red'), ('flower', 'Rose'), ('animal', 'rat')] keys(): car = { "brand": "Ford", "model": "Mustang", "year": 1964} x = car.keys() print(x) O/p: dict_keys(['brand', 'model', 'year'])
  • 88. pop(): >>>x={'flower':"Rose",'color':"Red",'animal':"rat"} >>>print(x) >>>x.pop("animal") >>>print(x) O/p: {'flower':"Rose",'color':"Red"} popitem(): Remove the last item from the dictionary: >>>x={'flower':"Rose",'color':"Red",'animal':"rat"} >>>print(x) >>>x.popitem( ) >>>print(x) O/p: {'flower': 'Rose', 'animal': 'rat'}
  • 89. >>>car = { "brand": "Ford","model": "Mustang","year": 1964} >>>x = car.setdefault("color", "White") >>>print(x) O/p: White Update(): >>>a={"animal":"cow","flower":"lilly","food":"idly "} >>>a.update({"name":"archi"}) >>>print(a) O/p: {"animal":"cow","flower":"lilly","food":"idly“, "name":"archi"}
  • 90. Membership Operators  Membership operators are useful to check whether the given object is available in collection (sequence) or not. (It may be string, list, set, tuple and dict)  There are two membership operators, ◦ In ◦ not in Example: x=[1,2,3,4,5] print(10 in x) print(1 in x) print(1 not in x) print(100 not in x)
  • 91. Keywords in python  The words which are reserved to do specific functionality is called reserved keywords words.  Totally we have 33 keywords in python  These are also case sensitive  All are small letters except  True  False  None  Note: We cannot use a keyword as variable name, function name or any other identifier.
  • 92. List of Keywords  False  class  finally  is  return  None  continue  for  lambda  try  True  def  from  nonlocal  while  and  del  global  not  with  as  elif  for  yield  assert  else  import  pass  break  except  in  raise
  • 93. Keyword: None  None is a special constant in Python that represents the absence of a value or a null value.  It is an object of its own data type, the None Type. We cannot create multiple None objects but can assign it to variables. These variables will be equal to one another.  Example: >>> x = None >>> y = None >>> x == y Output: True
  • 94. Functions in Python:  What is a function?  What is the use of a function  Types of Function
  • 95. What is a function & use of a function  A function is a set of statements that take inputs, do some specific computation and produces output. The idea is to put some commonly or repeatedly done task together and make a function, so that instead of writing the same code again and again for different inputs, we can call the function.
  • 96. Types of Function  Python provides built-in functions like print(), etc. but we can also create our own functions. These functions are called user-defined functions.  That means python has two types of functions 1.User defined 2. Built-in function
  • 97. Syntax of Function:  def function_name(parameters): """docstring"""  statement(s)
  • 98.  Example of a function: >>>def greet(name): """This function greets to the person passed in as parameter""“ >>>print("Hello, " + name + ". Good morning!") greet(“Deepak”) O/p: Hello Deepak Good morning
  • 99. Parameters  Parameters are specified after the function name, inside the parentheses. We can add as many parameters as you want, just separate them with a comma. Ex: >>>def classing(num): >>>print(num+ " " "one") >>>classing("one") >>>classing("two") >>>classing("three") O/p: One one two one three one
  • 100. Default Parameter Value:  If we call the function without parameter, it uses the default value: >>>def apple(country="India"): >>>print("I am from" " " +country) >>>apple("Japan") >>>apple("Nepal") >>>apple() >>>apple("Bhutan") O/p: I am from Japan I am from Nepal I am from India I am from Bhutan
  • 101. Passing a List as a Parameter:  We can send any data types of parameter to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function. >>>def my_number(number): >>>for x in number: >>>print(x) >>>integers=[1,2,3,4,5] >>>my_number(integers) O/p: 1 2 3 4 5
  • 102. Return Value:  To let a function return a value, use the return statement  Example: def multiplication(number): return 10*number print(multiplication(1)) print(multiplication(2)) print(multiplication(3)) print(multiplication(4)) O/p: 10 20 30 40
  • 103. Recursion:  Python also accepts function recursion, which means a defined function can call itself.  Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.  The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.
  • 105. Conditions in Python  If condition  If else condition  If elif else condition  Nested condition
  • 106. If condition:  We use “If condition” to check either a condition is true or False. To move to the next statement if the give condition is satisfied .  Syntax: if expression: Statement else: Statement
  • 107.  Example:1 def fun(): X=10 Y=20 If x<y: Print(“y is greater”) O/p: Y is greater Example:2 Def fun(): X=30 Y=20 If x<y: Print(y is greater) O/p: ??????
  • 108. If else: Example:1 def fun(): X=10 Y=20 If x<y: Print(“y is greater”) Else: Print(“x is greater”) Fun() O/p: y is greater Example:2 def fun(): X=20 Y=20 if x<y: Print(“ x is greater”) Else x>y: Print(“y is greater”) O/p: ????
  • 109. If else elif: def fun(): X=20 Y=20 if x<y: Print(“ y is greater”) elif x>y: Print(“x is greater”) Else: Print(“both are equal”) Fun() O/p: Both are equal
  • 110. If else if:  def fun(name):  name=input("please enter your name: ")  if name=="Deepak":  print("Hai deepak How are you doing")  elif name=="John":  print("Hai John How are you doing")  elif name=="Bob":  print("Hai Bob How are you doing")  elif name=="Cat":  print("Hai Cat How are you doing")  else:  print("Hai" +name+ "How are you doing")  fun("name")
  • 111. Nested if:  There may be a situation when we want to check for another condition after a condition resolves to true. In such a situation, we can use the nested ifconstruct.  In a nested if construct,we can have an if...elif...else construct inside another if...elif...else construct.
  • 112. Syntax:  if expression1: statement(s) if expression2: statement(s) elif expression3: statement(s) elif expression4: statement(s) else: statement(s) else: statement(s)
  • 113. Example: age= int(input("please enter your age: ")) if age >= 18: weight=int(input("what is your weight: ")) if weight==150: print("over weight") elif weight== 120: print("little less than over weight") elif weight==100: print("noraml weight") elif weight==50: print("less weight") else: print(“sorry please enter age more than or equal to 18") O/p: ????
  • 114. For loop in python:  A for loop is used for repeating over a sequence in any of the a list, a tuple, a dictionary, a set, or a string.  This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.  With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
  • 115. Example:1 X=range(6) For a in x: Print(a) O/p: 0 1 2 3 4 5 Example:2 x=["apple","boy","cat","do g"] for a in x: print(a) O/p: Apple Boy Cat dog
  • 116. Example: 1 a="banana" for x in a: print(x) O/p: ??? The break Statement  With the break statement we can stop the loop before it has looped through all the items Example:2 fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break O/p: Apple Banana
  • 117.  Exit the loop when x is "banana", but this time the break comes before the print fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": break print(x) O/p: Apple Banana
  • 118. Example: x=["apple","boy","cat","dog"] for a in x: print(a) if a=="cat": break  O/p: apple boy cat
  • 119. Continue statement:  With the continue statement we can stop the current iteration of the loop, and continue with the next Example: fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x) O/p: Apple cherry
  • 120. While in python:  A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true. Syntax: while expression: statement(s)
  • 121.  Example: num=0 while num<=9: print("number is: ",+num) num=num+1 print("end of loop") O/p: ('number is: ', 0) end of loop ('number is: ', 1) end of loop ('number is: ', 2) end of loop ('number is: ', 3) end of loop ('number is: ', 4) end of loop ('number is: ', 5) end of loop ('number is: ', 6) end of loop ('number is: ', 7) end of loop ('number is: ', 8) end of loop ('number is: ', 9) end of loop
  • 122. What is OOPS in python:  Object Oriented programming is a programming style that is associated with the concept of Class, Objects and various other concepts revolving around these two, like Inheritance, Polymorphism, Abstraction, Encapsulation etc.  OOP is designed in such a way that one should focus on an object while programming and not the procedure. An object can be anything that we see around us. It can be a human (that has some properties like - name, address, DOB and so on), a chair (portrayed by size, material, cost etc), a school (depicted by place, student strength, results) etc.  Object oriented programming brings programming close to real life, as we are always dealing with an object, performing operations on it, using it's methods and variables etc.
  • 123. Concepts of OOP in python:  Class  Object  Inheritance  Encapsulation  Abstraction  Polymorphism
  • 124. Class: A Class is a logical grouping of data and functions. It gives the freedom to create data structures that contains arbitrary content and hence easily accessible. Object: A unique instance of a data structure that's defined by its class. An object comprises both data members (class variables and instance variables) and methods.
  • 125. Inheritance: The transfer of the characteristics of a class to other classes that are derived from it. Polymorphism: The word polymorphism means having many forms. In programming, polymorphism means same function name (but different signatures) being uses for different types.
  • 126.  Encapsulation: Encapsulation is defined as wrapping up of data and information under a single unit. In Object Oriented Programming, Encapsulation is defined as binding together the data and the functions that manipulates them. Abstraction: Abstraction means displaying only essential information and hiding the details. Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation.
  • 127. Class: Syntax of a class: 1 Class class_name(): statements Printing the class Example: Class Myclass(): a=10 Print(Myclass) O/p: 10
  • 128. Syntax of a class:2 class MyClass: variable1 = something variable2 = something def function1(self, parameter1, ...): self.variable1 = something else self.variable3 = something function statements... def function2(self, parameter1, ...): self.variable2 = something else function2 statements... Note: It's a mandatory parameter for every function defined in a class. self represents the current active object of the class, using which the function of the class is called.
  • 129.  Inheritance in Python If we have a class Parent and another class Child and we want the class Child to inherit the class Parent, then: Example: # Parent class class Parent: # class variable a = 10; b = 100; # some class methods def doThis(): Statements def doThat(): statements # Child class inheriting Parent class class Child(Parent): # child class variable x = 1000; y = -1; # some child class method def doWhat(): statements def doNotDoThat(): statements
  • 130.  Creating an Object: class MyClass: x = 5 p1 = MyClass() print(p1.x) Here pl is an object
  • 131.  Identity: Identity refers to some piece of information that can be used to identify the object of a class. It can be the name of the student, the company name of the car, etc.  Properties: The attributes of that object are called properties. Like age, gender, DOB for a student; or type of engine, number of gears for a car.  Behavior: Behavior of any object is equivalent to the functions that it can perform. In OOP it is possible to assign some functions to objects of a class. Taking the example forward, like a student can read/write, the car can
  • 132.  Sample code for creating class & Object: class Apollo: # define a variable destination = "moon" # defining the member functions def fly(self): print ("Spaceship flying...“) def get_destination(self): print ("Destination is: " + self.destination) # 1st object objFirst = Apollo() # 2nd object objSecond = Apollo() # lets change the destination for objFirst to mars objFirst.destination = "mars" # objFirst calling fly function objFirst.fly() # objFirst calling get_destination function objFirst.get_destination() # objSecond calling fly function objSecond.fly() # objSecond calling get_destination function objSecond.get_destination()
  • 133. Polymorphism  Polymorphism, or Poly + Morph, means "many forms. Precisely, Polymorphism is the property of any function or operator that can behave differently depending upon the input that they are fed with.  Polymorphism can be achieved in tow different forms, they are: :Over riding & Over loading
  • 134.  Overloading: For example, consider a function add(), which adds all its parameters and returns the result. In python we will define it as, Example: def add(a, b): print("addition of two numbers is: ", a+b) add(3,4) def add(a, b, c): print("addition of three numbers is: ", a+b+c) add(3,4,5) # to add 4 numbers def add(a, b, c, d): print("addition of four numbers is: ", a+b+c+d) add(3,4,5,6)
  • 135.  Method Overriding:  Python method overriding occurs simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make the latter able to satisfy that method call, so the implementations of its ancestors do not come in play.
  • 136. class Parent(object): def __init__(self): self.value = 5 def get_value(self): return self.value class Child(Parent): def get_value(self): return self.value + 1
  • 137. Polymorphism: Sample code: def add(x, y, z = 0): return x + y+z print(add(2, 3)) print(add(2, 3, 4)) O/p: 5 9
  • 138.  Example of polymorphism: class India(): def capital(self): print("New Delhi is the capital of India.") def language(self): print("Hindi the primary language of India.") def type(self): print("India is a developing country.") class USA(): def capital(self): print("Washington, D.C. is the capital of USA.") def language(self): print("English is the primary language of USA.") def type(self): print("USA is a developed country.") Object_ind = India() Object_usa = USA() for country in (object_ind, object_usa): country.capital() country.language() country.type()
  • 139. Example of Inheritance class Person(object): def __init__(self, name): self.name = name def getName(self): return self.name def isEmployee(self): return False class Employee(Person): def isEmployee(self): return True emp = Person("Geek1") print(emp.getName(), emp.isEmployee()) emp = Employee("Geek2") # An Object of Employee print(emp.getName(), emp.isEmployee())
  • 141. Some Examples on Data visualization using Pandas, Numpy & matplotlib.pyplot
  • 142.  NumPy: (Numerical Python) It is a core library for scientific computing in python, It provides a higher performance multidimensional array object & tools for working with these arrrays. Pandas: Pandas takes data from .csv, .tsv or SQL database files & creates a python object with rows and columns called data frames that looks very similar to table in a statistical Software
  • 143. matplotlib.pyplot: Matplotlib.pyplot is a library used to create 2D graphs & plots by using python scripts. It has a module named pyplot which makes things easy for plotting by providing feature to control line styles font properties formatting axes etc.,
  • 145. import pandas import numpy import matplotlib.pyplot as dee myarray=numpy.array([[1,2,3,4,5],[6,7,8,9, 0]]) rowname=["a","b"] columnname=["m","n","o","p","q"] x=pandas.DataFrame(myarray, index=rowname, columns=columnname) print(x) O/p: m n o p q a 1 2 3 4 5 b 6 7 8 9 0
  • 146. Python for plotting graphs:  Example: import pandas import numpy import matplotlib.pyplot as dee x=numpy.array([1,2,3,4,5]) y=numpy.array([3,4,5,6,7]) dee.scatter(x,y) dee.xlabel(“x-axis”) dee.ylabel(“y-axis”) dee.show() O/p:
  • 147. Plotting graphs: import pandas import matplotlib.pyplot as dee import numpy url="https://archive.ics.uci.edu/ml/machi ne-learning-databases/iris/iris.data" name=['sl','sw','pl','pw','class'] data=pandas.read_csv(url, names=name) data.plot(kind='box', subplots=True, layout=(1,4)) dee.show()
  • 148. Reading a CSV file: url="https://archive.ics.uci.edu/ml/machine -learning-databases/iris/iris.data" name=['sl','sw','pl','pw','class'] data=pandas.read_csv(url, names=name) print(data
  • 149. import pandas from sklearn import model_selection from sklearn.linear_model import LinearRegression url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/housing.data" names = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV'] dataframe = pandas.read_csv(url, delim_whitespace=True, names=names) array = dataframe.values X = array[:,0:13] Y = array[:,13] seed = 7 kfold = model_selection.KFold(n_splits=10, random_state=seed) model = LinearRegression() scoring = 'neg_mean_squared_error' results = model_selection.cross_val_score(model, X, Y, cv=kfold, scoring=scoring) print(results.mean())