Python C C Presentation 2
Python C C Presentation 2
Python C C Presentation 2
PROGRAMMING
Presented By,
Anjaly Antony
Assistant Professor
Department of computer Application
MET’S College Of Advanced Studies
Python
# An example Python Function
def function_name( parameters ):
# code block
Example
def my_function():
Example
def my_function():
print("Hello from a function")
my_function()
Example2
Output:
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
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
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
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.
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
Example
thistuple = ("apple", "banana", "cherry")
print(thistuple)
OUTPUT
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
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)
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:
# Initialize list
Lst = [50, 70, 30, 20, 90, 10, 50]
# Display list
print(Lst[1:5])
Output:
# Initialize list
List = [1, 2, 3, 4, 5, 6, 7, 8, 9]
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.
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":
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.
Example
Insert the price inside the placeholder, the price should be in fixed point, two-decimal format:
string.format(value1, value2...)
Parameter Values
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
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
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
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
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.
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.
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
Also, when we do not want to give out sensitive parts of our code implementation
A lambda function can take any number of arguments, but can only have one expression.
Syntax
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.
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)
Example 2
#Make new fruits by sending two iterable objects into the function:
OutPut
def myfunc(a, b):
return a + b ['appleorange', 'bananalemon', 'cherrypineapple']
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:
def myFunc(x):
if x < 18:
return False
else:
return True
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
Output:
Exceptions:
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.
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:
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