You are on page 1of 38
4, CONDITIONAL STATEMENTS In programming languages, conditional statements are used to perform different computations or actions depending on the evaluation of condition The conditional statements available in python are listed below > ifstatement if-else statement > if-elif- else statement > Nestedifstatement 4.1 if'statement Decision making is required when we want to execute a code ony i'a certain condition is satisfied Here, the program evaluates the +: the text expression is Prue expression and will execute statement(s) only if If the text expression is Faise, the statement(s) is not executed. Python if Statement Syntax if test expression: statement(s) In Python, the body of the <¢ statement is indicated by the indentation. Body starts with an indentation and the first unindented line marks the end. Python interprets non-zero values as Tue. one and 0 ate interpreted as FaLe. 1 Test False Expression True 1 | Fig: Operation off statement hun = 3 point (num, “is a positive number”) 1 2 3+ if num > 6 4 5 print ("This is always printed.") 7 num L 8 if num > a: 9 peint(num, “is a positive number”) 40 print("This is also aluays printed.") Inthe above example, aun > 0 is the test expression. The body of ic is executed only if this evaluates to True, When variable num is equal to 3, test expression is true and body inside body of ir is executed. If variable num is equal to -1, test expression is false and body inside body of i is skipped 4.2 Python if..lse Statement ‘The ir. .e1se statement evaluates vest express ion and will execute body of + only when test condition is True. IFthe condition is raise, body of e1se is executed, Indentation is used to ‘separate the blocks. Symtaxofituehe grep Body ait else: Body ofebe | t Test False t ' | woayore | [aby fe Program 4 print ("Positive") oa alae 6 print("Negetive number") Output 43 Python if..lif...else The £132 is short for else if It allows us to check for multiple expressions. Ifthe condition for i is alse, it checks the condition of the next eLit block and so on. If all the conditions are False, body of ebe is executed. Syntax of if..elif..clse iftest expression: Body of if elif test expression: Body of elif else: Body of else Only one block among the several condition, elif. ..else blocks is executed according to the ‘The i block can have only one cise block. But it can have multiple 214 blocks. Flowchart of if. .elif...lse Test False Expression of Y Test False Exprossion Body of if of elif br ! Body of elif Body of else Fig: Operation of ielf..else statement Hit-elif-else statement 1 2 3 num - 3.4 a> if num > 5 6 print("Positive number") ~ elif num == 0: it("Zero") PI + else: print(“Hegatiye number") Output When variable num is positive, Positive number is printed. If num is equal to 0, Zer9 is printed. If num is negative, Negative number is printed 4.4 Python Nested if statements ‘Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. This can get confusing, so must be avoided iff we can. Program Tn this program, vie input a number 4 # check if the number is positive or # negative or zero and display 4 # an appropriate message This time we use nested if num = float(input ("Enter number: ")) if mm >= 0: if num == 6: print("Zero”) else: print ("Positive number") alse: print (*legative number") Output 1 Enter a number: 5 Positive number Output 2 Enter a number: Hegative number 5, LOOPING STATEMENTS A loop is a sequence of instructions that is continually repeated until a specifie condition is reached. ‘The looping statements used in python are > for loop > while loop 4.1 for loop The for oop in Python is used to iterate over a sequence (list, tuple, string) or ober iterable abject. lerating over a sequence i called traversal Syntax of for Loop for val in sequence: Body of for Here, val is the variable that takes the value of the item inside the sequence on each iteration. Loop continues until we reach the las item in the sequence. The body of for lop is separated from the rest of the code using indentation, Flowchart of for Loop foreach item in. sequence Lost “ tem reached? Yes No Body of for Exit loopy # Program to find the sum of all numbers stored in a list 1 2 3 # List of numbers 4 numbers = [6, 5, 3, 8 4, 2, 5,4, 11] 5 6 8 # variable to store the sum sum = 0 9 # iterate over the List Jo for yal in numbers: AL sum = suméval 13° # Output: The sum is 48 14 print("The sum is", sum) 5.1.1 The range() function We can generate a sequence of numbers using cenge() fmetion. x numbers from 0 to 9 (10 numbers). ge (10) will generate We can also define the start, stop and step size as range (s default to 1 if not provided step size). step size This funtion does not store all the values in memory, it would be inefficient. So it remembers the stat, stop, step size and generates the next number on the go. To force this function to output all the items, we can use the function 11st ( The following example will clarify this. 4 range function in for Loop 2 #print numbers from 0 to 9 totally 10 value: 3+ for i in range(o, 10): 4 print (4) #print particular values from the list 8 pnint("The List values are:") 9 list1=[0,1,2,3.4,5,6,7,8,9] 10+ for Listd in range (3,8): 11 print (list) 5.2 for loop with else ‘for loop can have an optional else block as well. The 21se parts executed ifthe items in the sequence used infor loop exkauss, break statement can be used to stop a for oop. In such ease, the else parti ignored, Hence, a for bop’ else part runs if no break oceurs Here is an example to illustrate ths. For loop with else statenent digits = [0, 1, 5] for i in digits: printi) + else: print("Wo items Left.") Here, the for loop prints tents ofthe list until the loop exhausts. When the for loop exhausts, it executes the block of code in the else and prints “ No items left.” 5.3 while loop The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. ‘We generally use this loop when we don't know beforehand, the number of times to iterate Syntax of while Loop in Python hile test_expression: Body of while In while loop, test expression is checked first. The body of the loop is entered only if the _ expression evaluates fo tzue. Afler one iteration, the test expression is checked again, This process continues until the cest expression evaluates to False. tes In Python, the body of the while loop is determined through indentation. Body starts with indentation and the first unindented line marks the end Python interprets any non-zero value as True. tone and 0 are interpreted as Fase. Flowchart of while Loop Enter while loop X Test False Expression True Body of | while Exit loop. Figg operation of while loop 1 Program to add natural 2 # numbers upto 3H sum = 12e34..4n 4 5 # To take input from the user 5 m= Anc(inputC"Enter ni ")) 7 8 ff initialize sum and counter &9 sum = 0 Wo ind a 12> while bc nz 3 sum = sum + i 4 L- 4s. # update counter 15 16 # print the sum nt ("The sum is", sum) In the above program, the test expression will be e2se as long as our counter variable # is less than or equal to n (10 in our program), ‘We need to increase the value of counter variable in the body of the loop. This is very important (and mostly forgotten), Failing to do so will result in an infinite loop (never ending loop). Finally the result is displayed, 5.4 while loop with else ‘Same as that of for loop, we can have an optional e: se block with while loop as well ‘The cise partis executed if the condition in the while loop evaluates to Paise. The while loop can be terminated with a break slatement In such case, the ese part is ignored. Hence, a while loop's ese part runs if no break occurs and the condition is false. Here isan example to illustrate this 1 # Example to illustrate while loop with else 2 3 countar = 0 a 5 while counter < 3: 6 print("uhile loop executes” 7 = counter + 1 eo Here, we use a counter variable to print the string “While loop executes” three times. ‘On the fourth iteration, the condition in while becomes F21se. Hence, the ese part is executed and prints “Else executes” 6. LOOP CONTROL STATEMENTS In Python, break ,continue and pass statements can alter the flow ofa normal loop Loops iterate over a block of code until test expression is false, but sometimes we wish to terminate the current iteration or even the whole loop without checking test expression. The three loop control statements are ‘Break statement 4 Continue statement Pass statement G.1 Python break statement ‘The break statement terminates the loop containing it, Control of the program flows to the statement immediately after the body of the loop. If break statement is inside a nested loop (loop inside another loop), break will terminate the innermost loop. Syntax of break break Flowchart of break Exit Loop ‘The working of break statement in for loop and while loop is shown below. for var in sequence: # codes inside for loop if condition: break # codes inside for loop LP # codes outside for loop while test expression: # codes inside while Loop if condition: break # codes inside while Loop > # codes outside while loop Program # Use of break statement inside 1 2 3+ for val in “string”: 40 Af val == “t" 5 break 6 petirt(val) 8 Output print ("The end") In this program, we iterate through the "string" sequence. We cheek if the letter is "i which we break fiom the loop. Hence, we see in our output that all the letters up til printed, Afer that, the loop terminates. upon "i gets 46.2 Python continue statement The continue statement is used to skip the est of the code inside a loop forthe current iteration only. Loop does not terminate but continues on with the nex iteration Syntax of Continue continue Flowchart of continue Ener eop tLoop re Ep The working of continue statement in for and while loop is shown below. for var in sequence: # codes inside for loop if condition: continue # codes inside for loop # codes outside for loop while test expression: [> # codes inside while loop if condition: continue # codes inside while Loop # codes outside while loop Program Program to show the use of continue statement inside loops if val == "i": 4 2 3» for val in “string ae 5 continue 6 print (val) 8 print ("The end”) Output This program is same as the above example except the break statement has been replaced with continue. We continue with the loop, ifthe string is "", not executing the rest of the block. Hence, we see ‘in our output that all the letters except "i" gets printed. 6.3 pass statement In Python programming, pass is a null statement. The difference between a comment and pass statement in Python is that, while the interpreter ignores a comment entirely, cass is not ignored. However, nothing happens when pass is executed, It results into no operation (NOP). Syntax of pass pass We generally use it as a placeholder. Suppose we have a loop or a function that isnot implemented yet, but we want to implement it in the future. They cannot have an empty body. The interpreter would complain, So, we use the © statement to construct a body that does nothing. 1 2 sequence = {'p', 3+ for val in sequence 4 pass 12.Python Functions In Python, function is a group of related statements that perform a specific task. 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 code reusable, ® Python Functions Ax erin nets anim | eatin) Syntax of Function def functicn_nane(paraneters): docstring’ statement (s) Above shown is a function definition which consists of following components 1. Keyword def marks the start of function header. ‘A Tunction name to uniguely identify it. Function naming follows the same ruks of \writing identifiers in Python. Parameters (arguments) through which we pass values to function. They are optional ‘Acolon (:) to mark the end of funetion header. Optional documentation string (docstring) to desctibe what the function does. ‘One or more valid python statements that make up the function body, Statements must have same indentation level (usually 4 spaces). 7. An optional return statement to return a value from the function, ease Example of a function Ly def greet(name): 2 “*"Ihis functien greets to 3 the person passed in as 4 parameter 5 print("Hello, " + name +". Good morning!" 6 greet ("MAHADEVAN") Output Hello, \8HADEVAN, Good morning Function Call 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 finetion name with appropriate parameters. >>> greet (*Paull') Hello, Paul. Good morning! The return statement The return statement is used to exit a fimetion and go back to the place fiom where it was called. Syntax of return return [expression list] This statement can contain expression which gets evaluated and the value is returned. If there is no expression in the statement or the xeturn statement itself is not present inside a function, then the function will return the wore object For example: >>> print (greet ("Hay")) Hello, flay. Good morning! lone Here, None is the retumed value. Example of return 2+ def absolute velue( num) : 2 *wthis function returns the absclute 3 velue of the entered ranber + $+ iF mmo 6 return num 7 ele 8 ecurn ° 10 # output: 2 AL print (absolute_value(2)) 2 32 oxtputs 4 AA prit(abealute_value(-4)) ‘Output 14.1 Flow of execution When you are working with functions it is really important to know the order in. which statements are executed. This is called the flow of execution. Execution always begins at the first statement of the program. Statements are executed one at a time, in order, from top to bottom. Function definitions do not alter the flow of execution of the program, but remember that statements inside the function are not executed until the function is called. Function calls ate like a detour in the flow of execution. Instead of going to the next statement, the flow jumps to the first line of the called function, executes all the statements there, and then comes back to pick up where it left off def functionName(): SJ ‘When you read a program, don’t read from top to bottom. Instead, follow the flow of execution. This means that you will read the def statements as you are scanning from top to bottom, but you should skip the body of the function until you reach a point where that function is called. 14.2 Types of Functions Basically, we can divide functions into the following two types: 1. Built-in functions - Functions that are built into Python, 2. User-defined functions - Functions defined by the users themselves. 14.2.1 Built in Functions: The Python interpreter has a number of functions that are always available for use. These functions are called built-in functions. For example, pict () function prints the given object to the standard output device (screen) or to the text stream file. In Python 3.6 (latest version), there are 68 built-in functions. They are listed below alphabetically along with brief description BUILT IN ‘SL.NO | FUNCTION DESCRIPTION NAME 1. | abs) retums absolute value of a number 2 | all returns true when all elements in iterable is true 3 | any() Checks ifany Element ofan lterable is True 4. | ascii) Reiurns String Containing Printable Representation 5. | bing) ‘converts integer to binary Sing bool() Coverts a Value to Boolean bytearray() ‘returns array of given byte size 8 | bytes) returns immutable bytes object 9 | eallable() Checks ifthe Object is Callable 10. | chr) ‘Returns a Character (a string) rom an Integer TL, | elassmethod() | returns class method for given function 12. | compile() ‘Returns a Python code object 13. | complex() ‘Creates a Complex Number 14. | delat ‘Deletes Attribute From the Object 15. | dict) ‘Creates a Dictionary 14.2.2 User defined functions Functions that we define ourselves to do certain specific task are referred as user-defined functions. The way in which we define and call functions in Python are already discussed. Functions that readily come with Python are called built-in functions. Ifwe use functions written by others in the form of library it can be termed as library functions, All the other functions that we write on our owa fall under user-defined functions. So, our user~ defined function could be a library function to someone else. Advantages of user-defined functions 1. User-defined functions help to decompose a large program into small segments which makes program easy to understand, maintain and debug. 2. If repeated code occurs in a program. Function can be used to include those codes and ‘execute When needed by calling that function. 3. Programmers working on large project can divide the workload by making different functions Program 1 Program to dMlustrate 20H the use oF user-defined functions 3 4y def ade_numbers( x,y): 5 smsxty 6 return cum 7 8 um = 5 8 num = 6 40 AL print(*The sun 23", edd_numbers(num, nim2)) ‘Output The sum is 1a Here, we have defined the function ny adaition() which adds two numbers and retums the result, ‘This is our user-defined fumetion. We could have multiplied the two numbers inside our function (Gt all up to us). But this operation would not be consistent with the name of the fimction. It ‘would create ambiguity, Its always a good idea to name functions according to the task they perform, In the above example, ispuc ), peint() and toee () are built-in functions of the Python programming language 143 Function Arguments Tn user-defined function topic, we learned about defining a flnetion and calling it. Otherwise, the function call will result into an enor. Here is an example, Lv def greet(nane,nsg): 2 "This function greets to 3 the person with the provided message 4 print(*WelLo",name +", "+ msg) 5 6 greet(" MAHADEVAN," Good merning!") Output Hello vaHADEYAll, Good marning! Here, the function gzect () has two parameters, Since, we have called this function with two arguments, it runs smoothly and we do not get any error. If we call it with different number of arguments, the interpreter will complain. Below is a call to this function with one and no arguments along with their respective error messages. >>> greet("Honica”) # only one argunert TypeEnrer: greet() missing 1 required positional argument: 'ssg’ 14.4 Types of Function Arguments ‘Until now functions had fixed number of arguments. In Python there are other ways to define a function which can take variable number of arguinents, Three different forms of this type are deseribed below. 41. Default Arguments 2. Keyword Arguments 3. Arbitrary Arguments 14.4.1 Default Arguments Function arguments can have default values in Python. To provide a default value to an argument by using the assignment operator (=). Here is an example Program defsumla=2,b6): cath sutn(a=3,) In this funotion, the parameter n2n= does not have a deftult value and is required (mandatory) during a call Any number of arguments in a function can have @ default value. But once we have a default argument, all the arguments to its right must also have default values, This means to say, non->> #2 keynord arguments >>> greet(nane = “Bruce” msg = "Hay do you do?) >>> # 2 keynord arguments (out of orden) >>> greet(nsg = "Hay do you do?,name = ruce") >>> # L positional, 1 keyword argument: >>> greet("Bruce",msg = "Hoy do you do?") As we can see, we can mix positional arguments with keyword arguments during a function call ‘But we must keep in mind that keyword arguments must Follow positional arguments, ‘Having a positional argument after keyword arguments will result into errors. For example the function call as follows: greet (name="Bruce","Haw do you do?") Will result into error as: SyntaxError: non-keyword arg after keyword arg Program: def sum(s,b): cath print (c) sum{a=3,b=5) sum(a=10,b=15) output: 8 25 14.43 Arbitrary Arguments Sometimes, we do not know in advance the number of arguments that will be passed into a function, Python allows us to handle this kind of situation through function calls with arbitrary number of arguments, In the function definition we use an asterisk (*) before the parameter name to denote this kind of argument. Here is an example Program + def greet(‘names) : “""This function greets all ‘the person in the names tuple," # names is a tuple with argument: + For name in names privrt("HelLo” yname) wovaueune greetil"Mahadeven” .erdyasony" ,"Sathishlamar","\Vishalakshi") Output Hello Sehedevan Hello periyaseny Hello Sathishkumar Hello Vishalaks! Here, we have called the function with multiple arguments. These arguments get wrapped up into a tuple before being passed into the function, Inside the function, we use a for loop to retrieve all the arguments back. Return Values ‘The built-in functions we have used, such as abs, pow, int, max, and range, have produced results. Calling each of these functions generates a value, which we usually assign to a variable ‘or use as part of an expression. biggest = max(3, 7, 2,5) x=abs(3-11)+10 we are going to write more functions that return values, which we will call fruitful functions, for want of a better name, The first example is area, which returns the area of a circle with the given radius: def area(radius): b= 3.14159 * radiust#2 retum b We have seen the return statement before, but in a fruitful function the return statement includes a return value, This statement means: evaluate the return expression, and then retum it immediately as the result (the fruit) of this function. The expression provided can be arbitrarily complicated, so we could have written this function like this: def area(radius): retum 3.14159 * radius * radius (On the other hand, temporary variables like b above often make debugging easier. ‘Sometimes it is useful to have multiple return statements, one in each branch of a conditional. We have already seen the built-in abs, now we see how to write our own: def absolute_value(x) ifx<0: return -x_ else: retum x Another way to write the above function is to leave out the else and just follow the if condition by the second return statement | def absolute_value(x): 2 ifx<0: 3 retum-x 4 return x ‘Think about this version and convince yourself it works the same as the first one. Code that appears after a retum statement, or any other place the flow of execution can never reach, is called dead code, or unreachable code. Ina fruitful function, it is @ good idea to ensure that every possible path through the program hits aretum statement. The following version of absolute_value fails to do this: def bad_absolute_value(x): ifx<0: Tetum -x_ elifx> 0: retum x defbad_absolute_value(x): ifx<0: Tetum -x alif'x>0 retum x This version is not correct because if x happens to be 0, neither condition is true, and the function ends without hitting a return statement. In this case, the return value is a special value called None: >>> print(bad_absolute_value(0)) None Al Python functions return None whenever they do not return another value. It is also possible to use a return statement in the middle ofa for loop, in which case control immediately returns fiom the function. Let us assume that we want 2 function which looks through alist of words. I should retum the first 2-letter word. If there is not one, it should return the empty string: def find_first_2_ letter word(xs) for wd in xs: iflen(wd) = retum wd retum"" >>> find_first_2_letter_word({"This", "is" ee >>> find_first_2_letter_word({"T", "like", "cheese"]) “dead”, "parrot"]) Single-step through this code and convince yourself that in the first test case that we've provided, the function returns while processing the second element in the list: it does not have to traverse the whole list 12. PYTHON 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 We know that in Python, a function can call other functions. It is even possible for the function to call itself. These type of construct are termed as recursive functions, Follovving is an example of recursive funetion 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. Program 1 oe eS 4 be 6 8 9 Output # Factorial using Recursion def fact(x): if x==4 return else return (x ' fact(x-1)) num-int (input ("Enter the lambs print("The factorial of", num, » s", fact(num)) In the above example, caic_factorial () isa recursive functions as it ealls itself When we call this function with a positive integer, it will recursively call itself by decreasing the ‘number. Each function call multiples the number with the factorial of number 1 until the number is equal to one, This recursive call can be explained in the following steps. fact(4) # Ist call with 4 4* fect) #2nd call with 3 4*3* fact(2) 3rd call with 2 4°32 fact(1) # 4th call with | 4*3%2*1 — #retum fiom 4th call as umber=1 4*3*2 #retum from 3rd call 4*6 # return from 2nd call 4 # return from Ist call ‘Our recursion ends when the number reduces to 1. This is called the base condition. Every recursive function must have @ base condition that stops the recursion or else the function calls itself infinitely. Advantages of recursion 1. Recursive functions make the code look clean and elegant 2. Acomplex task can be broken down into simpler sub-problems using recursion. 3. Sequence generation is easier with recursion than using some nested iteration. Disadvantages of recursion 1. Sometimes the logic behind recursion is hard to follow through. 2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time. 3. Recursive functions are hard to debug. 11, Python Anonymous/Lambda Function In Python, anonymous function is a function that is defined without a name. While normal functions are defined using the cee keyword, in Python anonymous functions are defined using the 1anbaa keyword, Hence, anonymous functions are also called lambda functions. Lambda Functions A lambda function has the following syntax. Syntax of Lambda Function Jambda arguments; expression Lambda functions can have any number of arguments but only one expression. The expression is evaluated and retumed. Lambda functions can be used wherever function objects are required. Example of Lambda Function Hete is an example of lambda function that doubles the input value. # Program to show the use of lambda functions double = Lanbda x: x! 2 # output: 19 print (double(s)) Output Inthe above program, 1anbda x: x * 2 is the lambda function, Here x isthe argument and x + 2 is the expression that gets evaluated and returned, This function has no name. Itretums a function object which is assigned to the identifier double. We can now call it asa normal function, The statement double = lambda x: x * 2 is nearly the same as def doubk(x) return x * 2. Use of Lambda Function We use lambda functions when we require a nameless fiction for a short period of time In Python, we generally use it as an argument to a higher-order function (a fiction that takes in ‘other functions as arguments). Lambda functions are used along with built-in functions like filter |), map() ete. Example use with filter() ‘The £i1ter () function in Python takes in a function and a list as arguments, ‘The function is called with all the items in the list and a new list is retumed which contains tems for which the function evaluats to true, Here is an example use of iter |) function to filter out only even numbers froma list. 4 2 # Program to filter out only the even items from a List 3 4 my_list = [1, 5, 4, 6, 8, 11, 3, 12] 5 6 — new_list = list(filter(Lambda x: (x2 == 0) , my_list)) 7 8 # Output: [4, 6, 8, 12] 9 print(new_list) Output Example use with map() The nap () finetion in Python takes in a function and lst. The function is called with all the items in the list and a new list is returned which contains items returned by that function for each item. Here is an example use of map () function to double all the items in a list, 1 # Program to do h item in a List using map() : my_list = (1, 5, 4, 6 8 UM, 3, 12] ; new List = List(map(lambda x: x 2, my_list)) 7 ¥ output: [2, 10, 8, 12 16, 2% 6, 2) 8 print(new_list) Output

You might also like