0% found this document useful (0 votes)
14 views

Python-Course-PPT

Python is a high-level, interpreted programming language known for its readability and simplicity, making it easy to learn and use. It supports multiple programming paradigms, including object-oriented and procedural programming, and has extensive libraries for various applications. Python is free, open-source, and portable across different platforms, making it suitable for a wide range of development tasks from web applications to data analysis.

Uploaded by

Thilaga adona
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Python-Course-PPT

Python is a high-level, interpreted programming language known for its readability and simplicity, making it easy to learn and use. It supports multiple programming paradigms, including object-oriented and procedural programming, and has extensive libraries for various applications. Python is free, open-source, and portable across different platforms, making it suitable for a wide range of development tasks from web applications to data analysis.

Uploaded by

Thilaga adona
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 184

WHICH ONE TO

CHOOSE AND WHY ?


What is Python ? Python is an interpreted, high-level,
general-purpose programming language. Created
by Guido van Rossum and first released in 1991,
Python's design philosophy emphasizes code
readability with its notable use of significant
whitespace.
What is Python ?
Python is one of those rare languages which can claim to be both simple and
powerful. You will find yourself pleasantly surprised to see how easy it is to
concentrate on the solution to the problem rather than the syntax and
structure of the language you are programming in.
FEATURES OF PYTHON
● Simple - Reading a good Python program feels almost like reading English, although very strict English!
● Easy to learn - As you will see, Python is extremely easy to get started with. Python has an extraordinarily
simple syntax, as already mentioned.
● Free and Open Source - In simple terms, you can freely distribute copies of this software, read its source
code, make changes to it, and use pieces of it in new free programs.
● High Level Language - When you write programs in Python, you never need to bother about the low-level
details such as managing the memory used by your program, etc.
● Portable - All your Python programs can work on any of these platforms without requiring any changes at all if
you are careful enough to avoid any system-dependent features.

You can use Python on GNU/Linux, Windows, FreeBSD, Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, BeOS,
OS/390, z/OS, Palm OS, QNX, VMS, Psion, Acorn RISC OS, VxWorks, PlayStation, Sharp Zaurus, Windows CE and
PocketPC!
FEATURES OF PYTHON
● Interpreted - Python, on the other hand, does not need compilation to binary. You just run the program
directly from the source code. Internally, Python converts the source code into an intermediate form called
bytecodes and then translates this into the native language of your computer and then runs it.

● Object oriented -Python supports procedure-oriented programming as well as object-oriented programming.


In procedure-oriented languages, the program is built around procedures or functions which are nothing but
reusable pieces of programs. In object-oriented languages, the program is built around objects which combine
data and functionality.

● Extensive Libraries - The Python Standard Library is huge indeed. It can help you do various things
involving regular expressions,documentation generation, unit testing, threading, databases, web browsers,
CGI, FTP, email, XML, XML-RPC, HTML, WAV files, cryptography, GUI (graphical user interfaces), and other
system-dependent stuff. Remember, all this is always available wherever Python is installed.
● Free and open source.

What is Python ?

● Interpreted, object oriented, high level
programming language.

● We can do any type of development that we
want.

● It is designed to be human readable.

● Hundreds of python libraries and
frameworks.

● Huge community.
What can we do with Python ?

GAMES Data Analysis AI/ML

3D GRAPHICS Web Apps Mobile Apps

GUIs Hacking Desktop Apps

ROBOTICS Testing Automation


DIFFERENT PYTHON
IDE
Python Installation and Setting Up
Environment
BASIC PYTHON SYNTAX

To display any output we use print() function.

INPUT /
OUTPUT
To take input from the user we use input() function.
All about print()
The print() function prints the specified message to the screen, or other standard output specified.

Just calling the print function without any message or


without passing any argument will result in a empty line.
We can call print multiple times.

We can pass message a string directly in print and it will


display that string in the python shell. Not only string we
can pass any data type in python and it will print that to
the shell.

We can also pass variables in print and it will print the


data stored in that variable. Not only one variable we can
pass n number of variables separated by commas.
All about print()
The print() function prints the specified message to the screen, or other standard output specified.

We can pass multiple arguments all at once and it will print it in the same line.

Multiple print will result in multiple lines. First print will be printed in the first line
and second print will be printed in the second line.

We can print in the same line by specifying the end argument in print. By default it is ‘\n’ that
means new line. We can change that to empty space just by giving end = ‘’
All about print()
We can also print the values passed in one print statement into multiple lines and format it according to our wish.

‘\n’ is used to break the line and Here we have specified ‘\n\t’. ‘\n’
print everything after \n in new line will break the line and ‘\t’ is used
for tab or four spaces.
Comments in Python
Comments are non-executable python code.

We use comments to -

● Explain python code.


● Make the code more readable. # is used for single line comment.
● Prevent Execution when testing the code

In python we use # and ‘‘‘ ’’’ to put


comment in our code.

‘‘‘ ’’’ is used for multi line comment.


• Variables are named memory locations that
store data.
• Python is dynamically typed which means you
don’t have to declare the type of variables
during initialization.

VARIABLES Assigned value

Variable name

To check the memory location we use


id(variable name)

print(id(first_num )
)
● Variable name should start with a letter or underscore.
● We cannot use python keywords as variable names.
RULES FOR NAMING ●

Do not use numbers at the start of variable names.
The only allowed special character is underscore (_) .
VARIABLES ● Variable names can only have alphanumeric characters
(A-Z,a-z,0-9) and underscore.
● Variable names are case sensitive (e.g Age, age and AGE
are different variable names)
OPERATORS
Operator Operands

Operators are used to perform operations


on operands (variables and values) .
Types of operators in python
Data types
PYTHON DATA TYPES

Numeric Dictionary Boolean Set Collection type

Int Float Complex Strings Lists Tuples


Integer type -
Whole number without decimal points (10,1,-1,240, etc.)

Float type -
Numeric Floats are the numbers with decimal values.

Types: Complex -
Complex types has a real and imaginary part.
Hex function -
hex() function is used to convert a decimal number into a
hexadecimal form

Bin Function -
Numeric bin() is used to convert a decimal number into a binary
number.

Types: Here ob is used to represent binary number

Oct function
oct() is used to convert a decimal number into a octal form.

Here Oo is used to represent octal numbers.


String:
String literals in python are surrounded by
either single quote,double quotes or triple
quotes.
Boolean:
Booleans are True and False
types.
Data Type Conversion:
int
float
string
boolean
Conversion
from int to :
float
string
boolean
Conversion
from float to :
int
string
boolean
Conversion
from string to :
int
boolean
float
Conversion
from bool to :
int
string
float
String operations
Strings are the ordered sequence of the character that means we can access
the individual characters by using the index at which the character is present.
Indexing starts from 0

String Indexing : Name = ‘Codegnan’

● Strings are immutable data types.


● Strings are structured data types so Indexes 0123456 7

they can be indexed and sliced.


● We can do positive and negative
Negative Indexing
indexing. Positive indexing starts
with 0 from left to the right.
● Negative indexing starts from -1 Name = ‘Codegnan’
from
Indexes -9-8-7-6-5-4-3-2-1
Negative
Positive Indexing Indexing

Attempting to index beyond the end of Attempting to index beyond the start of
string results in error. string using negative indexing also results
in error.
#slicing
a = 'Codegnan code stars'

String Slicing : #slicing --- a[start : end]


--> returns the string between
start index and end index
● By slicing a string we are creating a
substring a[0 : 10]
● When slicing you have to specify
the start index and end index.

The string a is sliced starting from index 0 to


index 10. When slicing the end index in exclusive.
It is not included and whitespaces are also
indexed so we got the output ‘codegnan c’
String Slicing :
● We can also omit the start and end
index.
● Omitting start index means the
If you choose to omit the start and end index the
string starts from zero till the end
result will be the whole string itself.
index specified.
● Omitting the end index means the
string will start from the start index
specified till the end.
String Slicing :
● We can also do slicing using the
negative indexing.
● Slicing string using mix of positive
and negative index is also possible.
In slicing operations if the end or the start index is not in the range it does not
throws any error. It will just slice the element till the last index if the end index is
out of range or it will slice the element from 0 index if the start index is out of
range.
String Slicing And
Striding :
● In addition to slicing we can also Here we have given stride of 2. That
include striding using another : means it will slice from start index to end
● Striding or step size is specified to index specified and give back every
skip the character while slicing. second element from that slice.
● By default the stride is 1.
String Slicing And
Striding :
Here we have given start index larger
● We can also use negative values for
than the end index. It simply means that
striding. But when giving negative
start from 5 go backwards with step of 1
stride value we have to give the
till 0.
start index bigger than the end
index.
Here it gives us every
second element
starting from 5 going
backwards with step
of 2 till 0.
Not specifying the start and the end index
will result in the string itself in entirety and Modifying a string element like above will
giving step size as -1 will reverse all the result in error as strings are immutable data
element of the string. types.
Old Style String Formatting

Strings in python have a unique built in operation that can be accessed by using %
operator to do positional string formatting.
#string formatting
first_name = 'John'
last_name = 'Harris'
print('Hello',first_name,last_name)

New String #string concatenation

Formatting :
print(first_name + ' ' + last_name)

#place holders and format() method


print('Hello, {} {}'.format(first_name,last_name))

#using 'f' string


print(f'Hello, {first_name} {last_name}')
Old way of string formatting.

String
Formatting :
str.format() method

We can use .format method to specify the values in


place holders. Represented by {} empty curly braces.
Here the first argument is passed in the first place
holder and second argument is passed in second
place holder.
String
Formatting : We can also give names to these place holders. Here we have
given the name ‘name’ to first place holder and ‘course’ to the
str.format() method second place holder. While passing the arguments we have to
pass keyword arguments to fill these place holders.
String
Formatting : Here we have given the arguments the place holders are going to
store the values. We have given 0 in first place holder and also 0 in
str.format() method second place holder and 1 in third place holder that means in first
and second place holder the values will be the one passed and 0th
argument.
String We can directly pass the values in the place holders itself without
using any explicit format method.

Formatting :
str.format() method
Using ‘+’ operator on string
will result in string
concatenation.

String
Functions: Using ‘*’ operator will result
in multiplying the string that
many number of times.

ord() gives the numeric


equivalent of a character
string.

chr() gives the


character equivalent of
a numeric value.
#to check all the methods in str
help(dir(str))

#count total occurrence of a letter

String a = ''' twinkle twinkle little star'''


a.count('t')

Methods : #replace a string with another string


a.replace('star','moon')

#find method() gives the index value of


first occurence of the string
a.find('twinkle')
#lower all the letters
b = "Hello Codegnan stars"
String
b.lower()
Methods :
b = "Hello Codegnan stars"
print(b.lower()) #changes all the letters to lowercase
print(b.upper()) #changes all the letters to uppercase
print(b.capitalize()) #changes the first letter into caps, other in lower
print(b.title()) #changes first letter of each word into caps

c = 'codegnan'
print(c.isupper()) #check whether the string is uppercase or not
print(c.islower()) #check whether the string is lowercase or not
Returns Boolean
print(c.isdigit()) #check whether the string is a digit or not
True or False
print(c.isalpha()) #check whether the string is alphanumeric(A-Z,a-z) or not
print(c.startswith('lo')) #check whether the string starts with "lo"
print(c.endswith('l')) #checks whether the string ends with "l"
String Methods
Some more methods -
➢ index() - gives the index of the string.
➢ rindex() - looks from right to left.
➢ isalnum() - checks whether the string is alphanumeric or not.
➢ isspace() - checks if the string is having only whitespace.
➢ isascii() - checks if the string has ascii representation or not.
➢ rfind() - looks for the specified string from right side.
➢ rjust() - right align the string
➢ ljust() - left align the string.
➢ swapcase() - swaps the case of the string.
➢ isdecimal() - checks if the string has decimal values.
➢ casefold() - converts all the alphabets in lower.
languages = "java,python,c,c++"
d = languages.split(',') #splits the string
after each occurrence of ',' into different
substrings and return a list of strings
print(d)

String a = " ".join(d) #join method takes all the strings in

Methods : iterable and joins into single string


print(a)
split
join
name = " John "
strip
print(name.strip()) #removes the whitespaces from string
print(name.lstrip()) #removes whitespace from the left
print(name.rstrip()) #removes the whitespace from the
right
LISTS
● Lists are ordered collection of elements enclosed within a bracket
and separated by commas.

● Lists are mutable data types that means we can add, update and
delete the element of the lists.

● Lists can be indexed and sliced.

● Lists are also a type of iterables in python.

Lists ● We can store multiple kind of data types in lists.

Syntax to create list

lst = [element1, element2,.. ,elementn]


Indexing and slicing operations in lists are same
as in strings

Lists:
Indexing
Slicing
length of list
Lists Methods
Lists: course = ["Python","Html","Java","Machine
Learning" ] #create list - course
Append() - adds the element at
print(course) #print course
the end of the list.
course.append ('IoT') #append IoT to list course
print(course) #print course after appending
'IoT'
#Extend

Lists: course = ["Python","Html","Java","Machine Learning"]


#create list - course
extend() - extends the list by add_course = ['IoT','ReactJs'] #create another list
appending all the elements add_course
from the iterable. course.extend(add_course) #extend add_course to list
course
print(course) #print course after extending add_course
Lists: #clear
course = ["Python","Html","Java","Machine
Clear ()- clears all the element Learning" ] #create list - course
from the list. print(course) #print course
course.clear () #append IoT to list course
print(course) #print course after clearing
Lists: #insert
course = ['Machine Learning' ,'Data
insert ()- insert an element at Science','Python','JavaScript' ]
the given position. print(course)
course.insert (1,'Java') #insert 'java' at index
1
print(course)
Lists: #remove
course = ['Machine Learning' ,'Data
remove (x)- removes first Science','Python','JavaScript' ,'Data Science' ]
element from the list whose print(course)
value is x.
course.remove ('Data Science' ) #removes the first
element with the value 'Data Science'
print(course)
Lists: #copy
course = ['Machine Learning' ,'Data
copy ()- returns the copy of Science','Python','JavaScript' ,'Data Science' ]
the specified lists. x = course.copy () #copy list course in x
print(course)
print(x)
Lists: #count
course = ['Machine Learning' ,'Data
count ()- returns the number Science','Python','JavaScript' ,'Data Science' ]
of times element appears in the course.count ('Data Science' ) #returns number of
list.
times data science appears in the list
Lists: #index
course = ['Machine Learning' ,'Data
index ()- returns the index of Science','Python','JavaScript' ,'Data Science' ]
the first element with the course.index ('Data Science' ) #returns first index
specified value.
of "data science"
Lists: #pop
last_course = course.pop (1)
pop()- remove the item at the #removes the element at index 1 and stores it
given position in the string and into last_course
return it. If index is not
specified it removes the last print(course)
element and returns it. print(last_course )
#reverse
Lists: course = ['Machine Learning' , 'Python',
'JavaScript' , 'Data Science' ]
reverse()-reverse the element
of the list in place. print(course)
course.reverse () #reverse the element in the list
print(course)
#sort
Lists: course = ['Machine Learning' , 'Python',
'JavaScript' , 'Data Science' ]
sort()-sort the item of the lists
in place. print(course)
course.sort () #sort the element in the list
print(course)
#delete
Lists: lst = ['Ram','John','Sam','Kartik']
print(lst)
del()-permanently deletes the
list del lst #delete the lst
print(lst)
#concatenation
Lists: course_1 = ['Python','Java']
course_2 = ['ML','Data Science' ]
Concatenate-the most
conventional way of print(course_1 + course_2 ) # concat course_1 and
concatenating two lists is the course_2
use of “+” operator.
Tuples
● Tuples are ordered collection of elements enclosed within a
round bracket and separated by commas.

● Tuples are immutable data types that means we cannot add,


update and delete the element of the tuples.

● Tuples can be indexed and sliced in similar ways as strings


and lists.

● Tuples are also a type of iterables in python.


Tuples ● We can store multiple kind of data types in tuples

Syntax to create tuples

tup = (element1, element2,.. ,elementn)


Tuple Methods
Tuple: a = ('Ram','Rahul',23,23,True)
count() - return the count of
the specified element. a.count(23) #returns the count of element '23'
Tuple: a = ('Ram','Rahul',23,23,True)
index() - returns the first index
of specified elements. a.index(23) #returns the index of element '23'
Sets
● Sets are unordered collection of elements enclosed
within a curly bracket and separated by commas.

● Sets are randomly ordered

● Set does not stores duplicate values.

Sets ● The elements contained in a set must be of immutable


type.

● Sets cannot be indexed and sliced.

Syntax to create sets

s = {element1, element2,.. ,elementn}


s = set(iterable)
Set Methods
Set: #add
add() - add method adds the
element to the set. a = {1,5,6,8,9}
print(a)
a.add(10) #add 10 to set a
print(a)
Set: a = {1,5,6,8,9}
len(setname) - returns the
number of elements in the set print(len(a)) #check the length of set a
Set: #issubset()
s.issubset(t) - check if every
element of s is in t. t = {1,2,3,4,5,8}
s = {2,3,5}
s.issubset (t) #check if every element of s is in t
Set: #issupersetset()
s.issuperset(t) - returns True if
all element in s is present in t t = {1,2,3,4,5,8}
s = {2,3,5}
t.issuperset(s) #checks if every element in t is in s
Set: a = {1,5,6,8,9}
print(a)
#set -a

a.union(b) - returns all the b = {5,8,9,7,10} #set -b


elements from both the sets. print(b)
a.union(b) #union on set a and b
Set: a = {1,5,6,8,9}
print(a)
#set -a

a.intersection(b) - returns the b = {5,8,9,7,10} #set -b


common element from bot the print(b)
sets. a.intersection(b) #intersection on set a and b
Set: a = {1,5,6,8,9}
print(a)
#set -a

a.difference(b) - returns the b = {5,8,9,7,10} #set -b


elements from set a that are print(b)
not there in set b. a.difference(b) #you will get element from set a that are not
there in set b
Set: a = {1,5,6,8,9}
print(a)
#set -a

a.symmetric_difference(b) - b = {5,8,9,7,10} #set -b


returns the elements from set print(b)
a and b that are not common. a.symmetric_difference(b) #returns new set with elements
either in s or t but not in both
Set: a = {1,2,3,4,5,8}
b = {10,12}
update()- updates the items in a.update(b) #updates set a with items of set b
current set by adding items in print(a)
another set.
Set: a = {1,2,3,4,5,8}
print(a)
remove()- removes specified a.remove(2) #removes 2 from set a
element from the set. print(a)
Set: a = {1,2,3,4,5,8}
print(a)
discard()- removes specified a.discard(2) #removes 2 from set a
element from the lists. print(a)
Set: a = {2,9,8,7,5}
print(a)
clear()- removes all elements a.clear() #removes all the element from a
from set. print(a)
Set: a = {2,9,8,7,5}
print(a) #deletes the set a
del()- deletes the set. del a
print(a)
Set: s = {1,2,3,4,5,8}
t = {2,3,5}
s.intersection_update(t)- print(s)
return set s with only the s.intersection_update(t) #return set s with only the elements
elements in t in t
print(s)
Set: s = {1,2,3,4,5,8}
t = {2,3,5}
s.difference_update(t)- return print(s)
set s with only the elements in s.difference_update(t) #return set s with only the elements
t not present in t
print(s)
Set: s = {1,2,3,4,5,8}
t = {2,3,5}
s.symmetric_difference_update(t)- print(s)
return set s with only the elements in s.symmetric_difference_update(t) #return set s with the
t elements from s or t but not both
print(s)
Set:
frozenset(t)- it makes the iterable
immutable.
Dictionary
Syntax to create dictionary
a = dict() #creates empty dictionary a
print(a)
dct = {'Name' : 'Rahul','Age':12,'Class' : 12}
#creates a dictionary with the key and the value
pair

Dictionary print(dct)

● Dictionaries are mutable unordered collections written with curly


braces

● Data is stored in key and value pair.

● The keys must be unique and should be hashable.


We can access the item of the dictionary by referring

Accessing to its key name inside square bracket.

a = dict() #creates empty dictionary a

Items: dct = {'Name' : 'Rahul','Age':18,'Class' : 12}


dct['Name'] #returns value associated with the
key-'Name'
Dictionary Methods
Dictionary: car = {"brand": "Ford",
"model": "Mustang",
clear() - removes all the item form "year": 1964}
the dictionary. print(car)
car.clear() #removes all the elements from the car
print(car)
Dictionary: car = {"brand": "Ford",
"model": "Mustang",
copy() - return a copy of the specified "year": 1964
dict. }
print(car)
new_c = car.copy() #creates a copy of car
print(new_c)
Dictionary: car = {"brand": "Ford",
"model": "Mustang",
items() - returns an iterable list of "year": 1964
(key,value) tuples }
car.items() #return an iterable list of (key,value) tuples
Dictionary: car = {"brand": "Ford",
"model": "Mustang",
keys() - returns an iterable of all the "year": 1964
keys from the dictionary }
car.keys() #return an iterable of all keys in car
Dictionary: car = {"brand": "Ford",
"model": "Mustang",
Values() - returns an iterable of all "year": 1964
the values from the dictionary }
car.values() #return an iterable of all keys in car
Dictionary: car = {"brand": "Ford",
"model": "Mustang",
"year": 1964}
popitem() - removes the last element
entered in the dictionary and returns print(car)
it a = car.popitem() #removes ('year', 1964) from car and store
it in a
print(car)
print(a)
Dictionary:
pop() - removes the specified
element from the dictionary and
returns it.
car = {"brand": "Ford",
"model": "Mustang",

Dictionary: "year": 1964}


x = car.setdefault('model', 'Bronco')
the key is not present return 'Bronco'
#returns "Mustang" if

setdefault() - returns the value of the


item specified. If the item is not print(x)
present it return the default value y = car.setdefault('place','India') #returns "India" as the
that we set. key "place" is not in car
print(y)
print(car)
car = {"brand": "Ford",

Dictionary: "model": "Mustang",


"year": 1964}
print(car)
update() - adds the specified item to
the dictionary. car.update({'Color' : 'black'}) #updates the car with new sets
of key value pair
print(car)
Dictionary:
dict.fromkeys() - creates a dictionary
from the elements of the iterable.
Conditional Statements
Conditional Statements in python performs different computations or actions
depending on whether a specific boolean constraint evaluates to True of False.
Syntax

If <expression> :
statement-1
If statement-2
…………….

Statements: statement-n

a = 15
if a > 10 :
Conditional Statements are handled print("A is greater than 10")
by if statement in python. It is used
for making decisions.
Syntax

If <expression> : When expression


evaluates to True then if
statement
block is executed else
else :
If- else statement
the control is transferred
to else block

Statements: a = 15
if a > 10 :
print("A is greater than 10")
else:
print("A is less than 10")
If- else
Statement
flowchart
Syntax

If <expression> :
statement
elif <expression> :
statement
If- elif elif <expression> :
statement

Statements: else:
statement

num = 10
if (num==0):
print("Number is 0")
elif (num > 5):
print("Number is greater than 5")
else:
print("Number is less than 5")
Nested IF
condition
Loops
Syntax

While Loop first checks


the condition. The loop
while <condition>: will execute unless the

While statement condition becomes


False.

Loop:
a = 1
while a < 10:
print(a)
a +=1
Syntax

A for loop is used for


iterating over a sequence
for var in <iterable>: (that is either a list, a tuple,
a dictionary, a set, or a
For statement string)

Loop:
lst = [10,20,30,40,50]
for var in lst:
print(var)
range() function generates
the integer numbers
between the start number
and end number

range(): range() function is mostly


used with for loops

for var in range(10,20):


print(var)
break is used for the

break: premature termination of


the loop.
continue is used to end the

continue: current iteration in a loop


and continue from next
iteration.
pass it is used when a

pass: statement is required


syntactically but you do not
want any command to
execute
assert

assert:
Functions
To define a Data to pass in
Name of the function
function
function
Syntax

Colon to mark the


def functionname(arguments): end of function

Functions: ‘ ‘ ‘docstring’ ’ ’
statements
header

● A function is a group of related return value


statements that performs a
specific task.
● Functions helps break our code
Documentation string to
into smaller & modular chunks. mark what the function
Set of statements - all the
● In python a function is defined statements within function does(optional)
using a def keyword. must have the same
indentation level

Return - Returns a value


from the function
def add(a,b):
''' Function to Add two Numbers
Arguments:
a : First number
b : Second number '''

Function print(a + b)
#a function executes when it is called we

Example: call a function using the function name.


add(10,20)
● The return statement is used to return
some value from the function when it is
called.
● When a return statement is not present
in a function the returned value is None

Functions: def add(a,b):


''' Function to Add two Numbers
return Arguments:

statement a : First number


b : Second number
Return:
Returns sum of a and b'''
sum = a + b
return sum

addition = add(50,60)
print(addition)
Functions:
parameters / arguments
● Positional arguments
● Keyword arguments
● Default arguments
● Variable length arguments
● Keyword variable length arguments
Functions: def greet(name,message):
''' A Function to greet a person
Positional arguments with message'''
print(name + " " + message)
Positional arguments are the
arguments that need to be greet('Monica','good morning')
included in the proper
position or order.
def grocery(item,price):
'''Function with two keyword arguments
'item','price'

Functions: '''
print(f'Price: {price}')
Keyword arguments print(f'Item name : {item}')

Keyword arguments are the #call the function and pass the keyword arguments
arguments that identifies the value
arguments by their name.
grocery(item='Soap',price=44)
def grocery(item,price=50.5):
'''Function with default
'''

Functions: print(f'Price: {price}')


print(f'Item name : {item}')
Default arguments
#call the function and pass the value for
default arguments are used parameter item
to set the default value for grocery(item='Soap')
the arguments.
Functions: def my_sum(*args):
''' Variable length arguments'''
Variable length return sum(args)
arguments
my_sum(10,20,30)
variable length arguments
can accept n number of
arguments. It is written with
a “*” symbol (*args).
Functions:
Keyword Variable
length arguments
Keyword variable length
arguments can accept n
number of arguments
provided in key value pair. It
is written with a “**” symbol
(*kargs).
Global and Local
Variables
x = "Gloabl scope variable" #declare a global scope variable
def foo():
'''A function that uses global variable'''

Functions: print(x)
foo() #call the function
Global variable
If we change the value of x inside the function it will throw an error. We have to
use global keyword while declaring variable x, if we want to change the value
A variable declared outside inside the function
of a function or in global
scope is known as global x = 10
variable. Global variables can
def add5():
be accessed inside and
outside of a function. global x
x = x + 5
print(x)
add5(10)
def local_example():
''' Example of local variable'''
x = "Hello"
print(x)
local_example()

Functions: If you try to access a local variable outside


a function body it will throw an error.

Local variable
The variables declared inside
a function body are known
as local variables.
Local variables cannot be
accessed outside a function
body.
def display(name): #main function

Functions:
''' Function inside a function to greet'''
def message(): #function inside a function
return "Good Morning!"
Function inside result = message () + ' ' + name
another function return result

display('Manvendra')
def display(name,func):

Functions: '''A function that accepts


another function as argument'''
return name + ' ' + func
Function as a
def message():
parameter to another
return 'Good Morning!'
function.
display('Manvendra',message())
Functions: def display():
def message():
A function can return return "Good morning"
another function. return message()
display()
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1

Recursion: else:
return (x * factorial(x-1))
When a function calls factorial(3)
itself over and over again
it is known as recursion. #factorial(3) # 1st call with 3
#3 * factorial(2) # 2nd call with 2
#3 * 2 * factorial(1) # 3rd call with 1
#3 * 2 * 1 # return from 3rd call as number=1
#3 * 2 # return from 2nd call
#6 # return from 1st call
Anonymous Function :
Lambda
● An anonymous function is a function which has no
name.
● Normal functions are defined using def keyword,
while lambda functions are defined using lambda
keyword.
● Lambda function can have any number of argument
Lambda: but only 1 expression

An anonymous function
is a function which has Syntax
no name.
lambda arguments : expression

double = lambda x : x*2


print(double(5))
Use of Lambda :
With map() & filter()
Lambda with lst = [1,2,3,4,5,6,7,8,9,10]
#filter out only even values from a list

filter(): new_lst = list(filter(lambda x : (x%2 == 0),lst))


print(new_lst)
The filter function in python takes a
function and a list as arguments.
Lambda with lst = [1,2,3,4,5,6,7,8,9,10]
#program to square each element in the list using

map(): map()
new_lst = list(map(lambda x : x**2,lst))
The map() function is similar to the
print(new_lst)
filter() function but acts on each
element and perhaps changes that
element.
List Comprehension
List Comprehension
Iterating through a loop using for loop.

● Lists can be built by leveraging any iterable h_letters = []


strings,tuples. for letter in 'human':
● List comprehension consists of an iterable containing h_letters.append(letter)
an expression followed by for clause
print(h_letters)

Iterating through a loop using list


Conditionals in list comprehension
comprehension
lst = [x for x in range(10) if x%2==0] h_letters = [x for x in 'human']
print(lst) print(h_letters)
Dict
Comprehension
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# Double each value in the dictionary
double_dict1 = {k:v*2 for (k,v) in dict1.items()}
print(double_dict1)

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f':6}

# Identify odd and even entries


dict1_tripleCond = {k:('even' if v%2==0 else 'odd') for (k,v) in dict1.items()}

print(dict1_tripleCond)
Generators
# A simple generator function
def my_gen():
n = 1
print('This is printed first')
# Generator function contains yield statements
yield n

Generators: n += 1
print('This is printed second')
Generators are iterators, a kind yield n
of iterators you can only iterate
over once. n += 1
It is created like ordinary
print('This is printed at last')
function but uses yield keyword
instead of return. yield n

# Using for loop


for item in my_gen():
print(item)
Modules
A module is a piece of software that
has specific functionalities.

Modules in python are just simply


python files with .py extension.

The name of the module will be the


name of the file.

A module can have a set of functions,


or variables defined and
implemented.
Modules: mymodule.py

Save python file as module. def greeting(name,message):


return name + ‘ ’ + message
To save a python file as module you just
have to save the file with .py extension
import modulename
import mymodule
mymodule.greet(“Manvendra”,
“Hello”)

from mymodule import greet

Modules: from mymodule import greet


greet(“Manvendra”, “Hello”)
Importing and using module
functionality in another file.

We have to import the file first using from mymodule import greet as gt
import and then use the functionality.
from mymodule import greet as gt
There are different ways to import gt(“Manvendra”, “Hello”)
module.

from mymodule import *


dir() - it is used to show all the functions in a
from mymodule import *
module. mymodule.greet(“Manvendra”,
“Hello”)
mymodule.py

def greeting(name,message):
return name + ‘ ’ + message
Modules: Person = {‘Name’ : ‘Manvendra’,
‘Age’ : 23, ‘Company’ : ‘Codegnan’ }
Variables in Modules

A module can have functions as well as


variables and we can access them in new.py
different files as well.
import mymodule
a = mymodule.person[‘Name’]
Packages
Packages:
● Packages allow for a hierarchical
structuring of the modules
namespace using dot notation.
● Creating a package and using them
is pretty straightforward in python
as it uses inherent hierarchical file import packagename.modulename
structure of operating system.
File Operations
Files:
● Files are named locations on disk to
store related information.

● A file is used to permanently store In Python a file operation takes place in


data in a volatile memory. following order :

● When we want to read from a file or 1. Open a file


2. Read or write (perform operation)
write to a file we need to open it first. 3. Close the file
● When we are done it needs to be
closed to free the resources.
Files: # open file in current directory
Opening files in python f = open(‘filename.extension’)

Python has a built in open() function #specifying full path


to open a file. f = open(r‘c:/python/test.txt’)

This function returns a file object also


called as handle.

We can also specify the mode while opening a


file.
Files: This is not the safe way to close a file. If an exception
Closing files in python happens when we are performing some action with
the file. The code exits without closing the file. A safer
close () is used to close an opened file way is to try..finally block.
and free the resources associated with
it.
Different modes and descriptions to
open a file.
● r mode - Read mode. Only open the file for reading.
● w mode - Write mode only opens the file for writing.
● a mode - Opens the file in append mode. Used to append
information in file. We can perform only write operation after
opening the file in append mode.
● r+ mode - Performs read as well as write operation.
● w+ mode - Performs write as well as read operation
● a+ mode - Opens the file in append mode. In a+ mode we can
perform both read and write operation without overwriting the file
data.
By default the file is opened in read mode. We can also specify the mode in which we want to
open the file here ‘r’ means open the file for reading. We use open function to open a file.

We are opening the files and have created fp object to store the file content. We won’t see the file
contents if we print fp.
There are 3 different functions to read the file
contents :-

1. fp.read() - reads all the content of the file.


We can also specify the number of
characters we want to read.
2. fp.readline() - reads the file content line by
line. We can specify number of characters
to read from the line.
3. fp.readlines() - reads all the line and gives
back a list of all the lines in the file.
Opening File in Write Mode

● We can open file in write mode by specifying the mode


as ‘w’. If we open a file in write mode it will create a file
if the file is not present.

● If we open a file in write mode it overwrites everything


that is present in file.

● In write mode we cannot perform the read operations. It


will throw error if we try to perform read operations. We
can only perform the write operation if we open file in
write mode.
In write mode we can only perform the write operation. Trying to read anything will give us error.
Opening File in Append Mode

● In append mode we can append the contents in the file it


won’t overwrite the contents of the file. Will add the
contents at the end of the file.

● In append mode we can only perform the write operation


not the read operation.

● It will also create the file if the file is not present.


In r+ mode we can perform both read and write operations.

fp.tell() - It tells the file pointer position.


fp.seek(offset,whence) - offset is how many characters to move and whence values can be 0,1,and 2.

0 means move to 0th position, 1 means maintain the current position and 2 means move at the end.
In w+ mode also it overwrites everything in the file. We can perform both read and write
operations .
In a+ mode it appends the content to the file. It does not overwrites the content of the file.
We can perform the read and write operations when file opened in append mode.
Errors and Exceptions in
Python
Syntax Error :
When proper syntax of language is not
followed a syntax error is thrown.

Errors:
Errors are the problem in the lst = [10,20,30,40,50] We can solve a
code that will stop the execution for i in lst syntax error by
of the program. print(i) writing the correct
syntax.
Types of errors in python -
● Syntax errors
● Logical error(Exceptions) A syntax error is thrown.
Exceptions:
Exceptions are raised when some
internal error occur which A = 100
changes the normal flow of the Mark = A/0
program. # when we divide any number by 0 ZeroDivisionError
exception is raised.

Types of errors in python -


● Syntax errors
● Logical error(Exceptions)
Python Exception
Handling
try :
The try block let’s us test a block of codes for
error.
Exception Handling:
When an error occurs / exception python will
normally stop and generate an error message.
except :
The except blocks let’s us handle the error.
These errors can be handled using try, except
and finally blocks.
finally :
The final block let’s us execute the code
regardless of the try and except block.
Example
We have not defined x. So an error will be
thrown. Without except block this code will
throw an error.

As an error is thrown by try block, except


block is executed.
We can write many
exception blocks
Finally Block:
The finally block if specified will be
executed regardless if try block throws
an error or not
Math Module

To check builtin functions - print(dir(__builtins__))


The Math module provides the
mathematical functions in python
l = [0.1] * 10
print(l)
print(sum(l))
l = [0.1] * 10
print(l)
print(math.fsum(l)) The sum of this operation will not result
in 1. We can use math module for
This will yield the result of 1. mathematical operations.
math.floor(15.5995) This will give the integral part as output

math.ceil(15.5995) It will round off the value to nearest biggest integral.

math.sqrt(25) Gives the sqrt of 25

math.factorial(5) The output will be the factorial of 5

The output of modf will result in a tuple where the first element will be the
math.modf(5)
decimal value and the other will be the integral part.

math.pow(10,2) The output will be 10 raise to power 2.

math.log(10) The result will be the log of 10


Random Module
The random module is a builtin module in python. It generates pseudo
random variables.

random.random() Generates a random number between 0.0 and 1.0

random.randint(10,100) Gives a random number between 10 and 100

random.randrange(10,100) Gives a random number between 0 and 100 it does not includes
the endpoint.

random.uniform(10,100) Gives a random number between 0 and 100 .

random.choice(seq) Randomly chooses 3 values from the list.


sys Module
Sys module is builtin module in python. It provides several functions and variables to
manipulate the python runtime environment.

import sys
print(‘hello world’) The program will exit after printing the hello world and will not print
sys.exit() the bye world
print(‘bye world’)

sys.path Gives the path of python executable.

sys.platform Gives the os name

sys.executable Specifies the path of python executable file

sys.modules Returns list of all available modules

sys.copyright() Gives the copyright of python

sys.argv() Gives list of command line arguments


OS Module
The os module in python provides the functions for interacting with the operating system.

os.getcwd() Gives the current working directory.

os.chdir(‘path’) Change the working directory.

os.listdir(‘path’) Gives list of all the files in the path.

os.mdir() For making a directory.

os.makedirs() For making a directory in the sub directory.

os.rename() For renaming directory

os.path.exists(‘file.txt’) For checking if the file exists or not

os.path.isdir(dirname) For checking if the directory exists or not


os.rmdir() Removing the directory

os.removedirs() For removing subdirectories as well.

os.stat(‘file.txt’) For removing subdirectories as well.

You might also like