Python C C Presentation 2

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 73

PYTHON

PROGRAMMING

Presented By,
Anjaly Antony
Assistant Professor
Department of computer Application
MET’S College Of Advanced Studies
Python

Functions and Modules


Python Functions

 A function is a block of code which only runs when it is called.


 A function is a collection of related data, that performs a mathematical, analytical, or evaluative
operation.
 Python functions are simple to define and essential to intermediate-level programming.
 You can pass data, known as parameters, into a function.
 A function can return data as a result.
 We may call the function and reuse the code contained within it with different variables rather
than repeatedly creating the same code block for different input variables.
Categories of functions
 User-defined and built-in functions are the two main categories of functions in Python.
 It helps maintain the programme concise, unique, and well-structured.
Advantages of Functions in Python
• By including functions,
we can prevent repeating the same code block repeatedly in a program.
• Python functions,
once defined, can be called many times and from anywhere in a program.
• If our Python program is large,
it can be separated into numerous functions which is simple to track.
• The key accomplishment of Python functions is
we can return as many outputs as we want with different arguments.
Syntax of Python Function

#  An example Python Function  
def function_name( parameters ):  
# code block  

• The beginning of a function header is indicated by a keyword called def.


• function_name is the function's name.
We will use this name to call the function later in the program.
In Python, name functions must follow the same rules as naming variables.
• We pass arguments to the defined function using parameters. However, they are optional.
• The function header is terminated by a colon (:).
• The body of the function is made up of several valid Python statements.
• We can use a return expression to return a value from a defined function.
Creating a Function

 In Python a function is defined using the def keyword:

Example

def my_function():

print("Hello from a function")


Calling a Function
 After a function's fundamental framework is complete,
we can call it from anywhere in the program.
 To call a function, use the function name followed by parenthesis:

Example

def my_function():
  print("Hello from a function")

my_function()
Example2

# Example Python Code for calling a function


def abc( string ):
return len(string)

# Calling the function we defined


print( "Length of the string Functions is: ", abc( "Functions" ) )
print( "Length of the string Python is: ", abc( "Python" ) )

Output:

Length of the string Functions is: 9


Length of the string Python is: 6
Arguments
 Information can be passed into functions as arguments.
 Arguments are specified after the function name, inside the parentheses.
 You can add as many arguments as you want, just separate them with a comma.
Example
It has a function with one argument (fname). When the function is called, we pass along a first
name, which is used inside the function to print the full name:

def my_function(fname):
  print(fname + " Refsnes")
OutPut
my_function("Emil") Emil Refsnes
my_function("Tobias") Tobias Refsnes
my_function("Linus") Linus Refsnes
Return Statement
 We write a return statement in a function to leave a function and
give the calculated value when a defined function is called.

Syntax:
return < expression to be returned as output >

 The return statement, which is supplied as output when a particular job or function is finished,
might take the form of an argument, a statement, or a value.
 A declared function will return a None object, if no return statement is written.
Return Values

 To let a function return a value, use the return statement:

Example

def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))
OUTPUT
15
25
45
Working of Python Function

Here,
 When the function is called, the control of the program goes to the function definition.
 All codes inside the function are executed.
 The control of the program jumps to the next statement after the function call.
Example of a User-Defined Function

Code
# Example Python Code for User-Defined function
def square( num ):
"""
This function computes the square of the number.
"""
return num**2
objects = square(6)
print( "The square of the given number is: ", objects)

Output:
The square of the given number is: 36
Example 2: Python Function Arguments

# function with two arguments


def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ",sum)

# function call with two values


add_numbers(5, 4)

Output:

Sum: 9
Example 3: Function return Type

# function definition
def find_square(num):
result = num * num
return result

# function call
square = find_square(3)

print('Square:',square)

Output:

Square: 9
Python Built in Functions
Function Description
abs() Returns the absolute value of a number
all() Returns True if all items in an iterable object are true
any() Returns True if any item in an iterable object is true
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
chr() Returns a character from the specified Unicode code.
complex() Returns a complex number
dict() Returns a dictionary (Array)
eval() Evaluates and executes an expression
exec() Executes the specified code (or object)
float() Returns a floating point number
format() Formats a specified value
hex() Converts a number into a hexadecimal value
id() Returns the id of an object
input() Allowing user input
int() Returns an integer number
len() Returns the length of an object
list() Returns a list
max() Returns the largest item in an iterable
min() Returns the smallest item in an iterable
next() Returns the next item in an iterable
object() Returns a new object
oct() Converts a number into an octal
pow() Returns the value of x to the power of y
print() Prints to the standard output device
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
reversed() Returns a reversed iterator
round() Rounds a numbers
sorted() Returns a sorted list
str() Returns a string object
sum() Sums the items of an iterator
Pass by Reference vs. Pass by Value

 All parameters in the Python programming language are provided by reference.

 It indicates that, if we alter the value of an argument inside of a function,

the calling function will likewise reflect the change.


Python Modules

 A module allows you to logically organize your Python code.

 A file containing a set of functions you want to include in your application.

 Grouping related code into a module makes the code easier to understand and use.

 A module is a Python object with arbitrarily named attributes that you can bind and reference.

 A module is a file consisting of Python code.

 A module can define functions, classes and variables.

 A module can also include runnable code.


Create a Module
 To create a module just save the code you want in a file with the file extension .py

def greeting(name):
print("Hello, " + name)

Use a Module
 We can use the module we just created, by using the import statement:

import mymodule

mymodule.greeting("Jonathan")
Python Tuples

 Tuples are used to store multiple items in a single variable.


 A tuple is a collection which is ordered and unchangeable.
 Tuples are written with round brackets.

Example

thistuple = ("apple", "banana", "cherry")
print(thistuple)

OUTPUT

('apple', 'banana', 'cherry')


Tuple Items
 Tuple items are ordered, unchangeable, and allow duplicate values.
 Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

1. Ordered
When we say that tuples are ordered, it means that the items have a defined order,
and that order will not change.
2. Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items
after the tuple has been created.
3. Allow Duplicates
Since tuples are indexed, they can have items with the same value.
Example
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
OutPut

('apple', 'banana', 'cherry', 'apple', 'cherry')

Tuple Length
 To determine how many items a tuple has, use the len() function.

Example OutPut
thistuple = tuple(("apple", "banana", "cherry"))
3
print(len(thistuple))
Tuple Items - Data Types
 Tuple items can be of any data type.

Example
OutPut
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3) ('apple', 'banana', 'cherry')
tuple3 = (True, False, False) (1, 5, 7, 9, 3)
(True, False, False)
print(tuple1)
print(tuple2)
print(tuple3)

 A tuple can contain different data types.


OutPut
Example
('abc', 34, True, 40, 'male')
tuple1 = ("abc", 34, True, 40, "male")
print(tuple1)
Python List Slicing
 List slicing is a common practice and it is the most used technique,
for programmers to solve efficient problems.
 Consider a python list, In-order to access a range of elements in a list, you need to slice a list.
 One way to do this is to use the simple slicing operator i.e. colon(:)
 With this operator, one can specify where to start the slicing, where to end, and specify the step.
 List slicing returns a new list from the existing list.

Syntax:
Lst[ Initial : End : IndexJump ]

 If Lst is a list, then the above expression returns the portion of the list
from index Initial to index End, at a step size IndexJump.
 simple program, to display a whole list using slicing.

Example
# Initialize list
Lst = [50, 70, 30, 20, 90, 10, 50]

# Display list
print(Lst[::])

Output:

[50, 70, 30, 20, 90, 10, 50]


Slicing

# Initialize list
Lst = [50, 70, 30, 20, 90, 10, 50]

# Display list
print(Lst[1:5])

Output:

[70, 30, 20, 90]


Example

# Initialize list
List = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Show original list


print("\nOriginal List:\n", List)

print("\nSliced Lists: ") Output:

# Display sliced list Original List:


print(List[3:9:2]) [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Display sliced list Sliced Lists:


print(List[::2]) [4, 6, 8]
[1, 3, 5, 7, 9]
# Display sliced list [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(List[::])
Python - List Comprehension

 List comprehension offers a shorter syntax when you want to create a new list based
on the values of an existing list.

Example:

 Based on a list of fruits, you want a new list, containing only the fruits with the letter
"a" in the name.
 With list comprehension you can do all that with only one line of code.

fruits = ["apple", "banana", "cherry", "kiwi", "mango"] OutPut

newlist = [x for x in fruits if "a" in x] ['apple', 'banana', 'mango']


print(newlist)
Syntax

newlist = [expression for item in iterable if condition == True]

 The return value is a new list, leaving the old list unchanged.

 The condition is like a filter that only accepts the items that valuate to True.
 The condition is optional and can be omitted.

Example
 Only accept items that are not "apple":

newlist = [x for x in fruits if x != "apple"]

 The condition if x != "apple" will return True for all elements other than "apple", making the new list
contain all fruits except "apple".
Python String format() Method

 The format() method formats the specified value and insert them inside the string's placeholder.

 The placeholder is defined using curly brackets: {}.

 The format() method returns the formatted string.

Example
 Insert the price inside the placeholder, the price should be in fixed point, two-decimal format:

txt = "For only {price:.2f} dollars!"


print(txt.format(price = 49)) OutPut

For only 49.00 dollars!


Syntax

string.format(value1, value2...)

Parameter Values

 value1, value2... Required.


 One or more values that should be formatted and inserted in the string.

 The values are either a list of values separated by commas,

a key=value list, or a combination of both.

 The values can be of any data type.


Python String Methods
Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string


count() Returns the number of times a specified value occurs in a string
find() Searches the string for a specified value and returns the position of where it was found

format() 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
isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

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

isupper() Returns True if all characters in the string are upper case

lower() Converts a string into lower case

title() Converts the first character of each word to upper case

upper() Converts a string into upper case


Numeric Functions in Python

Function Description
ceil(x) Returns the smallest integer greater than or equal to x.
fabs(x) Returns the absolute value of x
factorial(x) Returns the factorial of x
floor(x) Returns the largest integer less than or equal to x
fmod(x, y) Returns the remainder when x is divided by y
exp(x) Returns e**x
pow(x, y) Returns x raised to the power y
sqrt(x) Returns the square root of x
cos(x) Returns the cosine of x
sin(x) Returns the sine of x
tan(x) Returns the tangent of x
pi Mathematical constant, the ratio of circumference of a circle to it's diameter (3.14159...)
Object Oriented Programming
in Python
 In Python, object-oriented Programming (OOPs) is a programming paradigm

that uses objects and classes in programming.

 It aims to implement real-world entities like inheritance, polymorphisms,

encapsulation, etc. in the programming.

 The main concept of OOPs is to bind the data and the functions that work on that together

as a single unit so that no other part of the code can access this data.
OOPs Concepts in Python

 Class
 Objects
 Polymorphism
 Encapsulation
 Inheritance
 Data Abstraction
1. Python Class

 A class is a collection of objects.


 A class contains the blueprints or the prototype from which the objects are being created.
 It is a logical entity that contains some attributes and methods.
 Example, let’s say you wanted to track the number of dogs that may have different attributes
like breed, and age.

 Classes are created by keyword class.


 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.) operator.
 Eg: Myclass.Myattribute
Syntax:

class ClassName:
# Statement-1
.
.
.
# Statement-N Creating an Empty Class in Python

# Python3 program to
# demonstrate defining
# a class

class Dog:
pass
2. Python Objects

 The object is an entity that has a state and behavior associated with it.
 It may be any real-world object like a mouse, keyboard, chair, table, pen, etc.
 Integers, strings, floating-point numbers, even arrays, and dictionaries, are all objects.
 More specifically, any single integer or any single string is an object.
 The number 12 is an object, the string “Hello, world” is an object.
An object consists of:
 State: It is represented by the attributes of an object. It also reflects the properties of an object.
 Behavior: It is represented by the methods of an object. It also reflects the response of an object
to other objects.
 Identity: It gives a unique name to an object and enables one object to interact with other objects.
 To understand the state, behavior, and identity let us take the example of the class dog.

• The identity can be considered as the name of the dog.


• State or Attributes can be considered as the breed, age, or color of the dog.
• The behavior can be considered as to whether the dog is eating or sleeping.

Creating an Object
 This will create an object named obj of the class Dog.

Example
obj = Dog()
Python Inheritance

 Inheritance is the capability of one class to derive or inherit the properties from another class.
 The class that derives properties is called the derived class or child class
and the class from which the properties are being derived is called the base class or parent class.

The benefits of inheritance are:

 It represents real-world relationships well.


 It provides the reusability of a code.
 We don’t have to write the same code again and again.
 Also, it allows us to add more features to a class without modifying it.
Types of Inheritance

1. Single Inheritance:
Single-level inheritance enables a derived class to inherit characteristics from a single-parent class.
2. Multilevel Inheritance:
Multi-level inheritance enables a derived class to inherit properties from an immediate parent class
which in turn inherits properties from his parent class.
3. Hierarchical Inheritance:
Hierarchical-level inheritance enables more than one derived class to inherit properties from a parent class.
4. Multiple Inheritance:
Multiple-level inheritance enables one derived class to inherit properties from more than one base class.
Python Polymorphism

 Polymorphism simply means having many forms.


 For example, we need to determine, if the given species of birds fly or not, using
polymorphism we can do this using a single function.
 That is, the same entity (method or operator or object) can perform different operations in
different scenarios.
 Polymorphism refers to a subclass's ability to adapt a method that already exists in its
superclass to meet its needs.
 To put it another way, a subclass can use a method from its superclass as is or modify it as
needed.
Python Encapsulation

 Encapsulation is one of the fundamental concepts in object-oriented programming (OOP).


 It describes the idea of wrapping data and the methods that work on data within one unit.
 This puts restrictions on accessing variables and methods directly and can prevent the
accidental modification of data.
 To prevent accidental change, an object’s variable can only be changed by an object’s method.
 Those types of variables are known as private variables.
 A class is an example of encapsulation as it encapsulates all the data that is functions,
variables, etc.
Data Abstraction

 It hides unnecessary code details from the user.

 Also, when we do not want to give out sensitive parts of our code implementation

and this is where data abstraction came.

 Data Abstraction in Python can be achieved by creating abstract classes.


Python Lambda

 A lambda function is a small anonymous function.

 A lambda function can take any number of arguments, but can only have one expression.

Syntax

lambda arguments : expression

Example
#Add 10 to argument a, and return the result:
OutPut
x = lambda a : a + 10
print(x(5)) 15
 Lambda functions can take any number of arguments:

Example
OutPut
#Multiply argument a with argument b and return the result:
30
x = lambda a, b : a * b
print(x(5, 6))

Example
#Summarize argument a, b, and c and return the result:
OutPut
x = lambda a, b, c : a + b + c
print(x(5, 6, 2)) 13
Python map() Function

 The map() function executes a specified function for each item in an iterable.

 The item is sent to the function as a parameter.

Syntax

map(function, iterables)

Parameter Description
function Required. The function to execute for each item
iterable Required. A sequence, collection or an iterator object. You can send as many iterables
as you like, just make sure the function has one parameter for each iterable.
Example 1
OutPut
#Calculate the length of each word in the tuple:
[5, 6, 6]
def myfunc(n):
return len(n)

x = map(myfunc, ('apple', 'banana', 'cherry'))

Example 2

#Make new fruits by sending two iterable objects into the function:
OutPut
def myfunc(a, b):
return a + b ['appleorange', 'bananalemon', 'cherrypineapple']

x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon', 'pineapple'))


Python filter() Function

 The filter() function returns an iterator where the items are filtered through a function
to test if the item is accepted or not.

Syntax

filter(function, iterable)

Parameter Description
function A Function to be run for each item in the iterable
iterable The iterable to be filtered
Example

#Filter the array, and return a new array with only the values equal to or above 18:

ages = [5, 12, 17, 18, 24, 32]

def myFunc(x):
if x < 18:
return False
else:
return True

adults = filter(myFunc, ages)


OutPut
for x in adults:
print(x) 18
24
32
Python Generators
 A generator-function is defined like a normal function, but whenever it needs to generate a
value, it does so with the yield keyword rather than return.
 If the body of a def contains yield, the function automatically becomes a generator function.
 Python Generators are the functions that return the traversal object and used to create
iterators.
 It traverses the entire items at once.
 It is similar to the normal function defined by the def keyword and uses a yield keyword
instead of return.
 Or we can say that, if the body of any function contains a yield statement, it automatically
becomes a generator function.
Example

def simple():
for i in range(10):
if(i%2==0):
yield i

Output
#Successive Function call using for loop
0
for i in simple(): 2
print(i) 4
6
8
yield vs. return

 The yield statement is responsible for controlling the flow of the generator function.
 It pauses the function execution by saving all states and yielded to the caller.
 Later it resumes execution when a successive function is called.
 We can use the multiple yield statement in the generator function.

 The return statement returns a value and terminates the whole function
and only one return statement can be used in the function.
Python
Exception Handling
 Error in Python can be of two types i.e.

1. Syntax errors

2. Exceptions.

 Errors are problems in a program due to which the program will stop the execution.

 On the other hand, exceptions are raised when some internal events occur which

change the normal flow of the program.


Different types of exceptions in python
1. SyntaxError: This exception is raised when the interpreter encounters a syntax error in the code, such as a
misspelled keyword, a missing colon, or an unbalanced parenthesis.
2. TypeError: This exception is raised when an operation or function is applied to an object of the wrong type,
such as adding a string to an integer.
3. NameError: This exception is raised when a variable or function name is not found in the current scope.
4. AttributeError: This exception is raised when an attribute or method is not found on an object, such as trying to
access a non-existent attribute of a class instance.
5. IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails due to an
input/output error.
6. ZeroDivisionError: This exception is raised when an attempt is made to divide a number by zero.
7. ImportError: This exception is raised when an import statement fails to find or load a module.
Example: Syntax Error

# initialize the amount variable


amount = 10000

# check that You are eligible to


if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")

Output:
Exceptions:

 Exceptions are raised when the program is syntactically correct,


but the code results in an error.
 This error does not stop the execution of the program, however, it
changes the normal flow of the program.
Example:

# initialize the amount variable Output:


marks = 10000

# perform division with 0


a = marks / 0
print(a)

 The ZeroDivisionError as we are trying to divide a number by 0.

Note:
Exception is the base class for all the exceptions in Python.
Try and Except Statement – Catching Exceptions
 Try and except statements are used to catch and handle exceptions in Python.
 Statements that can raise exceptions are kept inside the try clause
and
the statements that handle the exception are written inside except clause.

Catching Specific Exception


 A try statement can have more than one except clause, to specify handlers for different exceptions.
 Please note that, at most one handler will be executed.
The general syntax for adding specific exceptions

try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
Finally Keyword in Python
 Python provides a keyword finally, which is always executed after the try and except blocks.
 The final block always executes after the normal termination of the try block or
after the try block terminates due to some exception.
Syntax:

try:
# Some Code....

except:
# optional block
# Handling of exception (if required)

else:
# execute if no exception

finally:
# Some code .....(always executed)
Example:

# No exception Exception raised in try block


try:
k = 5//0 # raises divide by zero exception.
print(k)

# handles zerodivision exception


except ZeroDivisionError:
print("Can't divide by zero")

finally:
# this block is always executed
# regardless of exception generation. Output:
print('This is always executed')
Can't divide by zero
This is always executed
Advantages of Exception Handling

 Improved program reliability: By handling exceptions properly, you can prevent your program from
crashing or producing incorrect results due to unexpected errors or input.
 Simplified error handling: Exception handling allows you to separate error handling code from the main
program logic, making it easier to read and maintain your code.
 Cleaner code: With exception handling, you can avoid using complex conditional statements to check for
errors, leading to cleaner and more readable code.
 Easier debugging: When an exception is raised, the Python interpreter prints a traceback that shows the exact
location where the exception occurred, making it easier to debug your code.
Disadvantages of Exception Handling:

 Performance overhead: Exception handling can be slower than using conditional statements to
check for errors, as the interpreter has to perform additional work to catch and handle the exception.
 Increased code complexity: Exception handling can make your code more complex, especially if
you have to handle multiple types of exceptions or implement complex error handling logic.
 Possible security risks: Improperly handled exceptions can potentially reveal sensitive information
or create security vulnerabilities in your code, so it’s important to handle exceptions carefully and
avoid exposing too much information about your program.
Python
Mini Project
SUPERMARKET BILLING
Project
GoodWill Traders require an invoice entry screen with the following details as shown below.
enter Item >Pen
enter qty: 10
Enter unit :No
enter Rate: 20
enter Tax %: 12.5
wanna add more [enter Q to exit] > Once the user enters Q/q the program should terminate
and
print item sales as follows.
Discount of 1 % should be given to all sales exceeding Rs 300.
The program should validate input and ask to re-enter values for all numeric entry fields.
THANK YOU

You might also like