Function in Python function in python.pptx

JHILIPASAYAT 46 views 54 slides Sep 22, 2024
Slide 1
Slide 1 of 54
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54

About This Presentation

Function in python


Slide Content

Function in Python By:- Amit Yerpude PGT(Computer Science) Kendriya Vidyalaya , No. 1 Bolangir

Let’s look in this 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Code to calculate factorial num=int(input(‘enter number’)) facto=1 for i in range(1,num+1): facto=facto*i print(facto) So to compute combination and permutation, we have to write these code 3 times 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Now look this code!!! 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir def facto(a): facto=1 for i in range(1,a+1): facto=facto*i return facto def combi(n,r): return facto(n)/facto(r)*facto(n-r) r1=combi(5,3) print(r1)

Definition: A function is a block of organized, reusable code that is used to perform a single, related action. Functions provides better modularity for your application and a high degree of code reusing. As you already know, Python gives you many built-in functions like print() etc. but you can also create your own functions. These functions are called user-defined functions. 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Types of function in python: 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Defining a Function Here are simple rules to define a function in Python: Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. The first statement of a function can be an optional statement - the documentation string of the function or docstring . The code block within every function starts with a colon (:) and is indented. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None. 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Syntax: def function_name (parameters): "function docstring " statement1 statement2 ... ... return [ expr ] e.g. >>> def hello(): """ This Python function simply prints hello to the screen """ print("Hello welcome to the World") 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Calling of any function: To call a defined function, just use its name as a statement anywhere in the code. For example, the above function can be called as hello() and it will show the following output. >>>hello() >>> Hello welcome to the World 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Python Function Parameters Sometimes, you may want a function to operate on some variables, and produce a result. Such a function may take any number of parameters. Let’s take a function to add two numbers. >>> def sum( a,b ): print( a,’+’,b ,’=‘, a+b ) >>> sum(2,3) 2+3=5 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Function with Return Value Most of the times, we need the result of the function to be used in further processes. Hence, when a function returns, it should also return a value. A user-defined function can also be made to return a value to the calling environment by putting an expression in front of the return statement. In this case, the returned value has to be assigned to some variable. 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Python return statement A Python function may optionally return a value. This value can be a result that it produced on its execution or it can be something you specify- an expression or a value. >>> def func1(a): if a%2==0: return 0 else: return 1 >>> func1(7) 1 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

1. Function without parameter without return value def simple_interest (): p= int (input(‘enter principal amount’)) r=float(input(‘enter rate of interest’)) t= int (input(‘enter time period’)) si =(p*r*t)/100 print(“Simple Interest = “, si ) 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

2. Function with parameter without return value p= int (input(‘enter principal amount’)) r=float(input(‘enter rate of interest’)) t= int (input(‘enter time period’)) def simple_interest ( p,r,t ): si =(p*r*t)/100 print(“Simple Interest = “, si ) simple_interest ( p,r,t ) 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

3. Function without parameter with return value def simple_interest (): p= int (input(‘enter principal amount’)) r=float(input(‘enter rate of interest’)) t= int (input(‘enter time period’)) return (p*r*t)/100 si = simple_interest () print(“Simple Interest = “, si ) 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

4. Function with parameter with return value 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir p= int (input(‘enter principal amount’)) r=float(input(‘enter rate of interest’)) t= int (input(‘enter time period’)) def simple_interest ( p,r,t ): return (p*r*t)/100 si = simple_interest ( p,r,t ) print(“Simple Interest = “, si )

Thank You!!! 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Types of Arguments By:- Amit Yerpude PGT(Computer Science) Kendriya Vidyalaya , No. 1 Bolangir

Positional Argument An argument is a variable, value or object passed to a function or method as input. Positional arguments are arguments that need to be included in the proper position or order. Positional arguments must be included in the correct order. The first positional argument always needs to be listed first when the function is called. The second positional argument needs to be listed second and the third positional argument listed third, etc. Example: def rect_area ( l,b ): return l*b r_area = rect_area (5,4) print( r_area ) 4/19/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Default argument While defining a function, its parameters may be assigned default values. This default value gets substituted if an appropriate actual argument is passed when the function is called. However, if the actual argument is not provided, the default value will be used inside the function. The following SayHello () function is defined with the name parameter having the default value 'Guest'. It will be replaced only if some actual argument is passed. Example: Parameter with Default Value def SayHello (name='Guest'): print ("Hello " + name) return You can call the above function with or without passing a value, as shown below. >>> SayHello () Hello Guest >>> SayHello (‘ Amit ') Hello Amit 4/19/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Function with Keyword Arguments In order to call a function with arguments, the same number of actual arguments must be provided. Consider the following function. def AboutMe (name, age): print ("Hi! My name is {} and I am {} years old".format ( name,age )) return The above function is defined to receive two positional arguments. If we try to call it with only one value passed, the Python interpreter flashes TypeError 4/19/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

>>> AboutMe (“ Amit ") TypeError : AboutMe () missing 1 required positional argument: 'age' If a function receives the same number of arguments and in the same order as defined, it behaves correctly. >>> AboutMe (“ Amit ", 32) Hi! My name is Amit and I am 32 years old Python provides a useful mechanism of using the name of the formal argument as a keyword in function call. The function will process the arguments even if they are not in the order provided in the definition, because, while calling, values are explicitly assigned to them. The following calls to the AboutMe () function is perfectly valid. >>> AboutMe (age=23, name="Mohan") Hi! My name is Mohan and I am 23 years old 4/19/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

List as argument 4/19/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir    def add_more (list):      list.append (50)     print("Inside Function", list)    mylist = [10,20,30,40]    add_more ( mylist ) print("Outside Function:", mylist ) Output : Inside Function [10, 20, 30, 40, 50] Outside Function: [10, 20, 30, 40, 50]

Dictionary as argument 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir def func (d):             for key in d:         print("key:", key, "Value:", d[key])             D = {'a':1, 'b':2, 'c':3} func (D) Output: key: b Value: 2 key: a Value: 1 key: c Value: 3

Tuple as argument def tupleprint (x): print(x) t1=(‘Amit’,30) tupleprint (t1) Output: (‘Amit’,30) 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Is Python call by reference or call by value ? Python utilizes a system, which is known as “Call by Object Reference” or “Call by assignment”. In the event that you pass arguments like whole numbers, strings or tuples to a function, the passing is like call-by-value because you can not change the value of the immutable objects being passed to the function. Whereas passing mutable objects can be considered as call by reference because when their values are changed inside the function, then it will also be reflected outside the function. 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir # call by value       string = “Hello"       def test(string):            string = “Hello Amit "     print("Inside Function:", string)        test(string ) print("Outside Function:", string) Output: Inside Function: Hello Amit Outside Function: Hello # call by reference       def add_more (list):      list.append (50)     print("Inside Function", list)    mylist = [10,20,30,40]    add_more ( mylist ) print("Outside Function:", mylist ) Output : Inside Function [10, 20, 30, 40, 50] Outside Function: [10, 20, 30, 40, 50]

Scope and Lifetime of Variables in Python A variable isn’t visible everywhere and alive every time. The scope and lifetime for a variable depend on whether it is inside a function. Scope A variable’s scope tells us where in the Function it is visible. A variable may have local or global scope. Local Scope- A variable that’s declared inside a function has a local scope. In other words, it is local to that function. >>> def func (): x=7 print(x) >>> func () 7 >>> x %If you then try to access the variable x outside the function, you cannot. Traceback (most recent call last): File “<pyshell#96>”, line 1, in <module> x NameError : name ‘x’ is not defined 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Global Scope- When you declare a variable outside python function, or anything else, it has global scope. It means that it is visible everywhere within the Function. >>> y=7 >>> def func (): print(y) >>> func () 7 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Lifetime A variable’s lifetime is the period of time for which it resides in the memory. A variable that’s declared inside python function is destroyed after the function stops executing. So the next time the function is called, it does not remember the previous value of that variable. >>> def func (): counter=0 counter+=1 print(counter) >>> func () 1 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Order of resolving scope Local namespace Enclosed namespace Global namespace Built-In namespace 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

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 The expression is executed and the result is returned: Example A lambda function that adds 10 to the number passed in as an argument, and print the result: x = lambda a : a + 10 print(x(5)) 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

More Example: A lambda function that multiplies argument a with argument b and print the result: x = lambda a, b : a * b print(x(5, 6)) A lambda function that sums argument a, b, and c and print the result: x = lambda a, b, c : a + b + c print(x(5, 6, 2)) 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

1.  Write a   Python  function to find the maximum of three numbers. 2.  Write a Python function to sum all the numbers in a list. Sample List  : (8, 2, 3, 0, 7) Expected Output  : 20 3.  Write a   Python  function to multiply all the numbers in a list. Sample List  : (8, 2, 3, -1, 7) Expected Output  : -336 4.  Write a Python program to reverse a string. Sample String  : "1234abcd" Expected Output  : "dcba4321” 5.  Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument. 6.  Write a   Python  function to check whether a number falls within a given range. 7.  Write a Python function that accepts a string and counts the number of upper and lower case letters. Sample String  : 'The quick Brow Fox' Expected Output  : No. of Upper case characters : 3 No. of Lower case Characters : 12 8.  Write a   Python  function that takes a list and returns a new list with distinct elements from the first list. Sample List :  [1,2,3,3,3,3,4,5] Unique List :  [1, 2, 3, 4, 5] 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

9.  Write a Python function that takes a number as a parameter and checks whether the number is prime or not. Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors other than 1 and itself. 10.  Write a   Python  program to print the even numbers from a given list. Sample List  : [1, 2, 3, 4, 5, 6, 7, 8, 9] Expected Result  : [2, 4, 6, 8] 11.  Write a   Python  function to check whether a number is "Perfect" or not. According to Wikipedia : In number theory, a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself (also known as its aliquot sum). Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Example  : The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 = 6. The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed by the perfect numbers 496 and 8128. 12.  Write a   Python  function that checks whether a passed string is a palindrome or not. Note: A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run. 13.  Write a   Python  function that prints out the first n rows of Pascal's triangle. Note : Pascal's triangle is an arithmetic and geometric figure first imagined by Blaise Pascal. Sample Pascal's triangle : Each number is the two numbers above it added together 4/18/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

14.  Write a Python function to check whether a string is a pangram or not. Note : Pangrams are words or sentences containing every letter of the alphabet at least once. For example : "The quick brown fox jumps over the lazy dog” 15.  Write a   Python  program that accepts a hyphen-separated sequence of words as input and prints the words in a hyphen-separated sequence after sorting them alphabetically. Sample Items  : green-red-yellow-black-white Expected Result  : black-green-red-white-yellow 16.  Write a   Python  function to create and print a list where the values are the squares of numbers between 1 and 30 (both included). 17.  Write a Python program to create a chain of function decorators (bold, italic, underline etc.). 18.  Write a Python program to execute a string containing   Python code . 19.  Write a Python program to access a function inside a function. 20.  Write a   Python  program to detect the number of local variables declared in a function. Sample Output: 3 4/19/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Thank You!!! 4/19/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Working with Python Module By:- Amit Yerpude PGT(Computer Science) Kendriya Vidyalaya , Khagaria

There are two way to use modules in your python Function By using import Syntex : import <name of module> e.g. import random num= random. randint (1, 25) By using from Syntex : from <name of module> import <name of function> e.g. from random import randint num= randint (1, 25) 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

List of Functions in Python Math Module Function Description ceil(x) Returns the smallest integer greater than or equal to x. copysign(x, y) Returns x with the sign of y 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 frexp(x) Returns the mantissa and exponent of x as the pair (m, e) fsum(iterable) Returns an accurate floating point sum of values in the iterable isfinite(x) Returns True if x is neither an infinity nor a NaN (Not a Number) isinf(x) Returns True if x is a positive or negative infinity isnan(x) Returns True if x is a NaN trunc (x) Returns the truncated integer value of x exp(x) Returns e**x expm1(x) Returns e**x - 1 log(x[, base]) Returns the logarithm of x to the base (defaults to e) log1p(x) Returns the natural logarithm of 1+x log2(x) Returns the base-2 logarithm of x log10(x) Returns the base-10 logarithm of 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 hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y) sin(x) Returns the sine of x tan(x) Returns the tangent of x degrees(x) Converts angle x from radians to degrees radians(x) Converts angle x from degrees to radians gamma(x) Returns the Gamma function at x lgamma (x) Returns the natural logarithm of the absolute value of the Gamma function at x pi Mathematical constant, the ratio of circumference of a circle to it's diameter (3.14159...) e mathematical constant e (2.71828...) 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

random.random (): Generates a random float number between 0.0 to 1.0. The function doesn't need any arguments. >>> random.random () 0.645173684807533 random.randint (): Returns a random integer between the specified integers. >>> random.randint (1,100) 95 random.randrange (): Returns a randomly selected element from the range created by the start, stop and step arguments. The value of start is 0 by default. Similarly, the value of step is 1 by default. >>> random.randrange (1,10) 2 >>> random.randrange (1,10,2) 5 random.choice (): Returns a randomly selected element from a non-empty sequence. An empty sequence as argument raises an IndexError . >>> random.choice ('computer') 't' >>> random.choice ([12,23,45,67,65,43]) 45 >>> random.choice ((12,23,45,67,65,43)) 67 random.shuffle (): This functions randomly reorders the elements in a list. >>>numbers=[12,23,45,67,65,43] >>> random.shuffle (numbers) >>>numbers [23, 12, 43, 65, 67, 45] 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir Python - Random Module

Assignment String Module functions 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Practice Problems: Write a Function to read an integer and print its multiplication table. Write a Function to find factorial of a number. Write a Function to print Fibonacci series upto N terms. Write a Function to calculate the square of first N natural numbers. Write a Function to calculate e x upto N terms. Write Functions to calculate sin(x), cos (x) and tan(x) upto N terms. Write a Python function to sum all the numbers in a list. Write a Python function to multiply all the numbers in a list. Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters. Write a Python function that takes a list and returns a new list with unique elements of the first list. Write a Function to generate a random number between 1-6, to simulate Dice. 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Thank You!!! 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Recursion in Python By:- Amit Yerpude PGT(Computer Science) Kendriya Vidyalaya , Khagaria

Recursive function A recursive function is a function defined in terms of itself via self-referential expressions. This means that the function will continue to call itself and repeat its behaviour until some condition is met to return a result. All recursive functions share a common structure made up of two parts: base case and recursive case. 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

To demonstrate this structure, let’s write a recursive function for calculating n!: Decompose the original problem into simpler instances of the same problem. This is the recursive case: n! = n x (n−1) x (n−2) x (n−3) ⋅⋅⋅⋅ x 3 x 2 x 1 n! = n x (n−1)! As the large problem is broken down into successively less complex ones, those subproblems must eventually become so simple that they can be solved without further subdivision. This is the base case: n! = n x (n−1)! n! = n x (n−1) x (n−2)! n! = n x (n−1) x (n−2) x (n−3)! ⋅ ⋅ n! = n x (n−1) x (n−2) x (n−3) ⋅⋅⋅⋅ x 3! n! = n x (n−1) x (n−2) x (n−3) ⋅⋅⋅⋅ x 3 x 2! n! = n x (n−1) x (n−2) x (n−3) ⋅⋅⋅⋅ x 3 x 2 x 1! Here, 1! is our base case, and it equals 1. 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Recursive function for calculating n! implemented in Python: def factorial_recursive (n): # Base case: 1! = 1 if n == 1: return 1 # Recursive case: n! = n * (n-1)! else: return n * factorial_recursive (n-1) >>> factorial_recursive (5) 120 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

a. Python Recursion Function Advantages With Python recursion, there are some benefits we observe: A recursive code has a cleaner-looking code. Recursion makes it easier to code, as it breaks a task into smaller ones. It is easier to generate a sequence using recursion than by using nested iteration. b. Python Recursion Function Disadvantages The flip side of the coin is easy to quote:Although it makes code look cleaner, it may sometimes be hard to follow. They may be simpler, but recursive calls are expensive. They take up a lot of memory and time. Finally, it isn’t as easy to debug a recursive function. 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

More Example: Define a function to calculate the sum of the first n natural numbers. >>> def sumofn (n): if n==1: return 1 return n+sumofn (n-1) >>> sumofn (16) 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

The first n terms from the Fibonacci series for argument ‘n’. def recur_fibo (n): if n <= 1: return n else: return( recur_fibo (n-1) + recur_fibo (n-2)) nterms = 10 # check if the number of terms is valid if nterms <= 0: print(" Plese enter a positive integer") else: print("Fibonacci sequence:") for i in range( nterms ): print( recur_fibo ( i )) 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Practice Problem: Function to calculate power of a number using recursion . This Function will read base and power and calculate its result using recursion, for example base is 2 and power is 3 then result will be (2^3=8). Function to count digits of a number using recursion . This Function will read an integer number and count its total digits using recursion, for example: input value is 34562, and then total number of digits is: 5. Function to find sum of all digits using recursion . This Function will read an integer number and print sum of all digits using recursion, for example: input value is 34562, and then sum of all digits is: 20. Function to calculate length of the string using recursion . This Function will read a string and count its total number of characters (length of the string) using recursion. 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir

Thank you!!! 4/17/2024 By:- Amit Yerpude, PGT CS, KV No.1 Bolangir
Tags