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

SL_Unit-4_Functions

This document provides an overview of functions in Python, including user-defined functions, recursion, and the math module. It explains how to define and call functions, pass parameters, and return values, as well as the advantages and disadvantages of recursion. Additionally, it covers various string functions and their usage in Python programming.

Uploaded by

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

SL_Unit-4_Functions

This document provides an overview of functions in Python, including user-defined functions, recursion, and the math module. It explains how to define and call functions, pass parameters, and return values, as well as the advantages and disadvantages of recursion. Additionally, it covers various string functions and their usage in Python programming.

Uploaded by

jainampanchal911
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 16
Unit-4: Functions 1. Introduction to Python User defined Function What is a function in Python? ¥ A function is « block of code which only runs when itis called. ¥ In Python, a function is a group of related statements that performs a specific task. You can pass data A function can retui Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable, Furthermore, it avoids repetition and makes the code reusable. known as parameters; into a function, data as a result KKK < mfax of Function def function_name (parameters): temeni(s) Above shown a function definition that consists of the following components. ¥ Keyword def that marks the start of the function header. vA function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python. ¥ Parameters (arguments) through which we pass values toa function. They are optional. A colon (:) to mark the end of the function header. ¥ One or more valid python statements that ms must have the same indentation level. ¥ return statement is used to return a value from the function. Example of creating a function: def my_function(): print("Hello from a 21CE! How to call a function in python? Example of call a functio Once we have defined a function, we can call it from another function, program, or even the Python prompt. To call a function we simply type the function name with appropriate parameters. my_funetion() Output: Hello from a 21CE 2. Passing paramete function to a function and returning values from a + Information ean be passed into funetions as arguments, + Arguments are specified afier the function name, inside the parentheses. You ean add as many arguments as you want, just separate them with a comma. +The following example has a funetion with one argument Gime). When the function is called. we pass along a name, which is used inside the function to print the name: Example of a function with parameter: functi (eam def im: print (Hello. + name +", Good morning calling a funetion: my_function (21CE3') Outpu Hello, 21CE3. Good mornin Returning a Values: ‘fo fet « function return a value. use the return statement + Example of a funetion with parameter and return valu del my_tunction(x) return 5 calling a funet print (my_funetion(3)) print (my_funetion(5)) print (my_function(9)) Output: 15 45 Python Default Arguments: » Function arguments ean have default values in Python. + We can provide a default value to an argument by using the assignment operator (=). Example: def sum(ab=10%: | def my_funetion (name, msg return a+b) print"Hello ", printisumis)) printisumiS.5)) Good morning!» ame. msg) my_function ("21CE3") my_funetion ("ENGINEERS', "How do you do?") Output: Output: 5 Hello 21CE3. Good morning! 10 Hello ENGINEERS, How do you do? 3. Recursion What is recursion? + A Function calls itself is said to be a recursion, Recursion is the process of defining something in terms of itself. A physical world example would be to place two parallel mirrors facing each other Any object in between them would be reflected recursively. Python Recursive Function: ¥ In Python, we know that a funetion can call other functions. It is even possible for the Junction to call itself. These types of construct are termed as recursive functions. ¥ The following image shows the workings of a recursive tunction called recurse. recursive call recurse() Example of a recursive function to find the factorial of an integer. ¥ Factorial of a number is the product of all the integers from 1 to that number, For example, the factorial of 6 (denoted as 6!) is 1*2*3%4*5*6 = 720. Examph def factorial(x): ifx==1 return 1 else: return (x * factorial(x-1)) calling a function: num =3 printe"The factorial of” num, "is", factorial(nam)) Output: The factorial of 3 is 6 ~ Our recursion ends when the number reduces (0 1, This is called the base condition. Every recursive function must have base conslition that stops the recursion or else the function ealls itself intinitely The Python interpreter limits the depths of recursion (© help avoid infinite recursions. resulting in stick overllows. By default, the maximum depth of recursion is 1000. IF the Timit is crossed, it results in ReeursionFrror Advantages of Recu v Re sion sive functions make the code look lean and elegant. A complex task can be broken down into simpler sub-problems usit “ S ecursion quence generation is easier with recursion than using some nested iteration. Disadvantages of Recu ion ¥ Sometimes the logic behind recursion is hard to follow through, Recursive calls are expensive (inefficient) as they take up a lot of memory and time. ¥ Recursive are har! to debug. math module - Mathematical functions ¥ Mathematical functions are defined in the math module. ¥ The math module has set of methods and constants ¥ This module ineludes trigonometric functions , logarithm functions .a tu Math constant: je conversion \ctions ete, Constant | Description Example mathe | Return Euler's number (2.718281828459045) | math hath. pi) path.e) math.pi_ | Return PE (3.141592653589793) pprint(math. tau) 35307 math.tau | Return tau (6.28 9586) ‘Numeric Functions: eil(): Rounds a number up to the nearest mteger Example : import math prin(math.ceild Output :9 23)) floor(:Rounds a number down to the nearest integer Example : import math print(math.floor(8.23)) Output :8 SqFtDEI retums the square root of the numbel Example: import math print(math.sqrtt25)) Output pow) ):itreceives (vo arguments. raises the first lo the second a Example: import math prine(math.pow(2,4)} Output: 16.0 factorial(): It returns the factorial of a given number. Example: import math print(math.factorial(4)) Output : 24 ged(): Itis used to find the greatest common divisor of two numbers passed as the arguments. Example :import math print(math.ged(10,35)) Output 35, fabs(): Tt returns the absolute value of the number. Example :import math print (math.fabs(-10)) Output : 10.0 fmod(): [t returns the reminder of x/y. Example : import math print (math.fmod(10.3)) Output : 1.0 exp(): [treturns a float number after raising e to the power of a given number. (e**x) Example : import math print (math.exp(2)) utput: 7.38905609893065 String functions @ Basie functio Jen, max, m n Ten( ): IUretums number of characters in the string synt He nam Exampl va len(string) python” Isten(s) print) Ouipu6 rmin( ): 1 finds the smallest element in the sequence. i the smallest code is selected in the str . the character that hi selected w For one st For the First alphabetically, yt as=min(s) n lexicographic order (dictionary orden) follows ans=n S="pythor Output print(min(s)) h s='abe+-0" + print(min(s)) ° s='012345' A print(min(s)) print(min(s)) Ouiput abe print(min(s)) max: IUTinds the Targest element in the sequen ng, the character that has the largest code is selected in the sting. For multiple string, a string is selected which, in lexicographic order, follows the last alphabetically Syntax. ans=max(s) Or ans=max(s1,s2,...sn) "pyton”™ print(max(s)) s='abe+-0" printimax(s}) s=012345' print(max(s}) s='aAbB" print(max(s)) s=(*det "abe KZ) print(max(s)) 2) print(man(s)) «© Testing functions: isalnum, isalpha, isdigit, isidentifier, islower, isupper, and isspace isalnumO; returns True if all he characters in the string is alphanumeric (a suring whieh contains either number or alphabets or both). Otherwise retum False print(s.isalnumQ) se'abe123" print(s.isalnum()) so print(s.isalnum@) sab’ print(s.isainum() isalpha: returns True if all the characters in the string are alphabets. Otherwise return False = Output: print(s.isalpha()) False s="ahe' True print(s.isalpha()) False s=123 False print(s.isalpha()) False sstabel 23" print(s.isalpha()) see! print(s.isalpha()) Isdigit: returns True if all the characters in the string are digits. Otherwise return False. Output print(”abe123" isdigit()) False print("123" isdigit()) True print(" 101 “.isdigit()) False print("101.129" isdigit()) False Tsidentifier: returns True if siring is an identifier or « keyword that is valid according lo the python syntax Otherwise return False. print( “hello” isidentifier) Output: print¢"al “isidentifier()) True print("1a”.isiclemtifien()) True print("for" isidentifier() False True slower: returns True if all the characters in the siring are in lowercase. Otherwise return False. s= Python’ Output: print(s.islower()) False print(“abe" islower0) True are in uppercase. Otherwise return pper: returns True if all the characters in the sti s='PY thon" Outputs print(s.isupper()) False print("ABC" isupper0) True return isspace : returns True if all the characters in the string are whitespace characters, Otherwis False. print("\nit™.isspaceO) Outputs print(” \n\e".isspace()) True print("@ \n\" isspaceQ) True print("123" isspace()) False False # Searching functions: endswith, startswith, find, rfind, count endswith: Syntax: endswith(sullix, start, end) ¥ Returns True when a string ends with the characters specified by sulfix. ¥ You can limit the check by specifying a starting index using start or an ending index using end. Y Ifstart and end indexes ure not provided then, by default iCtukes 0 and lengtl-1 as starting and ending indexes s="abedef™ Ouipats printis.endswith(er)) True print("abedef" endswith('ef,2,6)) True print("abedet™ endswith(eF,2.4)) False 5 sls! print(s2.ends ‘abed'ef) ‘abed 123 ef" ‘True (5 1,0,len(s2))) startswith: Syntax:startswith(prefix, start, end) ¥ Retums True when a string begins with the characters spec ¥ You can li ending indexes. «l by prelix. it the check by specifying u starting index using start or an ending index using end. ¥ If start and end indexes are not provided then, by default it takes 0 and length 1 as star ng and s="Hello” print(s.startswith(He')) print(s.startswith(‘o)) print(s.startswith(He',0)) print(s.startswith(He'0.len(s))) print(s.startswith('He’.2)) Output True False Tre True False True False Find: Syntax: find(str, start, end) ¥ Check whether str occur ¥ You can fi x string aud outputs the index of the location, it the search by specifying starting index using start or a ending index using end ¥ If start and end indexes are not provided then. by default it takes 0 and length-I as starting and ending indexes ¥ If search not found then it returns -1 "Hello World’ find( Hello’) print("Substring found at index:", ans) print(s.find('We')) printts.tind(l',2)) prints. finda’, 2)) print(s.find(o’, 2. 10)) Output: Substring found at index: 0 6 2 4 finds Syntax: rlind(sty, start, end) ¥ Provides the same functionality as of the starti ¥ You can ending indexes . ¥ If search not found then it retums -1. 1d(), but searches backward from the end of the string instead it the search by specifying starting index using start or a ending index using end. ¥ If start and end indexes aré not provided then, by default it takes 0 and length-1 as star and $= "Hello World’ ans = s.rfind(‘Hello’) print(”Substring found at index prinus. print(s.rfind(| print(s.rfinel print(s.rfind¢ find Wo')) 2» Output Substring found at index: 0 TLee count: Syntax: count(str, start, end): Y Counts how many times str occurs in a string. ¥ You can limit the search by specifying a starti ¥ If start and end indexes are not provided then, by default it takes 0 and length-1 as statt ending indexes. index using start or an ending index using end. ng and “Hello Students Hello" print(s.count("Hello”, 0, 5)) print(s.count¢"Hello”, 0, 20) print{s.count(T,0,20)) print(s.count(’c.0,20)) Output Sane mn functions: returns a copy of the original string gall other ch © Manipulat capitalize( capital (uppercase) letter, while mak Syntax: string_name.capitalizeQ and converts the first character of the string toa haracters in the string lowerease letters. s= "hello world” print(s.capitalizeQ) print("heLLo” capitalize()) print('123\capitalize()) Output Hello world Hello 123 returns it. Syntax: string lower() Jower(): This function converts all uppercase characters in a string into lowercase characters and s="AMI Patel” print("Original stvin print(”Converted string:"+s.lower() Output: Original string: AMI Patel Converted string:ami patel returns it. Syntax: string.upper() ‘upper (): This function converts all lowercase characters in a string into uppercase characters and MI Patel” print" Converted string:"+s.upper() Output: Original string: AMI Patel Converted string: AMI PATE! lowercase in the string and returns a new string. Syntax: string.title, tile (: It converts the first character in each word to uppercase and the remaining characters 10 s= "hELLo good morning print("Original string:".s) print("Converted string:"+s.title()) ‘Output Original string: HELLo good moming Converted string:Hello Good Morning swapease: The stri characters to uppercase of the given string, and retu Syntax: string.swapease() swapease() method converts all uppercase characters to lowercase and lowercase uns iL s="bELLo GOOD momi print” Original string:".s) Outputs Original string: hELLo GOOD moming print("Converted string:"+s.swapcase()) Converted string: HellO good MORNING replace: It returns a copy of the string where all occurrences of a substring are replaced with another substring. Syntax: string replace(old_string, new_string, count) s="Hello World” Output: slzs.replace( Hello World s2=s.replace("o","0".1) HeLLo World print(s) HellO World Istrip: It retums a copy of the string with leading characters removed (based on the string argument passed). If no argument is passed, it removes leading spaces. Syntax: string.Istrip({characters}) Here.characters [optional]: A set of characters to remove as leading characters. By default, it uses space as the character to remove. s=" Hello” Output: print(s.Istrip0) Hello s="+.--SHello” SHello print(s Istrip("+-")) strip: It returns a copy of the string with trailing characters removed (based on the string argument passed). If no argument is passed, it removes trailing spaces. Syntax: sting. sstrip([characters]) Parameters: characters (optional) ~ a string specifying the set of characters to be removed. s="Hello" ‘Output: print(s.rstrip()) Hello Hellot..+&, Hello print(s.rstrip(. 48) strip: [tis an inbuilt Function in the Python programming language that returns @ copy of the string, with both leading and trailing characters removed. Syntax: string. strip({characters}) s=" Hello World..." Output: print(s) Hello World... print(s.stripQ) Hello World. printts.stripC.)) Hello World casefold: Python String casefold() method is used to convert string to lower ease. [tis similar to lower() string method, but case removes all the case distinetions present in a string. Y For example, the German letter 8 is already lowercase so, the lower() method doesn’t make the conversion, Y But the casefold¢) method will convert & to its equivalent character ss. Syntax: string.casefold) s="HELLO™ Output: print(s.casefold0) hello print(s.lower()) hello © Formatting func format: The format() method formats the specified value(s) and insert them inside the string’s placeholder. The placeholder is defined using curly brackets: |}. It is used for handling complex string formatting more efficiently Syntax: swing format(value |, value2...) a=5) Output: b=10 S+10=15 (0}+{1)=(2)'-formatca.b,a+h) print(s) Output: s 2)" format(a,2,a**2) 5#92=25 print(s) s="My name is (Tame]”.formai(fname = “abe") | Output: print(s) My name is abe center: It creates and returns a new string that is padded with the specified character Syntax: string.center(length, fillehar)) Iength: length of the string after padding with the characters. fillchar: (optional) characters which need to be padded. If it’s not provided, space is taken as the default argument. s="Hello World” ‘Output, print(s.center(20)) Hello World print(s.center(5}) Hello World #HHHHello Worlds Hello World print(s.center(20, print(s.center(5,' just: This method! left aligns the string according to the width specified and fills the remaining space of the line with blank space if “fillehr” argument is not passed, Syntax: Ijusi(len, filler) len: The width of string to expand it fillchr (optional): The character to fill in the = "hello" Output: print(s.ljust(10)) hello print(s.Jjust(10, '-')) print(s.]just(10, '#)) This method left aligns the string according to the width specified and fills the remaini of the line with blank space if filehr* argument is not passed, Syntax: rjust(len, filler) len; The width of string to expand it. fillehr (optional): The character to fill in the remaining space. Wg space S= “hello” Ouiput primt(s.rjust(10)) hello print(s.rjust(10, )) hello print(s.rjust(10, '#')) #HtHihello Introduction to Text files Y Psthon provide Y There are iwvo types of files that in binary language. Os, and Is). built functions for creati be ary files (written Y Text files: In this type of file, Each (End of Line), which is the new line eh: ne of text is terminated with a special character called EOL crer ("\n’) in python by default. there is no tenninator fora lin ge. and the data is stored alter files: In this type of f ing it into machine-tnderstandable binary Lang ¥ Difference between Text files and Binary files: ext files Binary files Data stores in ASCH or Unicode. ‘Contains raw data ‘Content written in text files iy human readable, | Content written in binaty files snot human readable ‘Slower than binary file Faster than text file Text files are used to store data more user ry files are used fo store data more Y Files are named locations on disk to store related information Y They are used to permanently store data in a non-volatile memos Y When we want to read from oF write to a file, we need to open it first Y When we are done. it needs to be closed so that the resources that are tied with the file are freed, ¥ In Python. a file operation takes place in the following order: + Opena fi # Read or write (perform operation) © Close the file rd disk). File Handling functions: * Basic functions: open, close open Fil ¥ Before performing any operation on the file like reading or writing, first, we have to open that file. Y For this, we should use Python’s inbuilt function opend) ¥ Atihe time of opening, we have to specify the med, which represents the purpose of the opening file. Syntax: file object ie en(Filename, access mode) imple: Where the following mode is supported: [_Topen an existing fle fora read operation, Ww open an existing file for a write operation, Ifthe file already contains some data then it will be overridden but ifthe file is not present then it creates the Tile as well ‘| open an existing file for append operation, IC will not override existing data 1 | To read and write data into the file. The previous data in the file will be overridden wt | To write and read data. It will override existing data. a+ _| To append and read data from the file. Tt will not override existing data. close Fi ¥ closet) function closes the file and frees the memory space acquired by that file, Y Itis.used at the time when the file is no longer needed or if it is to be opened in a different file mode. Syntax: File object.close() Example: f= open("a.txt", "c") Helose() Reading file: Y To read a file in Python, we must open the file in reading (r) mode. Y There are three ways to read data from a text fl read, readline and readlines. read( } : Returns the read bytes in form of a string. It reads n bytes, if no n specified, reads the entire tile. Syntax: File object.read({n)) Feopen("a.txt Output: print(f:read()) hello everyone Exctose() Good morning readline( ) : Reads a line of the file and returns in form of a bytes. It does not reads more than one line, Syntax: File object.readline({n]) fEopen("atat",'T) ‘Output: print(f.read(5)) hello fuclose() ing. For specified n, reads at most a Readlines( ); Reads all the lines and return them as each line a string element in a list. Syntax: File_object.readllines() FopenCatxt’| ‘Output print(f.readlines( )) ‘hello everyone\n’, Good morning\n’ Have a nice day\n’| f.close() © writing file: write, append, writelines Y To write a file in Python, we must open the file in writing (w) mode or append mede(:) write():The write) method writes a string 10 a tex: file, Syntax: File_object.write(str1) Inserts the string str] ina single line in the text tile. Feopen("Evatxt","v" ‘Output: fawrite("Hello World") Open a.txt file_..... Hello World is display in text. F.close() file. append: To append (a text file, you need (© open When the file is opened in append mode, the frand written will be inserted at the end, after the existin the text file for appending mode. le is positioned at the end of the file. The data being data, open(E-/a.txt™."a") Output: f.write("Good Morning") Open a.txt file... Hello World Good Morning close) is display in text fle. writelines():The writelines() method write a list of strings to a file at once. Syntax: File_object.writelines(L) for L = [str]. str2, ste3] For a list of string elements, each string rings at a single time. miserted in the text file. Used to insert multiple FEopen(”Eva.tx'w") lines=["Hello\n", fwritelines(lines) fuclose() Output: Open atst file file. Hello ‘good morning Below content is displayed in text

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy