SlideShare a Scribd company logo
Python
Chapter 5
Presented to
Prof. Vibhakar Mansotra
Dean of Mathematical science
Presented by
Akanksha Bali
Research Scholar, Dept of Computer science and IT
Contents
• Introduction
• Environment Setup
• Syntax
• Indentation
• Comments
• Variables
• Numbers
• Strings
• Operators
• Arrays
• Conditional Statements
• Functions
• Classes and Objects
• Inheritance
• File Handling
• Exception Handling
Python Introduction
• Python is a Programming Language. It was created by Guido van Rossum, and
released in 1991
• Used for web development, software development, Data Science, Mathematical
computing, Desktop GUI and so on.
Why Python?
• Works on different platforms ( Windows, Mac, etc).
• Has a similar syntax similar to the English Language.
• Has syntax that allows developers to write programs with fewer lines than some
other programming language.
Python Environment Setup
• Run the following command in the cmd.exe(command line) to check python installation for
windows.
C:Usersyour Name>python --version
• For Linux: python --version
• If python is not installed on compute, then we can download it for free from the following website:
http://www.python.org/
• To run a python file on the command line: C:Usersyour Name>python h.py
• To test a short amount of code in python command line, it is quickest and easiest not to write the
code in a file.
• C:usersYour Name>python
>>> print(“Hello, world”)
Python syntax
• Python programs must be written with a particular structure. The syntax
must be correct, or the interpreter will generate error message and not
execute the program.
• .py extension is used to save the file.
• We will consider two ways in which we can run
IDLE’s Interactive Shell: It is a simple python integrated development
environment available for Windows, Linux and Mac OS X. It is useful for
experimenting with small snippets of python code.
IDLE’s Editor: It has a built in editor. We can save our program using save
option in the file menu using .py extension and run the program using F5
function key or from the editors run menu:
Run -> Run Module. The output appears in the IDLE’s interactive shell
window.
Python Indentation
What is a code block?
• A block is a group of statements in a program or script. Usually, it consists of at least one statement
and declarations for the block, depending on the programming or scripting language.
• Programming languages usually use certain methods to group statements into blocks.
• For example in C/C++, the statements can be grouped into a code block by using the braces "{}",
#include<iostream.h>
void main()
{ cout<<"Im inside code block 1";
for(int i=0;i<=10;i++)
{
cout<<"Im inside code block 2";
for(int j=0;j<=10;j++)
{
cout<<"Im inside code block 3";
}
cout<<"Im inside code block 2";
}
cout<<"Im inside code block 1";
}
#include<iostream.h> void main(){ cout<<"Im inside code block 1";
for(int i=0;i<=10;i++){ cout<<"Im inside code block 2"; for(int
j=0;j<=10;j++){ cout<<"Im inside code block 3"; } cout<<"Im inside code
block 2"; } cout<<"Im inside code block 1"; }
Python Indentation (cont’d)
So what is a code block in Python?
• Python takes readability a step further by enforcing strict rules for writing code. Code
blocks in python are defined by their indentation.
• In the case of Python, it's a language requirement, not a matter of style. This principle
makes it easier to read and understand other people's Python code.
Block 1
Block 2
Block 3
Block 2
Block 1
print("This is block 1")
print("This is also block 1")
for i in range(10):
print("This is code block 2")
for j in range(10):
print("This is code block 3")
print("This is code block 2")
print("This is block 1")
Python Comments
• Comments can be used to explain Python code.
• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code.
Creating a Comment
• Comments starts with a #, and python will ignore them.
Example:
#This is a comment
Print(“hello”)
Python Variables
• Variables are containers for storing data values.
• Unlike other programming languages, Python has no command for declaring a variable.
• Variables do not need to be any particular type and even change type after they have been set.
• String variables can be declared either by using single or double quotes
Input Output
X=4
X=“candy”
print(x)
Candy
X=‘john’
print(x)
X=“john”
print(x)
john
john
Variable Names
• A variable can have a short name (like x and y) or a more descriptive name (age,
car name, total_volume).
Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
Assign Value to Multiple Variables
• Python allows you to assign values to multiple variables in one line.
Example x, y, z=“orange”, “banana”, “cherry”
Print(x)
Print(y)
Print(z)
• Python allows you to assign same value to multiple variables in one line.
Example x= y= z=“orange”
Print(x)
Print(y)
Print(z)
Swap two variables in
python
a=5
b=6
a,b=b,a
print(a)
print(b)
#return 6
5
Output Variables
• To combine both text and a variable, Python uses the + Character.
Example
x= “awesome”
print(“python is” + x) #return python is awesome
• We can also use the + character to add a variable to another variable.
Example
x= “python is”
y= “awesome”
z= x + y
print(z) #return python is awesome
• For numbers, the + character works as a mathematical operator.
x= 5
y= 10
print(x + y) #return 15
Output?
x= 5
y= “john”
print(x + y)
Python Basics by Akanksha Bali
Python Numbers
There are three numeric types in Python:
• int
• float
• Complex
Example:
x= 1 #int type
y= 2.5 #float type
z= 1j #complex type
Type Conversion : converting one type to another with int(), float() and complex()
methods.
Python Basics by Akanksha Bali
Random Number
• Python comes with a random number generator which can be used to generate various
distributions of numbers. To access the random number generator, the random module must
be imported.
Import random
Luckynumber=random.random()
print(Luckynumber)
• If we want to generate some int value between given range then you can use
random.randrange() function. For example : suppose we want to display a random number
between 1 and 10
Import random
print(random.randrange(1,10))
Python Basics by Akanksha Bali
Python Basics by Akanksha Bali
Python Strings
• We can assign a multiline string to a variable by using three double quotes or single quotes
Example: a = “ “ “ abcderjndndmnvvmccd
nndknfkslfnskdldnndnd” ” ”
Strings are Arrays
• Python does not have a character data type, a single character is simply a string with a length of 1.
• Square brackets can be used to access elements of the string.
Example : a= “Hello, World”
print(a[1]) # returns e
print(a[2:5]) # returns llo,
print(a.strip()) # returns Hello, World
print(len(a)) # returns 12
print(a.lower()) # returns hello, world
print(a.upper()) # returns HELLO, WORLD
print(a.replace(“H”,”J”) # returns Jello, World
print(a.split(“,”)) # returns [‘Hello’, ‘World’]
0 1 2 3 4 5 6 7 8 9 10
H e l l o , W o r l d
String Format
• We can combine string and numbers by using format() method.
• The format() method takes the passed arguments, formats them and places them in the string
where the placeholders {} are:
Example: quantity = 10
item=20
price = 50
myorder = “ I want {} pieces of item {} for {} dollars.”
print(myorder.format(quantity, item, price))
#returns I want 10 pieces of item 20 for 50 dollars
• We can use index numbers {0} to be sure the arguments are placed in the correct placeholders.
Example: myorder= “ I want to pay{2} dollars for {0} piece of item {1}.”
# returns I want to pay 50 dollars for 10 piece of item 20
Python Operators
Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Membership operators
• Bitwise operators
Arithmetic Operators
• Arithmetic operators are used with numeric values to perform common mathematical operations.
Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y
Assignment Operators
• Used to assign values to variables.
Operator Example Same as
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Comparison Operators
• Used to compare two values.
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Logical Operators
• Used to combine conditional statements
Operator Description Example
and Returns True if both
statements are true
x < 5 and x < 10
or Returns True if one of the
statements is true
x < 5 or x < 4
not Reverse the result, returns
False if the result is true
not(x < 5 and x < 10)
Membership Operators
• Used to test if sequence is presented in an object.
Operator Description Example
in Returns True if a sequence
with the specified value is
present in the object
x in y
not in Returns True if a sequence
with the specified value is
not present in the object
x not in y
Input Output
X=[“apple”, “banana”]
print(“pineapple” not in x)
True
Example:
Bitwise Operators
• Used to compare binary numbers
Operator Name Description
& AND Sets each bit to 1 if both
bits are 1
| OR Sets each bit to 1 if one of
two bits is 1
^ XOR Sets each bit to 1 if only
one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros
in from the right and let the
leftmost bits fall off
>> Signed right shift Shift right by pushing
copies of the leftmost bit in
from the left, and let the
rightmost bits fall off
Example
• >>>~12(complement of 12)
Ans -13
How?
12= 00001100 (binary format of 12)
= 11110011(1’s complement of 12)
13= 00001101(binary format of 13)
-13 = 2’s complement of 13
= 11110010( 1’s complement of 13)
= 11110011(2’s complement of 13)
• >>>12 & 13
Ans 12
12= 00001100
13=00001101
Import Math Functions
>>> X=sqrt(25)
Error:sqrt is not defined
>>> Import math
>>> X= math.sqrt(25)
>>>X
5.0
>>> print(math.floor(2.5))
2
>>>print(math.ceil(2.5))
3
>>>3**2
9
>>> print(math.pow(3,2))
9
>>>print(math.pi)
3.1415926.......
>>> print(math.e)
2.7182828459045
>>> import math as m
>>>x=m.sqrt(25)
>>>x
5
>>> from math import sqrt, pow
Python Collections (Arrays)
There are four collection data types in the Python programming language:
• List is a collection which is ordered and changeable. Allows duplicate members.
• Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
• Set is a collection which is unordered and unindexed. No duplicate members.
• Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
Python Lists
• Python has a built in methods that we can use on lists.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the
current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Python Lists (Cont’d)
Examples
1. thislist = [“apple”, “banana”, “cherry”]
print(thislist) #return [‘apple’, ‘banana’, ‘cherry’]
2. print(thislist[1]) #return banana
3. thislist[1] = “guava”
print(thislist) #return [‘apple’, ‘guava’, ‘cherry’]
4. for x in thislist:
print(x) #return apple guava cherry
5. if “apple” in thislist:
print(“yes, ‘ apple’ is in fruit list”) #return yes, ‘ apple’ is in
fruit list
6. print(len(thislist)) #return 3
7. thislist.append(“orange”)
print(thislist) #return [‘apple’, ‘guava’, ‘cherry’, ‘orange’]
8. thislist.insert(1, “banana”)
print(thislist) #return [‘apple’, ‘banana’, ‘cherry’, ‘orange’]
9. thislist.remove(“banana”)
print(thislist) #return [‘apple’, ‘cherry’, ‘orange’]
10. thislist.pop()
print(thislist) #return [‘apple’, ‘cherry’]
11. del thislist[0]
print(thislist) #return [‘cherry’]
12. del thislist
print(thislist) #return thislist is not defined
13. thislist = [“apple”, “banana”, “cherry”]
thislist.clear()
print(thislist) # return []
14. thislist = [“apple”, “banana”, “cherry”]
mylist=thislist.copy()
print(mylist) #return [‘apple’, ‘banana’, ‘cherry’]
Python Tuples Examples
1. thistuple = (“apple”, “banana”, “cherry”)
print(thistuple) #return (‘apple’, ‘banana’,
‘cherry’)
2. print(thistuple[1]) #return banana
3. thistuple[1] = “guava”
#return error (once a tuple is created, we cannot
change its value)
4. for x in thistuple:
print(x) #return apple banana cherry
5. if “apple” in thistuple:
print(“yes, ‘ apple’ is in fruit list”) #return yes, ‘
apple’ is in fruit list
6. print(len(thistuple)) #return 3
7. thistuple.append(“orange”)
thistuple.insert(1, “banana”)
thistuple.remove(“banana”)
thistuple.pop()
del thistuple[0]
#return error (tuple is unchangeable)
8. del thistuple
# deletes the tuple
Python Sets
Examples
1. thisset = {“apple”, “banana”, “cherry”}
print(thisset) #return {‘banana’, ‘cherry’, ‘apple’}
2. print(thisset[1]) #return error (not indexing)
3. thisset[1] = “guava”
print(thisset) #return error
4. for x in thisset:
print(x) #return cherry, apple, banana
5. print(“banana” in thisset) #return true
6. print(len(thisset)) #return 3
7. thisset.add(“orange”)
print(thisset) #return {‘banana’, ‘orange’,‘cherry’, ‘apple’}
8. thisset.update([“guava”, “mango”])
print(thisset) #return {‘apple’, ‘guave’, ‘orange’, ‘cherry’,
‘mango’, ‘banana’}
9. thisset.insert(1, “banana”)
print(thisset) #return error
9. thisset.remove(“banana”)
print(thisset) #return {‘apple’, ‘cherry’,
‘orange’,’guava’,’mango’}
10. thisset.pop()
print(thisset) #return {‘apple’, ‘cherry’,’mango’,
‘orange’}
11. del thisset[0]
print(thisset) #return error
12. del thisset
print(thisset) #return thisset is not defined
13. thisset = {“apple”, “banana”, “cherry”}
thisset.clear()
print(thisset) # return set()
Python Dictionaries
• A dictionary is a collection which is unordered, changeable and indexed.
• In python dictionaries are written with curly brackets, and they have key and values.
Example: thisdict={
“brand”: “Maruti”,
“model”: “swift”,
“year”: 2005
}
print(thisdict) #return {‘brand’ : ‘Maruti’, ‘model’: ‘swift’, ‘year’:2005}
• Accessing items: by referring key name inside square brackets.
x= thisdict[“model”] # return swift
• Change Values: by referring to its key name:
thisdict[“year”]=2007
print(thisdict) #return {‘brand’ : ‘Maruti’, ‘model’: ‘swift’, ‘year’:2007}
Python Dictionaries (cont.)
Examples
• For x in thisdict:
print(x) #return brand model year
• For x in thisdict.values():
print(x) #return Maruti swift 2007
• If “model” in thisdict:
print(“yes”) #return yes
• print(len(thisdict)) #return 3
• thisdict[“color”]=“silver”
print(thisdict) #return {‘brand’ : ‘Maruti’, ‘model’:
‘swift’, ‘year’:2007, ‘color’: ‘silver’}
• thisdict.pop(“model”)
print(thisdict) #return {‘brand’ : ‘Maruti’, ‘year’:2007,
‘color’: ‘silver’}
• thisdict.popitem()
print(thisdict) #return {‘brand’ : ‘Maruti’, ‘year’:2007}
• del thisdict[“year”]
print(thisdict) #return {‘brand’ : ‘Maruti’}
• del thisdict
print(thisdict) #return error
• thisdict={
“brand”: “Maruti”,
“model”: “swift”,
“year”: 2005
}
mydict=thisdict.copy()
print(mydict) #return {‘brand’ : ‘Maruti’, ‘model’:
‘swift’, ‘year’:2005}
• thisdict.clear()
print(thisdict) #return {}1
Number system Conversion
>>>Bin(25)
Ans: 0b11001
>>>obo101
5
>>>oct(25)
0o31
>>>hex(25)
0x19
>>>hex(10)
0xa
>>>0xa
15
Python if…else
• If statement is used to check a condition: if the condition is true, we run a block of
statements (called the if-block), else we process another block of statements (called the
else-block). The else clause is optional.
• a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
# return a is greater than b
Python While Loops
• A while loop statement in Python programming language repeatedly executes a target statement as
long as a given condition is true.
• i = 1
while i < 6:
print(i)
if (i == 3):
break
i += 1
# return 1,2
Python For Loops
• A for loop is a repetition control structure.
• The main difference between for loop and while loop is that the `for` statement iterates through a
collection of iteratable object and the while statement simply loops until the condition is False.
primes = [2, 3, 5, 7]
for num in primes:
print(num)
print ("Outside the for loop")
#return 2 3 5 7
Python Functions
• A function is a block of code which only runs when it is called.
• In Python a function is defined using the def keyword:
• To call a function, use the function name followed by parenthesis:
• Parameters are specified after the function name, inside the parentheses. You can
add as many parameters as you want, just separate them with a comma.
• If we call the function without parameter, it uses the default value.
def my_function(country = "Norway"): #create function
print("I am from " + country)
my_function("Sweden") #calling function #return I am from Sweden
my_function() #default parameter value I am from Norway
Functions (contd)
def sum(a,*b):
c=a
for i in b:
c=c+i
print (c)
Sum(5,6,7,8)
Sum(5,6)
#return 26
#return 11
Passing values as references
def update(x):
print(id(x))
x=8
print(id(x))
a=10
print(id(a))
update(a)
Print(“a”,a)
#return 1795
1795
x 8
a 10
Python Classes/objects
• Python is an object oriented programming language.
• Almost everything in Python is an object, with its properties and
methods.
• A Class is like an object constructor, or a "blueprint" for creating
objects.
• class MyClass: #create class
x = 5 #return nothing
• Create an object named p1, and print the value of x:
• p1 = MyClass() #create object
print(p1.x) #Access the value of x #return 5
Python Inheritance
• Inheritance is the capability of one class to derive or inherit the properties from
some another class. The benefits of inheritance are:
• It represents real-world relationships well.
• It provides reusability of a code.
• It is transitive in nature.
• Syntax:
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
Python Basics by Akanksha Bali
Python Inheritance
• To create a class that inherits the functionality from another class,
send the parent class as a parameter when creating the child class:
• class Student(Person):
pass
• Use the Student class to create an object, and then execute
the printname method:
• x = Student("Mike", "Olsen")
x.printname()
Multiple inheritance
Class A:
def feature1(self)
Print(“hello”)
Class B(A):
def feature2(self)
Print(“world”)
ClassC(B):
def feature3(self)
Print(“ good morning “)
Multiple inheritance
Class C(A,B)
Inheritance
Class A
Feature1
Class B
Feature2
Class C
Feature1
Feature2
Feature3
A
B
C
Multilevel Inheritance
A B
C
Multiple Inheritance
Class A
Feature1
Class B
Feature1
Feature2
Class C
Feature1
Feature2
Python Basics by Akanksha Bali
Python File Handling
• File handling is an important part of any web application.
• Python has several functions for creating, reading, updating, and deleting files.
• There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
• In addition you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
• Syntax: f = open("demofile.txt")
f = open("demofile.txt", "rt")
Python Write/Create Files
• To write to an existing file, you must add a parameter to the open() function:
• "a" - Append - will append to the end of the file
• "w" - Write - will overwrite any existing content
Example:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
Output:
C:UsersMy Name>python
demo_file_append.py
Hello! Welcome to demofile2.txt
This file is for testing purposes.
Good Luck!Now the file has more
content!
Create a New File
• To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example
Create a file called "myfile.txt":
f = open("myfile.txt", "x")
Result: a new empty file is created!
Example
Create a new file if it does not exist:
f = open("myfile.txt", "w")
Python Delete Files
• To delete a file, you must import the OS module, and run its os.remove() function:
• Example:
import os
os.remove("demofile.txt")
• Check if file exists, then delete it:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
• To delete an entire folder, use the os.rmdir() method:
Example: import os
os.rmdir("myfolder")
Python Exception Handling
• The try block lets you test a block of code for errors.
• The except block lets you handle the error.
• The finally block lets you execute code, regardless of the result of the try- and except blocks.
• When an error occurs, or exception as we call it, Python will normally stop and generate an error
message.
• These exceptions can be handled using the try statement:
• try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
#return Hello
Nothing went wrong
Python Basics by Akanksha Bali
The finally block, if specified, will be executed regardless if the try block raises an error or not.
References
• https://www.geeksforgeeks.org/python/
• https://youtu.be/QXeEoD0pB3E
Python Basics by Akanksha Bali

More Related Content

What's hot (20)

PDF
Introduction To Programming with Python
Sushant Mane
 
PPTX
Welcome to python workshop
Mukul Kirti Verma
 
PPTX
Python The basics
Bobby Murugesan
 
PDF
Lesson 03 python statement, indentation and comments
Nilimesh Halder
 
PPTX
Python-04| Fundamental data types vs immutability
Mohd Sajjad
 
PDF
Let’s Learn Python An introduction to Python
Jaganadh Gopinadhan
 
PPTX
Chapter 9 python fundamentals
Praveen M Jigajinni
 
PPTX
Python programming
Ashwin Kumar Ramasamy
 
PPTX
Python 3 Programming Language
Tahani Al-Manie
 
PPTX
Python for Beginners(v1)
Panimalar Engineering College
 
PDF
What is Python?
wesley chun
 
PDF
Python-02| Input, Output & Import
Mohd Sajjad
 
PPTX
Basic data types in python
sunilchute1
 
PPTX
Introduction to the basics of Python programming (part 3)
Pedro Rodrigues
 
PDF
Introduction to Python for Plone developers
Jim Roepcke
 
PPSX
DITEC - Programming with Java
Rasan Samarasinghe
 
PPTX
Python Session - 2
AnirudhaGaikwad4
 
Introduction To Programming with Python
Sushant Mane
 
Welcome to python workshop
Mukul Kirti Verma
 
Python The basics
Bobby Murugesan
 
Lesson 03 python statement, indentation and comments
Nilimesh Halder
 
Python-04| Fundamental data types vs immutability
Mohd Sajjad
 
Let’s Learn Python An introduction to Python
Jaganadh Gopinadhan
 
Chapter 9 python fundamentals
Praveen M Jigajinni
 
Python programming
Ashwin Kumar Ramasamy
 
Python 3 Programming Language
Tahani Al-Manie
 
Python for Beginners(v1)
Panimalar Engineering College
 
What is Python?
wesley chun
 
Python-02| Input, Output & Import
Mohd Sajjad
 
Basic data types in python
sunilchute1
 
Introduction to the basics of Python programming (part 3)
Pedro Rodrigues
 
Introduction to Python for Plone developers
Jim Roepcke
 
DITEC - Programming with Java
Rasan Samarasinghe
 
Python Session - 2
AnirudhaGaikwad4
 

Similar to Python Basics by Akanksha Bali (20)

PPTX
Basic concept of Python.pptx includes design tool, identifier, variables.
supriyasarkar38
 
PDF
Python basics_ part1
Elaf A.Saeed
 
PPTX
Presgfdjfwwwwwwwwwwqwqeeqentation11.pptx
aarohanpics
 
PPTX
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
yuvarajkumar334
 
PPT
Python programming
saroja20
 
PPTX
Python (Data Analysis) cleaning and visualize
IruolagbePius
 
PPTX
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
 
PPTX
modul-python-all.pptx
Yusuf Ayuba
 
PPTX
Learn about Python power point presentation
omsumukh85
 
PDF
An overview on python commands for solving the problems
Ravikiran708913
 
PPTX
Python knowledge ,......................
sabith777a
 
PPTX
Lecture1_introduction to python.pptx
MohammedAlYemeni1
 
PPT
Python Programming Introduction demo.ppt
JohariNawab
 
PPTX
BASICS OF PYTHON usefull for the student who would like to learn on their own
Nandini485510
 
PPTX
Chapter1 python introduction syntax general
ssuser77162c
 
PDF
Introduction-to-Python-print-datatype.pdf
AhmedSalama337512
 
PPTX
Python fundamentals
natnaelmamuye
 
PPTX
Python introduction towards data science
deepak teja
 
PPTX
CLASS-11 & 12 ICT PPT PYTHON PROGRAMMING.pptx
seccoordpal
 
PPTX
Python basics
Manisha Gholve
 
Basic concept of Python.pptx includes design tool, identifier, variables.
supriyasarkar38
 
Python basics_ part1
Elaf A.Saeed
 
Presgfdjfwwwwwwwwwwqwqeeqentation11.pptx
aarohanpics
 
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
yuvarajkumar334
 
Python programming
saroja20
 
Python (Data Analysis) cleaning and visualize
IruolagbePius
 
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
 
modul-python-all.pptx
Yusuf Ayuba
 
Learn about Python power point presentation
omsumukh85
 
An overview on python commands for solving the problems
Ravikiran708913
 
Python knowledge ,......................
sabith777a
 
Lecture1_introduction to python.pptx
MohammedAlYemeni1
 
Python Programming Introduction demo.ppt
JohariNawab
 
BASICS OF PYTHON usefull for the student who would like to learn on their own
Nandini485510
 
Chapter1 python introduction syntax general
ssuser77162c
 
Introduction-to-Python-print-datatype.pdf
AhmedSalama337512
 
Python fundamentals
natnaelmamuye
 
Python introduction towards data science
deepak teja
 
CLASS-11 & 12 ICT PPT PYTHON PROGRAMMING.pptx
seccoordpal
 
Python basics
Manisha Gholve
 
Ad

More from Akanksha Bali (7)

PDF
Feedback by akanksha bali, Feedback of FDP, Shortterm course, Workshop
Akanksha Bali
 
PDF
Feedback by akanksha bali
Akanksha Bali
 
PPTX
Regression analysis by akanksha Bali
Akanksha Bali
 
PPTX
Regression (Linear Regression and Logistic Regression) by Akanksha Bali
Akanksha Bali
 
PPT
Decision Tree, Naive Bayes, Association Rule Mining, Support Vector Machine, ...
Akanksha Bali
 
PPTX
Machine learning basics by akanksha bali
Akanksha Bali
 
PPTX
Machine learning basics
Akanksha Bali
 
Feedback by akanksha bali, Feedback of FDP, Shortterm course, Workshop
Akanksha Bali
 
Feedback by akanksha bali
Akanksha Bali
 
Regression analysis by akanksha Bali
Akanksha Bali
 
Regression (Linear Regression and Logistic Regression) by Akanksha Bali
Akanksha Bali
 
Decision Tree, Naive Bayes, Association Rule Mining, Support Vector Machine, ...
Akanksha Bali
 
Machine learning basics by akanksha bali
Akanksha Bali
 
Machine learning basics
Akanksha Bali
 
Ad

Recently uploaded (20)

PPTX
Online Cab Booking and Management System.pptx
diptipaneri80
 
PPTX
quantum computing transition from classical mechanics.pptx
gvlbcy
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PPTX
Basics of Auto Computer Aided Drafting .pptx
Krunal Thanki
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PPTX
Precedence and Associativity in C prog. language
Mahendra Dheer
 
DOCX
SAR - EEEfdfdsdasdsdasdasdasdasdasdasdasda.docx
Kanimozhi676285
 
PDF
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
PPTX
ETP Presentation(1000m3 Small ETP For Power Plant and industry
MD Azharul Islam
 
PDF
4 Tier Teamcenter Installation part1.pdf
VnyKumar1
 
PDF
CAD-CAM U-1 Combined Notes_57761226_2025_04_22_14_40.pdf
shailendrapratap2002
 
PPTX
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
PPTX
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
PDF
Air -Powered Car PPT by ER. SHRESTH SUDHIR KOKNE.pdf
SHRESTHKOKNE
 
PPTX
filteration _ pre.pptx 11111110001.pptx
awasthivaibhav825
 
PPTX
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
PDF
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
PDF
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
PPTX
sunil mishra pptmmmmmmmmmmmmmmmmmmmmmmmmm
singhamit111
 
PPTX
ENSA_Module_7.pptx_wide_area_network_concepts
RanaMukherjee24
 
Online Cab Booking and Management System.pptx
diptipaneri80
 
quantum computing transition from classical mechanics.pptx
gvlbcy
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
Basics of Auto Computer Aided Drafting .pptx
Krunal Thanki
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Precedence and Associativity in C prog. language
Mahendra Dheer
 
SAR - EEEfdfdsdasdsdasdasdasdasdasdasdasda.docx
Kanimozhi676285
 
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
ETP Presentation(1000m3 Small ETP For Power Plant and industry
MD Azharul Islam
 
4 Tier Teamcenter Installation part1.pdf
VnyKumar1
 
CAD-CAM U-1 Combined Notes_57761226_2025_04_22_14_40.pdf
shailendrapratap2002
 
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
Air -Powered Car PPT by ER. SHRESTH SUDHIR KOKNE.pdf
SHRESTHKOKNE
 
filteration _ pre.pptx 11111110001.pptx
awasthivaibhav825
 
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
sunil mishra pptmmmmmmmmmmmmmmmmmmmmmmmmm
singhamit111
 
ENSA_Module_7.pptx_wide_area_network_concepts
RanaMukherjee24
 

Python Basics by Akanksha Bali

  • 1. Python Chapter 5 Presented to Prof. Vibhakar Mansotra Dean of Mathematical science Presented by Akanksha Bali Research Scholar, Dept of Computer science and IT
  • 2. Contents • Introduction • Environment Setup • Syntax • Indentation • Comments • Variables • Numbers • Strings • Operators • Arrays • Conditional Statements • Functions • Classes and Objects • Inheritance • File Handling • Exception Handling
  • 3. Python Introduction • Python is a Programming Language. It was created by Guido van Rossum, and released in 1991 • Used for web development, software development, Data Science, Mathematical computing, Desktop GUI and so on. Why Python? • Works on different platforms ( Windows, Mac, etc). • Has a similar syntax similar to the English Language. • Has syntax that allows developers to write programs with fewer lines than some other programming language.
  • 4. Python Environment Setup • Run the following command in the cmd.exe(command line) to check python installation for windows. C:Usersyour Name>python --version • For Linux: python --version • If python is not installed on compute, then we can download it for free from the following website: http://www.python.org/ • To run a python file on the command line: C:Usersyour Name>python h.py • To test a short amount of code in python command line, it is quickest and easiest not to write the code in a file. • C:usersYour Name>python >>> print(“Hello, world”)
  • 5. Python syntax • Python programs must be written with a particular structure. The syntax must be correct, or the interpreter will generate error message and not execute the program. • .py extension is used to save the file. • We will consider two ways in which we can run IDLE’s Interactive Shell: It is a simple python integrated development environment available for Windows, Linux and Mac OS X. It is useful for experimenting with small snippets of python code. IDLE’s Editor: It has a built in editor. We can save our program using save option in the file menu using .py extension and run the program using F5 function key or from the editors run menu: Run -> Run Module. The output appears in the IDLE’s interactive shell window.
  • 6. Python Indentation What is a code block? • A block is a group of statements in a program or script. Usually, it consists of at least one statement and declarations for the block, depending on the programming or scripting language. • Programming languages usually use certain methods to group statements into blocks. • For example in C/C++, the statements can be grouped into a code block by using the braces "{}", #include<iostream.h> void main() { cout<<"Im inside code block 1"; for(int i=0;i<=10;i++) { cout<<"Im inside code block 2"; for(int j=0;j<=10;j++) { cout<<"Im inside code block 3"; } cout<<"Im inside code block 2"; } cout<<"Im inside code block 1"; } #include<iostream.h> void main(){ cout<<"Im inside code block 1"; for(int i=0;i<=10;i++){ cout<<"Im inside code block 2"; for(int j=0;j<=10;j++){ cout<<"Im inside code block 3"; } cout<<"Im inside code block 2"; } cout<<"Im inside code block 1"; }
  • 7. Python Indentation (cont’d) So what is a code block in Python? • Python takes readability a step further by enforcing strict rules for writing code. Code blocks in python are defined by their indentation. • In the case of Python, it's a language requirement, not a matter of style. This principle makes it easier to read and understand other people's Python code. Block 1 Block 2 Block 3 Block 2 Block 1 print("This is block 1") print("This is also block 1") for i in range(10): print("This is code block 2") for j in range(10): print("This is code block 3") print("This is code block 2") print("This is block 1")
  • 8. Python Comments • Comments can be used to explain Python code. • Comments can be used to make the code more readable. • Comments can be used to prevent execution when testing code. Creating a Comment • Comments starts with a #, and python will ignore them. Example: #This is a comment Print(“hello”)
  • 9. Python Variables • Variables are containers for storing data values. • Unlike other programming languages, Python has no command for declaring a variable. • Variables do not need to be any particular type and even change type after they have been set. • String variables can be declared either by using single or double quotes Input Output X=4 X=“candy” print(x) Candy X=‘john’ print(x) X=“john” print(x) john john
  • 10. Variable Names • A variable can have a short name (like x and y) or a more descriptive name (age, car name, total_volume). Rules for Python variables: • A variable name must start with a letter or the underscore character • A variable name cannot start with a number • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) • Variable names are case-sensitive (age, Age and AGE are three different variables)
  • 11. Assign Value to Multiple Variables • Python allows you to assign values to multiple variables in one line. Example x, y, z=“orange”, “banana”, “cherry” Print(x) Print(y) Print(z) • Python allows you to assign same value to multiple variables in one line. Example x= y= z=“orange” Print(x) Print(y) Print(z) Swap two variables in python a=5 b=6 a,b=b,a print(a) print(b) #return 6 5
  • 12. Output Variables • To combine both text and a variable, Python uses the + Character. Example x= “awesome” print(“python is” + x) #return python is awesome • We can also use the + character to add a variable to another variable. Example x= “python is” y= “awesome” z= x + y print(z) #return python is awesome • For numbers, the + character works as a mathematical operator. x= 5 y= 10 print(x + y) #return 15 Output? x= 5 y= “john” print(x + y)
  • 14. Python Numbers There are three numeric types in Python: • int • float • Complex Example: x= 1 #int type y= 2.5 #float type z= 1j #complex type Type Conversion : converting one type to another with int(), float() and complex() methods.
  • 16. Random Number • Python comes with a random number generator which can be used to generate various distributions of numbers. To access the random number generator, the random module must be imported. Import random Luckynumber=random.random() print(Luckynumber) • If we want to generate some int value between given range then you can use random.randrange() function. For example : suppose we want to display a random number between 1 and 10 Import random print(random.randrange(1,10))
  • 19. Python Strings • We can assign a multiline string to a variable by using three double quotes or single quotes Example: a = “ “ “ abcderjndndmnvvmccd nndknfkslfnskdldnndnd” ” ” Strings are Arrays • Python does not have a character data type, a single character is simply a string with a length of 1. • Square brackets can be used to access elements of the string. Example : a= “Hello, World” print(a[1]) # returns e print(a[2:5]) # returns llo, print(a.strip()) # returns Hello, World print(len(a)) # returns 12 print(a.lower()) # returns hello, world print(a.upper()) # returns HELLO, WORLD print(a.replace(“H”,”J”) # returns Jello, World print(a.split(“,”)) # returns [‘Hello’, ‘World’] 0 1 2 3 4 5 6 7 8 9 10 H e l l o , W o r l d
  • 20. String Format • We can combine string and numbers by using format() method. • The format() method takes the passed arguments, formats them and places them in the string where the placeholders {} are: Example: quantity = 10 item=20 price = 50 myorder = “ I want {} pieces of item {} for {} dollars.” print(myorder.format(quantity, item, price)) #returns I want 10 pieces of item 20 for 50 dollars • We can use index numbers {0} to be sure the arguments are placed in the correct placeholders. Example: myorder= “ I want to pay{2} dollars for {0} piece of item {1}.” # returns I want to pay 50 dollars for 10 piece of item 20
  • 21. Python Operators Python divides the operators in the following groups: • Arithmetic operators • Assignment operators • Comparison operators • Logical operators • Membership operators • Bitwise operators
  • 22. Arithmetic Operators • Arithmetic operators are used with numeric values to perform common mathematical operations. Operator Name Example + Addition x + y - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y ** Exponentiation x ** y // Floor division x // y
  • 23. Assignment Operators • Used to assign values to variables. Operator Example Same as = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 %= x %= 3 x = x % 3 //= x //= 3 x = x // 3 **= x **= 3 x = x ** 3 &= x &= 3 x = x & 3 |= x |= 3 x = x | 3 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3
  • 24. Comparison Operators • Used to compare two values. Operator Name Example == Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y
  • 25. Logical Operators • Used to combine conditional statements Operator Description Example and Returns True if both statements are true x < 5 and x < 10 or Returns True if one of the statements is true x < 5 or x < 4 not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
  • 26. Membership Operators • Used to test if sequence is presented in an object. Operator Description Example in Returns True if a sequence with the specified value is present in the object x in y not in Returns True if a sequence with the specified value is not present in the object x not in y Input Output X=[“apple”, “banana”] print(“pineapple” not in x) True Example:
  • 27. Bitwise Operators • Used to compare binary numbers Operator Name Description & AND Sets each bit to 1 if both bits are 1 | OR Sets each bit to 1 if one of two bits is 1 ^ XOR Sets each bit to 1 if only one of two bits is 1 ~ NOT Inverts all the bits << Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off >> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
  • 28. Example • >>>~12(complement of 12) Ans -13 How? 12= 00001100 (binary format of 12) = 11110011(1’s complement of 12) 13= 00001101(binary format of 13) -13 = 2’s complement of 13 = 11110010( 1’s complement of 13) = 11110011(2’s complement of 13) • >>>12 & 13 Ans 12 12= 00001100 13=00001101
  • 29. Import Math Functions >>> X=sqrt(25) Error:sqrt is not defined >>> Import math >>> X= math.sqrt(25) >>>X 5.0 >>> print(math.floor(2.5)) 2 >>>print(math.ceil(2.5)) 3 >>>3**2 9 >>> print(math.pow(3,2)) 9 >>>print(math.pi) 3.1415926....... >>> print(math.e) 2.7182828459045 >>> import math as m >>>x=m.sqrt(25) >>>x 5 >>> from math import sqrt, pow
  • 30. Python Collections (Arrays) There are four collection data types in the Python programming language: • List is a collection which is ordered and changeable. Allows duplicate members. • Tuple is a collection which is ordered and unchangeable. Allows duplicate members. • Set is a collection which is unordered and unindexed. No duplicate members. • Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
  • 31. Python Lists • Python has a built in methods that we can use on lists. Method Description append() Adds an element at the end of the list clear() Removes all the elements from the list copy() Returns a copy of the list count() Returns the number of elements with the specified value extend() Add the elements of a list (or any iterable), to the end of the current list index() Returns the index of the first element with the specified value insert() Adds an element at the specified position pop() Removes the element at the specified position remove() Removes the item with the specified value reverse() Reverses the order of the list sort() Sorts the list
  • 32. Python Lists (Cont’d) Examples 1. thislist = [“apple”, “banana”, “cherry”] print(thislist) #return [‘apple’, ‘banana’, ‘cherry’] 2. print(thislist[1]) #return banana 3. thislist[1] = “guava” print(thislist) #return [‘apple’, ‘guava’, ‘cherry’] 4. for x in thislist: print(x) #return apple guava cherry 5. if “apple” in thislist: print(“yes, ‘ apple’ is in fruit list”) #return yes, ‘ apple’ is in fruit list 6. print(len(thislist)) #return 3 7. thislist.append(“orange”) print(thislist) #return [‘apple’, ‘guava’, ‘cherry’, ‘orange’] 8. thislist.insert(1, “banana”) print(thislist) #return [‘apple’, ‘banana’, ‘cherry’, ‘orange’] 9. thislist.remove(“banana”) print(thislist) #return [‘apple’, ‘cherry’, ‘orange’] 10. thislist.pop() print(thislist) #return [‘apple’, ‘cherry’] 11. del thislist[0] print(thislist) #return [‘cherry’] 12. del thislist print(thislist) #return thislist is not defined 13. thislist = [“apple”, “banana”, “cherry”] thislist.clear() print(thislist) # return [] 14. thislist = [“apple”, “banana”, “cherry”] mylist=thislist.copy() print(mylist) #return [‘apple’, ‘banana’, ‘cherry’]
  • 33. Python Tuples Examples 1. thistuple = (“apple”, “banana”, “cherry”) print(thistuple) #return (‘apple’, ‘banana’, ‘cherry’) 2. print(thistuple[1]) #return banana 3. thistuple[1] = “guava” #return error (once a tuple is created, we cannot change its value) 4. for x in thistuple: print(x) #return apple banana cherry 5. if “apple” in thistuple: print(“yes, ‘ apple’ is in fruit list”) #return yes, ‘ apple’ is in fruit list 6. print(len(thistuple)) #return 3 7. thistuple.append(“orange”) thistuple.insert(1, “banana”) thistuple.remove(“banana”) thistuple.pop() del thistuple[0] #return error (tuple is unchangeable) 8. del thistuple # deletes the tuple
  • 34. Python Sets Examples 1. thisset = {“apple”, “banana”, “cherry”} print(thisset) #return {‘banana’, ‘cherry’, ‘apple’} 2. print(thisset[1]) #return error (not indexing) 3. thisset[1] = “guava” print(thisset) #return error 4. for x in thisset: print(x) #return cherry, apple, banana 5. print(“banana” in thisset) #return true 6. print(len(thisset)) #return 3 7. thisset.add(“orange”) print(thisset) #return {‘banana’, ‘orange’,‘cherry’, ‘apple’} 8. thisset.update([“guava”, “mango”]) print(thisset) #return {‘apple’, ‘guave’, ‘orange’, ‘cherry’, ‘mango’, ‘banana’} 9. thisset.insert(1, “banana”) print(thisset) #return error 9. thisset.remove(“banana”) print(thisset) #return {‘apple’, ‘cherry’, ‘orange’,’guava’,’mango’} 10. thisset.pop() print(thisset) #return {‘apple’, ‘cherry’,’mango’, ‘orange’} 11. del thisset[0] print(thisset) #return error 12. del thisset print(thisset) #return thisset is not defined 13. thisset = {“apple”, “banana”, “cherry”} thisset.clear() print(thisset) # return set()
  • 35. Python Dictionaries • A dictionary is a collection which is unordered, changeable and indexed. • In python dictionaries are written with curly brackets, and they have key and values. Example: thisdict={ “brand”: “Maruti”, “model”: “swift”, “year”: 2005 } print(thisdict) #return {‘brand’ : ‘Maruti’, ‘model’: ‘swift’, ‘year’:2005} • Accessing items: by referring key name inside square brackets. x= thisdict[“model”] # return swift • Change Values: by referring to its key name: thisdict[“year”]=2007 print(thisdict) #return {‘brand’ : ‘Maruti’, ‘model’: ‘swift’, ‘year’:2007}
  • 36. Python Dictionaries (cont.) Examples • For x in thisdict: print(x) #return brand model year • For x in thisdict.values(): print(x) #return Maruti swift 2007 • If “model” in thisdict: print(“yes”) #return yes • print(len(thisdict)) #return 3 • thisdict[“color”]=“silver” print(thisdict) #return {‘brand’ : ‘Maruti’, ‘model’: ‘swift’, ‘year’:2007, ‘color’: ‘silver’} • thisdict.pop(“model”) print(thisdict) #return {‘brand’ : ‘Maruti’, ‘year’:2007, ‘color’: ‘silver’} • thisdict.popitem() print(thisdict) #return {‘brand’ : ‘Maruti’, ‘year’:2007} • del thisdict[“year”] print(thisdict) #return {‘brand’ : ‘Maruti’} • del thisdict print(thisdict) #return error • thisdict={ “brand”: “Maruti”, “model”: “swift”, “year”: 2005 } mydict=thisdict.copy() print(mydict) #return {‘brand’ : ‘Maruti’, ‘model’: ‘swift’, ‘year’:2005} • thisdict.clear() print(thisdict) #return {}1
  • 37. Number system Conversion >>>Bin(25) Ans: 0b11001 >>>obo101 5 >>>oct(25) 0o31 >>>hex(25) 0x19 >>>hex(10) 0xa >>>0xa 15
  • 38. Python if…else • If statement is used to check a condition: if the condition is true, we run a block of statements (called the if-block), else we process another block of statements (called the else-block). The else clause is optional. • a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b") # return a is greater than b
  • 39. Python While Loops • A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true. • i = 1 while i < 6: print(i) if (i == 3): break i += 1 # return 1,2
  • 40. Python For Loops • A for loop is a repetition control structure. • The main difference between for loop and while loop is that the `for` statement iterates through a collection of iteratable object and the while statement simply loops until the condition is False. primes = [2, 3, 5, 7] for num in primes: print(num) print ("Outside the for loop") #return 2 3 5 7
  • 41. Python Functions • A function is a block of code which only runs when it is called. • In Python a function is defined using the def keyword: • To call a function, use the function name followed by parenthesis: • Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma. • If we call the function without parameter, it uses the default value. def my_function(country = "Norway"): #create function print("I am from " + country) my_function("Sweden") #calling function #return I am from Sweden my_function() #default parameter value I am from Norway
  • 42. Functions (contd) def sum(a,*b): c=a for i in b: c=c+i print (c) Sum(5,6,7,8) Sum(5,6) #return 26 #return 11 Passing values as references def update(x): print(id(x)) x=8 print(id(x)) a=10 print(id(a)) update(a) Print(“a”,a) #return 1795 1795 x 8 a 10
  • 43. Python Classes/objects • Python is an object oriented programming language. • Almost everything in Python is an object, with its properties and methods. • A Class is like an object constructor, or a "blueprint" for creating objects. • class MyClass: #create class x = 5 #return nothing • Create an object named p1, and print the value of x: • p1 = MyClass() #create object print(p1.x) #Access the value of x #return 5
  • 44. Python Inheritance • Inheritance is the capability of one class to derive or inherit the properties from some another class. The benefits of inheritance are: • It represents real-world relationships well. • It provides reusability of a code. • It is transitive in nature. • Syntax: class BaseClass: Body of base class class DerivedClass(BaseClass): Body of derived class
  • 46. Python Inheritance • To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class: • class Student(Person): pass • Use the Student class to create an object, and then execute the printname method: • x = Student("Mike", "Olsen") x.printname()
  • 47. Multiple inheritance Class A: def feature1(self) Print(“hello”) Class B(A): def feature2(self) Print(“world”) ClassC(B): def feature3(self) Print(“ good morning “) Multiple inheritance Class C(A,B)
  • 48. Inheritance Class A Feature1 Class B Feature2 Class C Feature1 Feature2 Feature3 A B C Multilevel Inheritance A B C Multiple Inheritance Class A Feature1 Class B Feature1 Feature2 Class C Feature1 Feature2
  • 50. Python File Handling • File handling is an important part of any web application. • Python has several functions for creating, reading, updating, and deleting files. • There are four different methods (modes) for opening a file: "r" - Read - Default value. Opens a file for reading, error if the file does not exist "a" - Append - Opens a file for appending, creates the file if it does not exist "w" - Write - Opens a file for writing, creates the file if it does not exist "x" - Create - Creates the specified file, returns an error if the file exists • In addition you can specify if the file should be handled as binary or text mode "t" - Text - Default value. Text mode "b" - Binary - Binary mode (e.g. images) • Syntax: f = open("demofile.txt") f = open("demofile.txt", "rt")
  • 51. Python Write/Create Files • To write to an existing file, you must add a parameter to the open() function: • "a" - Append - will append to the end of the file • "w" - Write - will overwrite any existing content Example: f = open("demofile2.txt", "a") f.write("Now the file has more content!") f.close() #open and read the file after the appending: f = open("demofile2.txt", "r") print(f.read()) Output: C:UsersMy Name>python demo_file_append.py Hello! Welcome to demofile2.txt This file is for testing purposes. Good Luck!Now the file has more content!
  • 52. Create a New File • To create a new file in Python, use the open() method, with one of the following parameters: "x" - Create - will create a file, returns an error if the file exist "a" - Append - will create a file if the specified file does not exist "w" - Write - will create a file if the specified file does not exist Example Create a file called "myfile.txt": f = open("myfile.txt", "x") Result: a new empty file is created! Example Create a new file if it does not exist: f = open("myfile.txt", "w")
  • 53. Python Delete Files • To delete a file, you must import the OS module, and run its os.remove() function: • Example: import os os.remove("demofile.txt") • Check if file exists, then delete it: import os if os.path.exists("demofile.txt"): os.remove("demofile.txt") else: print("The file does not exist") • To delete an entire folder, use the os.rmdir() method: Example: import os os.rmdir("myfolder")
  • 54. Python Exception Handling • The try block lets you test a block of code for errors. • The except block lets you handle the error. • The finally block lets you execute code, regardless of the result of the try- and except blocks. • When an error occurs, or exception as we call it, Python will normally stop and generate an error message. • These exceptions can be handled using the try statement: • try: print("Hello") except: print("Something went wrong") else: print("Nothing went wrong") #return Hello Nothing went wrong
  • 56. The finally block, if specified, will be executed regardless if the try block raises an error or not.