UNIT III CONTROL FLOW, FUNCTIONS
3.1. CONDITIONALS:
3.1.1 BOOLEAN VALUES AND OPERATORS:
x != y
x is not equal to y
x > y
x greater than y
x<y
x less than y
x<=y
x less than or equal to
x>=y
x greater than or equal to
Boolean and Logical operators
1. and Operator:
TRUE
TRUE
TRUE
TRUE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
1. or Operator:
TRUE
TRUE
TRUE
TRUE
FALSE
TRUE
FALSE
TRUE
TRUE
FALSE
FALSE
FALSE
Example 3.1:
A python program to display the National holidays. For example: January 26-Republic day August 15-Indepependance day October 2-Gandhi Jayanthi* If user input is other than the given condition,Error will be displayed as “Invalid input”.
Program: print("Enter Month and Day") month=input() day=int(input()) if(month =="january" and day ==26): print ("republic day") elif(month =="august" and day ==15): print ("independence day") elif(month =="october" and day ==2): print ("Gandhi Jayanthi") else: print ("invalid input")
Output Enter Month and Day august 15 independence day
Example 3.2:
Number of days in a month varies from 30 to 31 days. Write a python program to read the name of the month and display corresponding days. If he input is other than the given month, then display error message as “Invalid”.
Program: import sys month=input("Enter the name of the month") if(month=="may" or month=="july" or month=="august"): print ("31") elif(month=="jun"): print ("30") else: print ("invalid")
Output Enter name of the month may 31
3.1.2. OPERATORS
i. Arithmetic Operators
ii. Comparison (Relational) Operators iii. Assignment Operators iv. Logical Operators v. Membership Operators vi. Identity Operators
i. Arithmetic operators
+ Addition
Adds values on either side of the operator.
a + b = 30
-Subtraction
Subtracts right hand operand from left hand operand.
a – b = -10
* Multiplication
Multiplies values on either side of the operator
a * b = 200
/ Division
Divides left hand operand by right hand operand
b / a = 2
% Modulus
Divides left hand operand by right hand operand and returns remainder
b % a = 0
** Exponent
Performs exponential (power) calculation on operators
a**b =10 to the power 20
// Floor Division
The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity) −
9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0
ii. Comparison Operators
== Equal
If the values of two operands are equal, then the condition becomes true.
(a == b) is not true.
!= Not Equal
If values of two operands are not equal, then condition becomes true.
(a != b) is true.
> Greater than
If the value of left operand is greater than the value of right operand, then condition becomes true.
(a > b) is not true.
<
If the value of left operand is less than the value of right operand, then condition becomes true.
(a < b) is true.
>=
If the value of left operand is greater than or equal to the value of right operand, then condition becomes true.
(a >= b) is not true.
<=
If the value of left operand is less than or equal to the value of right operand, then condition becomes true.
(a <= b) is true.
iii. Assignment and Compound Operators
= Assignment
Assigns values from right side operands to left side operand
c = a + b assigns value of a + b into c
+= Add & Assign
It adds right operand to the left operand and assign the result to left operand
c += a is equivalent to c = c + a
-= Subtract & Assign
It subtracts right operand from the left operand and assign the result to left operand
c -= a is equivalent to c = c - a
* = Multiply and Assign
It multiplies right operand with the left operand and assign the result to left operand
c _ = a is equivalent to c = c _ a
/= Divide and Assign
It divides left operand with the right operand and assign the result to left operand
c /= a is equivalent to c = c / ac /= a is equivalent to c = c / a
%= Modulus & Assign
It takes modulus using two operands and assign the result to left operand
c %= a is equivalent to c = c % a
** = Exponent & Assign
Performs exponential (power) calculation on operators and assign value to the left operand
c ** = a is equivalent to c = c ** a
iv. Logical Operators
and Logical AND
If both the operands are true then condition becomes true.
(a and b) is true.
or Logical OR
If any of the two operands are non-zero then condition becomes true.
(a or b) is true.
not Logical NOT
Used to reverse the logical state of its operand.
Not(a and b) is false.
v. Membership Operators
in
True if value/variable is found in the sequence
5 in numlist, returns true if 5 is in the numlist.
not in
True if value/variable is not found in the sequence
5 in numlist, returns false if 5 is not in the numlist.
vi. Identity Opertors
is
Evaluates to true if the variables on either side of the operator point to the same object and false otherwise.
x is y, here is results in 1 if id(x) equals id(y).
is not
Evaluates to false if the variables on either side of the operator point to the same object and true otherwise.
x is not y, here is not results in 1 if id(x) is not equal to id(y).
3.1.3. CONDITIONAL STATEMENTS
Available conditional statements in python are
i. if statement
ii. if..else statement
iii. if..elif..else statement
iv. Nested if statement
Rules for conditional statements:
3.1.3.1. ‘if’ STATEMENT (CONDITIONAL STATEMENT)
Example 3.3: Python program to check whether a person is eligible for vote.
Program: print("Enter Your age") n=int(input()) if(n>=18): print("Eligible for voting") Output Enter Your age 21 Eligible for voting
3.1.3.2. ‘if...else’ STATEMENT(ALTERNATIVE CONDITIONAL STATEMENT)
Syntax of if...else
Example 3.4:
Python program to checks if the number is positive or negative
Program num = 3 if num >= 0: print("Positive or Zero") else: print("Negative number")
Output Positive or Zero
Example 3.5:
Program
Output
3.1.3.3. ‘if...elif...else’(CHAINED CONDITIONAL STATEMENT)
Syntax of if...elif...else
Example 3.6:
Python program to check if the number is positive or negative or zero
Program num = 3.4 if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number")
Output
Example 3.7:
Program
Output
3.1.3.4. NESTED CONDITIONAL
Example 3.8:
Python program to check if the number is positive or negative or zero using nested if.
Program
Output
3.2. REPETITION STRUCTURE/LOOPING/ITERATIVE STATEMENTS
i. ‘for‘ Statement ii. ‘while’ Statement
3.2.1. ‘for’ LOOP
Syntax of for Loop
Example 3.9:
Python Program to find the sum of all numbers stored in a list
Program #number list numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] sum = 0 for val in numbers: sum = sum+val print("The sum is", sum) Output The sum is 48
3.2.2. ‘while’ LOOP:
Syntax
Example 3.10:
Python program using while Loop to add natural numbers upto n
Program
Output
In the above program, the test expression will be True as long as our counter variable i is less than or equal to n (10 in our program).
while loop with else
Example 3.11:
Python program to illustrate the use of else statement with the while loop
Program
Output
Difference between while and for loop
Indefinite loop
Definite loop
The exit condition will be evaluated again and execution resumes from the top(repeatedly executes a set of code)
The for is to iterate over a sequence (List, Tuple and dictionary etc)
3.2.3. UNCONDITIONAL STATEMENTS
i. Break
ii. Continue
iii. Pass
i. Python break statement
Syntax of break
Example 3.12:
Python program to illustrate break statement inside loop
Program
Output
Example 3.13:
Python program to demonstrate break
Program
Output
ii. Python continue statement
-[] The continue statement is used to skip the rest of the code inside a loop for the current iteration only. -[] Loop does not terminate but continues on with the next iteration.
Syntax of Continue
Example 3.14:
Python Program to show the use of continue statement inside loops
Program
Output
Example 3.15:
Python Program to show the use of continue statement inside loops
Program
Output
iii. Pass STATEMENT
Syntax of pass
Example 3.16:
Python program to illustrate pass
Program
Output
Example 3.17:
Program
Output
3.3. FRUITFUL FUNCTIONS: RETURN VALUES, PARAMETERS, LOCAL AND GLOBAL SCOPE, FUNCTION COMPOSITION, RECURSION
3.3.1. Functions
i. Creating a Function
Syntax
Example 3.18:
ii. Calling a Function To call a function, use the function name followed by parenthesis.
Example 3.19:
Program
Output
iii. Parameters
Example 3.20:
Program
Output
iv. Default Parameter Value
Example 3.21:
Program
Output
3.3.2 Return Values
Example 3.22:
Program
Output
3.3.3 Function Arguments
The types of formal arguments are:
i. Required arguments
Example 3.23:
Program
Output
ii. Keyword arguments
Example 3.24:
Program
Output
iii. Default arguments
Example 3.25:
Program
Output
iv. Variable-length arguments
Syntax:
An asterisk is placed before the variable name that holds the values of all non keyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call.
Example 3.26:
Program
Output
3.3.4. Scope of Variables
Global vs. Local variables
Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.
This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions.
When you call a function, the variables declared inside it are brought into scope.
Example 3.27:
Program
Output
3.3.5. Function composition or Anonymous Functions
Function composition is the way of combining the functions
These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.
Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because lambda requires an expression
Syntax
Example 3.28:
Program
Output
3.3.6. Recursive Function:
Recursion is the process of the function call by itself.
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.
Example - 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 12345*6 = 720.
Example 3.29:
Program def calc_factorial(x): '''This is a recursive function to find the factorial of an integer''' if(x == 1): return 1 else: return (x * calc_factorial(x-1))
Output
In the above example, calc_factorial() is a recursive functions as it calls itself.
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.
calc_factorial(4) # 1st call with 4
calc_factorial(3) # 2nd call with 3
3 * calc_factorial(2) # 3rd call with 2
3 _ 2 _ calc_factorial(1) # 4th call with 1
3 _ 2 _ 1 # return from 4th call as number=1
3 * 2 # return from 3rd call
6 # return from 2nd call # return from 1st call
Our recursion ends when the number reduces to 1. This is called the base condition.
Every recursive function must have a base condition that stops the recursion or else the function calls itself infinitely.
Advantages of recursion
Recursive functions make the code look clean and elegant.
A complex task can be broken down into simpler sub-problems using recursion.
Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of recursion
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 functions are hard to debug.
3.4. STRINGS
A string is a sequence of characters. You can access the characters one at a time with the bracket operator:
Example 3.30:
Program
Output The letter present at index 1 is: a The second statement selects character number 1 from fruit and assigns it to letter. The expression in brackets is called an index. The index indicates which character in the sequence you want (hence the name). Always index starts from 0. The value of the index has to be an integer. Otherwise you get:
Example 3.31:
Program fruit = 'banana' letter = fruit[1.5] print("The letter present at index 1 is:",letter) Output Traceback (most recent call last): File "c:\users\administrator\mu_code\or_op.py", line 2, in letter = fruit[1.5] TypeError: string indices must be integers
3.4.1. String Lengths
len() is a built-in function that returns the number of characters in a string.
Example 3.32:
Program
Output
To get the last letter of a string, you might be tempted to try something like this:
Example 3.33:
Program fruit = "banana" length = len(fruit) last = fruit[length] print("The last letter in fruit is:",last) Output
The reason for the IndexError is that there is no letter in 'banana' with the index 6. Since we started counting at zero, the six letters are numbered 0 to 5. To get the last character, you have to subtract 1 from length:
Alternatively, you can use negative indices, which count backward from the end of the string. The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on.
3.4.2. String slices
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
The operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth” character, including the first but excluding the last. If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string: fruit = 'banana' print(fruit[:3]) #Prints 'ban' print(fruit[3:] #Prints 'ana' If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks:
An empty string contains no characters and has length 0, but other than that, it is the same as any other string.
3.4.3. Strings are immutable
It is tempting to use the [] operator on the left side of an assignment, with the intention of changing a character in a string. For example:
The “object” in this case is the string and the “item” is the character you tried to assign. For now, an object is the same thing as a value, but we will refine that definition later. An item is one of the values in a sequence. The reason for the error is that strings are immutable, which means you can’t change an existing string. The best you can do is create a new string that is a variation on the original:
This example concatenates a new first letter onto a slice of greeting. It has no effect on the original string.
3.4.4. String methods
A method is similar to a function—it takes arguments and returns a value—but the syntax is different. For example, the method upper takes a string and returns a new string with all uppercase letters: Instead of the function syntax upper(word), it uses the method syntax word.upper(). word = 'banana' new_word = word.upper() print(new_word) #Prints BANANA
This form of dot notation specifies the name of the method, upper, and the name of the string to apply the method to, word. The empty parentheses indicate that this method takes no argument. A method call is called an invocation; in this case, we would say that we are invoking upper on the word. As it turns out, there is a string method named find that is remarkably similar to the function we wrote:
In this example, we invoke find on word and pass the letter we are looking for as a parameter.
i. find method
Actually, the find method is more general than our function; it can find substrings, not just characters: word = 'banana' print(word.find('na')) #Prints 2
It can take as a second argument the index where it should start: word = 'banana' print(word.find('na', 3)) # Prints 4
And as a third argument the index where it should stop:
This search fails because b does not appear in the index range from 1 to 2 (not including 2).
ii. String comparison
The relational operators work on strings. To see if two strings are equal: if(word == 'banana'): print('All right, bananas.') Other relational operations are useful for putting words in alphabetical order:
Python does not handle uppercase and lowercase letters the same way that people do. All the uppercase letters come before all the lowercase letters, so:Your word, Pineapple, comes before banana. A common way to address this problem is to convert strings to a standard format, such as all lowercase, before performing the comparison. Keep that in mind in case you have to defend yourself against a man armed with a Pineapple.
iii. Indexing
Individual characters in a string can be accessed using subscript([ ]) operator. The expression in bracket is called as Index.
iv. Traversing a String
A string can be traversed by accessing characters from one index to another.
0
1
2
3
4
5
-6
-5
-4
-3
-2
-1
3.4.4 . String module
-[] The string module consists of number of useful constants,classes and functions -[] These functions are used to manipulate strings -[] Some constants are defined in string module are: + string.ascii_lowercase - Refers all lower case letters. Example: a-z + string.ascii_uppercase - Refers all upper case letters. Example: A-Z + string.digits - Refer digits from 0-9 + string.uppercase - A string that has all the characters that are considered upper case letters Example: A-Z + string.whitespace - A string that has all characters that are considered white space like space,tab etc
Example: Hello world Hai Ajay Output: HelloworldHaiAjay
Example 3.34: Program that use different string methods
Program
Output
3.4.5. Example Programs:**
1. Traversing a string
Program message="hello!" index=0 for i in message: print("message[",index,"]=",i) index+=1 Output
2. String operations
Program
Output
3. Concatenate two strings
Program
Output
4. Append a string
Program
Output Enter the String to Concatenate:World HelloWorld 5. String slices
-[] A substring of a string is called a slice -[] A slice operation is used to refer the subpart of strings -[] The subset of a string can be taken from string by using [ ] operator
Example 1: Positive Indexing/Slicing
Program
Output
Example 2: Negative Indexing/Slicing
Program str="python" print("str[-1]=",str[-1]) print("str[-6]=",str[-6]) print("str[-2:]=",str[-2:]) print("str[:-2]=",str[:-2]) print("str[-5:-2]=",str[-5:-2]) Output
Example:3 Program
Output
3.4.6. String functions and methods
-[] Python supports many build-in methods to manipulate strings -[] A method is like a function
1
capitalize()
Capitalizes first letter of string
str=”hello” print(str.capitalize())
2
count(str,beg,end)
Count the number of times str occurs in a String
str=”he” m=”hellohellohello” print(m.count(str,0,len(m))
3
endwith(suffix,beg,end)
Check the string is end with given end string
m=”she is my friend” print(m.endwith(“end”,0,len(m))
4
startwith(prefix,beg,end)
Check the string starts with given string
m=”the world” print(m.startwith(“th”,0,len(m))
5
find(str,beg,end)
Check if the str is present in the string
m=”she is my friend” print(m.find(“my”,0,len(m))
6
isalpha()
Return true,if the string contain only alphabet
m=”jamesbond007” print(m.isalpha())
7
isdigit()
Return true,if the string contain only digit
m=”007”print(m.isdigit())
8
isalnum()
Return True,if string contain both alphabets and number
m=”james007” print(m.isalnum())
9
islower()
Returns true,if string contain only lower case
m=”hello” print(m.islower())
10
isupper()
Returns true,if string contain only upper case
m=”hello” print(m.isupper())
11
len(string)
Returns the length of the string
str=”hello” print(len(str))
12
lower()
Convert all the character into lowercase
m=”HELLO” print(m.lower())
13
upper()
Convert all the character into uppercase
m=” hello” print(m.upper())
14
strip()
Remove all the white space
m=”he llo” print(m.strip())
15
max(str)
Returns highest alphabetic character(ASCII value)
m=”hello zuzu” print(max(m))
16
min(str)
Returns the lowest alphabetical character
m=”hello zuzu” print(min(m))
17
split(delim)
Returns the list of substrings separated by the specified delimiter
m=”hello,hai,sai” print(m.split(‘,’))
Last updated