SlideShare a Scribd company logo
1 of 23
Python Programming
Part V
Megha V
Research Scholar
Kannur University
09-11-2021 meghav@kannuruniv.ac.in 1
Anonymous Functions
• Anonymous function is a function that is defined without a name.
• Anonymous function is defined using the lambda keyword
• Also called lambda functions
syntax
lambda [,arg1 [,arg2,……….argn]]:expression
Eg: # Lambda function definition
square=lambda x : x*x;
# Usage of lambda function
n=int(input(“Enter a number:”))
print(“square of”,n,”is”,square(n)) #
Output
Enter a number:5
Square of 5 is 25
09-11-2021 meghav@kannuruniv.ac.in 2
Main characteristics of lambda function
1. Lambda functions can take any number of arguments but return only one
value in the form of an expression
2. It cannot contain multiple expressions
3. It cannot have comments
4. A lambda function cannot be a direct call to print because lambda requires
an expression
5. Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the global
namespace
6. Lambda functions are not equivalent to inline functions in C or C++
09-11-2021 meghav@kannuruniv.ac.in 3
• lambda is the keyword, x shows the argument passed, and x*x is the
expression to be evaluated and stored in the variable square
Example with two arguments
# Lambda function definition
sum =lambda x,y : x+y
#usage of lambda function
m=int(input(“Enter first number:”))
n=int(input(“Enter second number:”))
print(“sum of”,m,”and”,n,”is”,sum(m,n))#lambda function call
09-11-2021 meghav@kannuruniv.ac.in 4
Use of lambda function
• We use lambda function when we require a nameless function for a
short period of time.
• Lambda functions are used along with built-in functions like filter(),
map() etc
• The map() function in Python takes input; function and a list.
• The function is called with all the item in the list and a new list is
returned which contains items returned by that function for each
item
09-11-2021 meghav@kannuruniv.ac.in 5
#Lambda function to increment the items in list by 2
oldlist=[2,31,42,11,6,5,23,44]
print(oldlist)
#Usage of lambda function
newlist=list(map(lambda x: x+2,oldlist))
print(“List after incrementation by 2”)
print(newlist)
Output
[2,31,42,11,6,5,23,44]
List after incrementation by 2
[4,33,44,13,8,7,25,46]
lambda function
09-11-2021 meghav@kannuruniv.ac.in 6
• filter() function
• The function filter(function,list) offers a way to filter out all the elements
of a list, for which the function returns True.
• The first argument function returns a Boolean value, i.e., either True or
False.
• This function will be applied to every element of the list lis.
09-11-2021 meghav@kannuruniv.ac.in 7
Example: The function called with all the items in the list and a new list is returned
which contains items for which the function evaluates to True
#Lambda function to filter out only odd numbers from a
list
oldlist=[2,31,42,11,6,5,23,44]
newlist=list(filter(lambda x:(x%2!=0),oldlist))
print(oldlist)
print(newlist)
Output
[2,31,42,11,6,5,23,44]
[31,11,5,23]
09-11-2021 meghav@kannuruniv.ac.in 8
reduce() function
• The function reduce(func,seq) continually applies the fuction func() to the
sequence seq.
• It returns a single value
• If seq=[s1,s2, s3…………….sn], calling reduce(func,seq) work like this:
• At first the two elements of seq will be applied to func, i.e func(s1,s2)
• The list on which reduce() works looks now like this: [func(s1,s2),s3………sn]
• In the next step func will be applied on the previous result and the third
element of the list, i.e. func(func(s1,s2),s3)
• The list looks like this now: [func(func(s1,s2),s3),………,sn]
09-11-2021 meghav@kannuruniv.ac.in 9
• Continue like this until just one element is left and return this element as the
result of reduce()
• Used for performing some computation on list and returning the result.
• The following example illustrates the use of reduce() function, that computes
the product of a list of integers
• Example:
import functools
list=[1,2,3,4]
product=functools.reduce[lambda x,y:x*y,list]
print(list)
print(“Product=” product)
Output
[1,2,3,4]
product=24
09-11-2021 meghav@kannuruniv.ac.in 10
Function with more than one return type
• Instead of writing separate functions for returning individual values, we can return all the values withing
same function
• Example: def cal(a,b)
sum=a+b
diff=a-b
prod=a*b
quotient=a/b
return sum,diff,prod,quotient
a=int(input(“Enter first number:”))
b=int(input(“Enter second number:”))
s,d,p,q=calc(a,b)
print(“Sum=”,s)
print(“Difference=”,d)
print(“Product=”,p)
print(“Quotient=”,q)
Output
Enter first number:10
Enter Second number:5
Sum=15
Difference=5
Product=50
Quotient=5
09-11-2021 meghav@kannuruniv.ac.in 11
Strings
• Python allows several string operators that can be applied on the python
string are as below:
1. Assignment operator: “=.”
2. Concatenate operator: “+.”
3. String repetition operator: “*.”
4. String slicing operator: “[]”
5. String comparison operator: “==” & “!=”
6. Membership operator: “in” & “not in”
7. Escape sequence operator: “.”
8. String formatting operator: “%” & “{}”
09-11-2021 meghav@kannuruniv.ac.in 12
Basic String operations
• Assignment operator: “=.”
string1 = "hello“
• Concatenate operator: “+.”
string1 = "hello"
string2 = "world "
string_combined = string1+string2
print(string_combined)
• String repetition operator: “*.”
string1 = "helloworld "
print(string1*2)
09-11-2021 meghav@kannuruniv.ac.in 13
Basic String operations
string1 = "helloworld"
print(string1[1])
print(string1[-3])
print(string1[1:5])
print(string1[1:-3])
print(string1[2:])
print(string1[:5])
print(string1[:-2])
print(string1[-2:])
print(string1[::-1])
• String slicing operator: “[]”
09-11-2021 meghav@kannuruniv.ac.in 14
Basic String operations
String comparison operator: “==” & “!=”
string1 = "hello"
string2 = "hello, world"
string3 = "hello, world"
string4 = "world"
print(string1==string4) #False
print(string2==string3) #True
print(string1!=string4) #True
Membership operator: “in” & “not in”
string1 = "helloworld"
print("w" in string1) #True
print("W" in string1) #False
print("t" in string1) #False
print("t" not in string1) #True
print("hello" in string1) #True
print("Hello" in string1) #False
09-11-2021 meghav@kannuruniv.ac.in 15
Basic String operations
• EscapeSequence Operator“.”
• To inserta non-allowedcharacterin thegiveninput string,an escapecharacterisused.
• An escapecharacterisa “” or “backslash”operatorfollowedby a non-allowedcharacter.
string = "Hello world I am from "India""
print(string) #ERROR
string = "Hello world I am from "India""
print(string)
Output
Hello world I am from “India”
09-11-2021 meghav@kannuruniv.ac.in 16
• Escape characters
• An escape character is a character that gets interpreted when placed
in single or double quotes
Escape character Description
a Bell or alert
b Backspace
f Formfeed
n Newline
r Carriage return
s Space
t Tab
v Vertical Tab
09-11-2021 meghav@kannuruniv.ac.in 17
Basic String operations
• String formatting operator: “%” & “{}”
• String formatting operator is used to format a string as per requirement
name = "india"
age = 19
marks = 20.56
string1 = 'Hey %s' % (name)
print(string1)
string2 = 'my age is %d' % (age)
print(string2)
string3= 'Hey %s, my age is %d' % (name, age)
print(string3)
string3= 'Hey %s, my subject mark is %f' % (name, marks)
print(string3)
Operator Description
%d Signed decimal integer
%u unsigned decimal integer
%c Character
%s String
%f Floating-point real number
09-11-2021 meghav@kannuruniv.ac.in 18
Strings
• Python has a set of built-in methods that you can use on strings.
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
09-11-2021 meghav@kannuruniv.ac.in 19
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
09-11-2021 meghav@kannuruniv.ac.in 20
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
09-11-2021 meghav@kannuruniv.ac.in 21
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice
versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at
the beginning
09-11-2021 meghav@kannuruniv.ac.in 22
Example
s=‘Learning Python is easy’
print(s.lower())
print(s.title())
print(s.upper())
print(s.swapcase())
print(s.capitalize())
09-11-2021 meghav@kannuruniv.ac.in 23

More Related Content

What's hot

Python Lambda Function
Python Lambda FunctionPython Lambda Function
Python Lambda FunctionMd Soyaib
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functionsHarsh Patel
 
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...cprogrammings
 
Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2MOHIT TOMAR
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonPriyankaC44
 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaEdureka!
 
Classes,object and methods java
Classes,object and methods javaClasses,object and methods java
Classes,object and methods javaPadma Kannan
 
What is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | EdurekaWhat is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | EdurekaEdureka!
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control StructureSokngim Sa
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++Shyam Gupta
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT03062679929
 

What's hot (20)

Python Lambda Function
Python Lambda FunctionPython Lambda Function
Python Lambda Function
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
 
Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in Python
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | Edureka
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Python set
Python setPython set
Python set
 
Classes,object and methods java
Classes,object and methods javaClasses,object and methods java
Classes,object and methods java
 
What is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | EdurekaWhat is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | Edureka
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
Inline function
Inline functionInline function
Inline function
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Python Intro
Python IntroPython Intro
Python Intro
 
Python strings
Python stringsPython strings
Python strings
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Python-Polymorphism.pptx
Python-Polymorphism.pptxPython-Polymorphism.pptx
Python-Polymorphism.pptx
 
Function in C
Function in CFunction in C
Function in C
 

Similar to Python programming: Anonymous functions, String operations

Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptAnishaJ7
 
A brief introduction to apply functions
A brief introduction to apply functionsA brief introduction to apply functions
A brief introduction to apply functionsNIKET CHAURASIA
 
Python functions part12
Python functions  part12Python functions  part12
Python functions part12Vishal Dutt
 
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry PiRaspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry PiMohamed Abdallah
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala Knoldus Inc.
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming languageMegha V
 
Diploma ii cfpc u-4 function, storage class and array and strings
Diploma ii  cfpc u-4 function, storage class and array and stringsDiploma ii  cfpc u-4 function, storage class and array and strings
Diploma ii cfpc u-4 function, storage class and array and stringsRai University
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab FunctionsUmer Azeem
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshopBAINIDA
 
PYTHON-PROGRAMMING-UNIT-II (1).pptx
PYTHON-PROGRAMMING-UNIT-II (1).pptxPYTHON-PROGRAMMING-UNIT-II (1).pptx
PYTHON-PROGRAMMING-UNIT-II (1).pptxgeorgejustymirobi1
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdfsimenehanmut
 
Bsc cs i pic u-4 function, storage class and array and strings
Bsc cs i pic u-4 function, storage class and array and stringsBsc cs i pic u-4 function, storage class and array and strings
Bsc cs i pic u-4 function, storage class and array and stringsRai University
 
Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Guy Lebanon
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4Saranya saran
 

Similar to Python programming: Anonymous functions, String operations (20)

Functions.docx
Functions.docxFunctions.docx
Functions.docx
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.ppt
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
A brief introduction to apply functions
A brief introduction to apply functionsA brief introduction to apply functions
A brief introduction to apply functions
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
R Functions.pptx
R Functions.pptxR Functions.pptx
R Functions.pptx
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
 
Python functions part12
Python functions  part12Python functions  part12
Python functions part12
 
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry PiRaspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry Pi
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
 
Diploma ii cfpc u-4 function, storage class and array and strings
Diploma ii  cfpc u-4 function, storage class and array and stringsDiploma ii  cfpc u-4 function, storage class and array and strings
Diploma ii cfpc u-4 function, storage class and array and strings
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab Functions
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
PYTHON-PROGRAMMING-UNIT-II (1).pptx
PYTHON-PROGRAMMING-UNIT-II (1).pptxPYTHON-PROGRAMMING-UNIT-II (1).pptx
PYTHON-PROGRAMMING-UNIT-II (1).pptx
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdf
 
Bsc cs i pic u-4 function, storage class and array and strings
Bsc cs i pic u-4 function, storage class and array and stringsBsc cs i pic u-4 function, storage class and array and strings
Bsc cs i pic u-4 function, storage class and array and strings
 
Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Data Analysis with R (combined slides)
Data Analysis with R (combined slides)
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 

More from Megha V

Soft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptxSoft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptxMegha V
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxMegha V
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptMegha V
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception HandlingMegha V
 
Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expressionMegha V
 
File handling in Python
File handling in PythonFile handling in Python
File handling in PythonMegha V
 
Python programming -Tuple and Set Data type
Python programming -Tuple and Set Data typePython programming -Tuple and Set Data type
Python programming -Tuple and Set Data typeMegha V
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7Megha V
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6Megha V
 
Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Megha V
 
Python programming –part 3
Python programming –part 3Python programming –part 3
Python programming –part 3Megha V
 
Python programming
Python programmingPython programming
Python programmingMegha V
 
Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplicationMegha V
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrencesMegha V
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm AnalysisMegha V
 
Algorithm analysis and design
Algorithm analysis and designAlgorithm analysis and design
Algorithm analysis and designMegha V
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithmMegha V
 
UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data  UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data Megha V
 
Seminar presentation on OpenGL
Seminar presentation on OpenGLSeminar presentation on OpenGL
Seminar presentation on OpenGLMegha V
 
Msc project_CDS Automation
Msc project_CDS AutomationMsc project_CDS Automation
Msc project_CDS AutomationMegha V
 

More from Megha V (20)

Soft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptxSoft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptx
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptx
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
 
Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expression
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Python programming -Tuple and Set Data type
Python programming -Tuple and Set Data typePython programming -Tuple and Set Data type
Python programming -Tuple and Set Data type
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6
 
Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)
 
Python programming –part 3
Python programming –part 3Python programming –part 3
Python programming –part 3
 
Python programming
Python programmingPython programming
Python programming
 
Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplication
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrences
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm Analysis
 
Algorithm analysis and design
Algorithm analysis and designAlgorithm analysis and design
Algorithm analysis and design
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithm
 
UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data  UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data
 
Seminar presentation on OpenGL
Seminar presentation on OpenGLSeminar presentation on OpenGL
Seminar presentation on OpenGL
 
Msc project_CDS Automation
Msc project_CDS AutomationMsc project_CDS Automation
Msc project_CDS Automation
 

Recently uploaded

Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 

Recently uploaded (20)

Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 

Python programming: Anonymous functions, String operations

  • 1. Python Programming Part V Megha V Research Scholar Kannur University 09-11-2021 meghav@kannuruniv.ac.in 1
  • 2. Anonymous Functions • Anonymous function is a function that is defined without a name. • Anonymous function is defined using the lambda keyword • Also called lambda functions syntax lambda [,arg1 [,arg2,……….argn]]:expression Eg: # Lambda function definition square=lambda x : x*x; # Usage of lambda function n=int(input(“Enter a number:”)) print(“square of”,n,”is”,square(n)) # Output Enter a number:5 Square of 5 is 25 09-11-2021 meghav@kannuruniv.ac.in 2
  • 3. Main characteristics of lambda function 1. Lambda functions can take any number of arguments but return only one value in the form of an expression 2. It cannot contain multiple expressions 3. It cannot have comments 4. A lambda function cannot be a direct call to print because lambda requires an expression 5. Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace 6. Lambda functions are not equivalent to inline functions in C or C++ 09-11-2021 meghav@kannuruniv.ac.in 3
  • 4. • lambda is the keyword, x shows the argument passed, and x*x is the expression to be evaluated and stored in the variable square Example with two arguments # Lambda function definition sum =lambda x,y : x+y #usage of lambda function m=int(input(“Enter first number:”)) n=int(input(“Enter second number:”)) print(“sum of”,m,”and”,n,”is”,sum(m,n))#lambda function call 09-11-2021 meghav@kannuruniv.ac.in 4
  • 5. Use of lambda function • We use lambda function when we require a nameless function for a short period of time. • Lambda functions are used along with built-in functions like filter(), map() etc • The map() function in Python takes input; function and a list. • The function is called with all the item in the list and a new list is returned which contains items returned by that function for each item 09-11-2021 meghav@kannuruniv.ac.in 5
  • 6. #Lambda function to increment the items in list by 2 oldlist=[2,31,42,11,6,5,23,44] print(oldlist) #Usage of lambda function newlist=list(map(lambda x: x+2,oldlist)) print(“List after incrementation by 2”) print(newlist) Output [2,31,42,11,6,5,23,44] List after incrementation by 2 [4,33,44,13,8,7,25,46] lambda function 09-11-2021 meghav@kannuruniv.ac.in 6
  • 7. • filter() function • The function filter(function,list) offers a way to filter out all the elements of a list, for which the function returns True. • The first argument function returns a Boolean value, i.e., either True or False. • This function will be applied to every element of the list lis. 09-11-2021 meghav@kannuruniv.ac.in 7
  • 8. Example: The function called with all the items in the list and a new list is returned which contains items for which the function evaluates to True #Lambda function to filter out only odd numbers from a list oldlist=[2,31,42,11,6,5,23,44] newlist=list(filter(lambda x:(x%2!=0),oldlist)) print(oldlist) print(newlist) Output [2,31,42,11,6,5,23,44] [31,11,5,23] 09-11-2021 meghav@kannuruniv.ac.in 8
  • 9. reduce() function • The function reduce(func,seq) continually applies the fuction func() to the sequence seq. • It returns a single value • If seq=[s1,s2, s3…………….sn], calling reduce(func,seq) work like this: • At first the two elements of seq will be applied to func, i.e func(s1,s2) • The list on which reduce() works looks now like this: [func(s1,s2),s3………sn] • In the next step func will be applied on the previous result and the third element of the list, i.e. func(func(s1,s2),s3) • The list looks like this now: [func(func(s1,s2),s3),………,sn] 09-11-2021 meghav@kannuruniv.ac.in 9
  • 10. • Continue like this until just one element is left and return this element as the result of reduce() • Used for performing some computation on list and returning the result. • The following example illustrates the use of reduce() function, that computes the product of a list of integers • Example: import functools list=[1,2,3,4] product=functools.reduce[lambda x,y:x*y,list] print(list) print(“Product=” product) Output [1,2,3,4] product=24 09-11-2021 meghav@kannuruniv.ac.in 10
  • 11. Function with more than one return type • Instead of writing separate functions for returning individual values, we can return all the values withing same function • Example: def cal(a,b) sum=a+b diff=a-b prod=a*b quotient=a/b return sum,diff,prod,quotient a=int(input(“Enter first number:”)) b=int(input(“Enter second number:”)) s,d,p,q=calc(a,b) print(“Sum=”,s) print(“Difference=”,d) print(“Product=”,p) print(“Quotient=”,q) Output Enter first number:10 Enter Second number:5 Sum=15 Difference=5 Product=50 Quotient=5 09-11-2021 meghav@kannuruniv.ac.in 11
  • 12. Strings • Python allows several string operators that can be applied on the python string are as below: 1. Assignment operator: “=.” 2. Concatenate operator: “+.” 3. String repetition operator: “*.” 4. String slicing operator: “[]” 5. String comparison operator: “==” & “!=” 6. Membership operator: “in” & “not in” 7. Escape sequence operator: “.” 8. String formatting operator: “%” & “{}” 09-11-2021 meghav@kannuruniv.ac.in 12
  • 13. Basic String operations • Assignment operator: “=.” string1 = "hello“ • Concatenate operator: “+.” string1 = "hello" string2 = "world " string_combined = string1+string2 print(string_combined) • String repetition operator: “*.” string1 = "helloworld " print(string1*2) 09-11-2021 meghav@kannuruniv.ac.in 13
  • 14. Basic String operations string1 = "helloworld" print(string1[1]) print(string1[-3]) print(string1[1:5]) print(string1[1:-3]) print(string1[2:]) print(string1[:5]) print(string1[:-2]) print(string1[-2:]) print(string1[::-1]) • String slicing operator: “[]” 09-11-2021 meghav@kannuruniv.ac.in 14
  • 15. Basic String operations String comparison operator: “==” & “!=” string1 = "hello" string2 = "hello, world" string3 = "hello, world" string4 = "world" print(string1==string4) #False print(string2==string3) #True print(string1!=string4) #True Membership operator: “in” & “not in” string1 = "helloworld" print("w" in string1) #True print("W" in string1) #False print("t" in string1) #False print("t" not in string1) #True print("hello" in string1) #True print("Hello" in string1) #False 09-11-2021 meghav@kannuruniv.ac.in 15
  • 16. Basic String operations • EscapeSequence Operator“.” • To inserta non-allowedcharacterin thegiveninput string,an escapecharacterisused. • An escapecharacterisa “” or “backslash”operatorfollowedby a non-allowedcharacter. string = "Hello world I am from "India"" print(string) #ERROR string = "Hello world I am from "India"" print(string) Output Hello world I am from “India” 09-11-2021 meghav@kannuruniv.ac.in 16
  • 17. • Escape characters • An escape character is a character that gets interpreted when placed in single or double quotes Escape character Description a Bell or alert b Backspace f Formfeed n Newline r Carriage return s Space t Tab v Vertical Tab 09-11-2021 meghav@kannuruniv.ac.in 17
  • 18. Basic String operations • String formatting operator: “%” & “{}” • String formatting operator is used to format a string as per requirement name = "india" age = 19 marks = 20.56 string1 = 'Hey %s' % (name) print(string1) string2 = 'my age is %d' % (age) print(string2) string3= 'Hey %s, my age is %d' % (name, age) print(string3) string3= 'Hey %s, my subject mark is %f' % (name, marks) print(string3) Operator Description %d Signed decimal integer %u unsigned decimal integer %c Character %s String %f Floating-point real number 09-11-2021 meghav@kannuruniv.ac.in 18
  • 19. Strings • Python has a set of built-in methods that you can use on strings. Method Description capitalize() Converts the first character to upper case casefold() Converts string into lower case center() Returns a centered string count() Returns the number of times a specified value occurs in a string encode() Returns an encoded version of the string endswith() Returns true if the string ends with the specified value expandtabs() Sets the tab size of the string find() Searches the string for a specified value and returns the position of where it was found format() Formats specified values in a string format_map() Formats specified values in a string index() Searches the string for a specified value and returns the position of where it was found isalnum() Returns True if all characters in the string are alphanumeric isalpha() Returns True if all characters in the string are in the alphabet isascii() Returns True if all characters in the string are ascii characters 09-11-2021 meghav@kannuruniv.ac.in 19
  • 20. isdecimal() Returns True if all characters in the string are decimals isdigit() Returns True if all characters in the string are digits isidentifier() Returns True if the string is an identifier islower() Returns True if all characters in the string are lower case isnumeric() Returns True if all characters in the string are numeric isprintable() Returns True if all characters in the string are printable isspace() Returns True if all characters in the string are whitespaces istitle() Returns True if the string follows the rules of a title isupper() Returns True if all characters in the string are upper case join() Converts the elements of an iterable into a string ljust() Returns a left justified version of the string lower() Converts a string into lower case 09-11-2021 meghav@kannuruniv.ac.in 20
  • 21. lstrip() Returns a left trim version of the string maketrans() Returns a translation table to be used in translations partition() Returns a tuple where the string is parted into three parts replace() Returns a string where a specified value is replaced with a specified value rfind() Searches the string for a specified value and returns the last position of where it was found rindex() Searches the string for a specified value and returns the last position of where it was found rjust() Returns a right justified version of the string rpartition() Returns a tuple where the string is parted into three parts rsplit() Splits the string at the specified separator, and returns a list rstrip() Returns a right trim version of the string split() Splits the string at the specified separator, and returns a list 09-11-2021 meghav@kannuruniv.ac.in 21
  • 22. splitlines() Splits the string at line breaks and returns a list startswith() Returns true if the string starts with the specified value strip() Returns a trimmed version of the string swapcase() Swaps cases, lower case becomes upper case and vice versa title() Converts the first character of each word to upper case translate() Returns a translated string upper() Converts a string into upper case zfill() Fills the string with a specified number of 0 values at the beginning 09-11-2021 meghav@kannuruniv.ac.in 22
  • 23. Example s=‘Learning Python is easy’ print(s.lower()) print(s.title()) print(s.upper()) print(s.swapcase()) print(s.capitalize()) 09-11-2021 meghav@kannuruniv.ac.in 23