Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained conditional (if- elif -else); Iteration: state, while, for, break, continue, pass; Fruitful functions: return values, parameters, scope: local and global, composition, recursion; Strings: string slices, immutability, string functions and methods, string module; Lists as arrays. Illustrative programs: square root, gcd , exponentiation, sum the array of numbers, linear search, binary search
BOOLEAN VALUES Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false: None False Zero of any numeric type, for example, 0, 0L, 0.0, 0j. Any empty sequence, for example, ‘’, (), []. Any empty mapping, for example, {}.
Boolean Operations (and, or, not)
OPERATORS Operators are the constructs (operator) which can manipulate the value of operands. Consider the expression 4 + 5 = 9. Here , 4 and 5 are called operands and + is called operator.
DECISION MAKING The execution of the program taking action according to the conditions. This concept is also known as Conditional statements or Branching statements . Python programming language provides following types of decision making statements.
Types of Conditional statements if statements (conditional) if-else statements (alternative) if- elif -else (chained conditional) Nested Conditional
if statements (conditional)
Example a=10 if ( a>9): print(“A is Greater than 9”) Output A is Greater than 9
If... Else Statement Flow chart
if...else Example 20 Example: a=10 b=20 if(a>b): print(“A is Greater than B”) else: print(“B is Greater than A”) Output: B is Greater than A
The Elif Else Statement Flow chart
Example num = -3 if( num > 0): print(“Positive number”) elif (num == 0): print(“Zero”) else: print(“Negative number”) Output: Negative number
Nested Conditionals Syntax: if (condition1) : if (condition2): statements else : statements else: statements
Example: num = float(input(“Enter a number: “)) if (num >= 0): if (num == 0): print(“Zero”) else: print(“Positive number”) else: print(“Negative number”) Output : Enter a number: 5 Positive number
ITERATION A loop statement allows us to execute a statement or group of statements multiple times. Repeated execution of a set of statements is called iteration. Types while loop for loop nested loop
While Loop A while loop statement executes a block of statement again and again until the condition will occur false . It tests the condition before executing the loop body so this technique is known as Entry controlled loop.
While Loop
Example: count = 0 while (count < 5): print (“The count is:”%count) count = count + 1 print “Good bye!” Output The count is: 0 The count is: 1 The count is: 2 The count is: 3 The count is: 4 Good bye!
For Loop : Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
Example: #List of numbers number=[3,2,5,7,9,1,4,6,8] #variable to store the sum total=0 for item in number: total= total+item print(“total = %d” %total) Output: total= 45
Nested Loops - Python programming language allows using one loop inside another loop.
Example program to print range values print(“first loop values”) for x in range(5): print(x) print(“second loop values”) for x in range(3,6): print(x) print(“third loop values”) for x in range(3,8,2): print(x) Output: first loop values 1 2 3 4 second loop values 3 4 5 Third loop values 3 5 7
Iterating by Sequence Index - An alternative way of iterating through each item is by index offset into the sequence itself . Example fruits = [‘banana’, ‘ apple ’, ‘ mango ’] for index in range( len (fruits)): print (“Current fruit :”% fruits[index] ) print “Good bye!” Output Current fruit : banana Current fruit : apple Current fruit : mango Good bye!
Break Statement Terminates the loop statement and transfers execution to the statement immediately following the loop. The break statement can be used in both while and for loops.
Break
Example for letter in ‘Python’: if ( letter == ‘h’): break print (“Current Letter : %s” %letter) Output Current Letter : P Current Letter : y Current Letter : t
Continue Statement It returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. The continue statement can be used in both while and for loops.
Continue Statement
Example: for val in “string” : if( val ==‘ i ’): continue print( val ) print(“the end”) Output: s t r n g the end
Pass Statement The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. It execute nothing. It is a null statement. Difference between a comment and pass statement in python is that, interpreter ignores a comment entirely but not the pass statement. Syntax: pass
Example for letter in ‘Python’: if letter == ‘h’: pass print ‘This is pass block’ print ‘Current Letter :’, letter Output Current Letter : P Current Letter : y Current Letter : t This is pass block Current Letter : h Current Letter : o Current Letter : n
FRUITFUL FUNCTIONS: Functions that return values are sometimes called fruitful functions. In many other languages, a function that doesn’t return a value is called a procedure, but we will stick here with the Python way of also calling it a function, or if we want to stress it, a non-fruitful function.
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. Example biggest = max(3, 7, 2, 5)x = abs(3 - 11) + 10
Parameters Parameter -- Data sent to one function from another. Types of parameter: Formal parameter -- The parameter defined as part of the function definition. Example: def add(x1,x2): here x1,x2 are formal parameter Actual Parameter -- The actual data sent to a function. It’s found in the function call. Example:add ( a,b ) here a,b are actual parameter
Pass-by-value parameter passing Pass-by-value parameter passing-- the value of the actual parameter is copied to the formal parameter. In Python, scalar values are sent by-value. Lists and other objects are sent by reference. def processNumber (x): x=72 return x+3 # main y=54 res = processNumber (y)
Pass-by-Reference parameter passing It provide reference to the actual parameter is sent to the function. When we trace a program, and a list is sent, we don’t copy the list to the actual parameter box, we draw an arrow from formal to actual. Example: def processList (list): list[1]=99 # main aList = [5,2,9] processList ( aList )
Scope of the Variable – Variable scope and lifetime Scope of a variable specifies the part of a program where a variable is accessible . Lifetime of a variable specifies the time period in which the variable has valid memory. Python uses LEGB Rule for Scope resolution. L ocal -> E nclosed -> G lobal -> B uilt-in
LEGB Rule: Local can be inside a function or class method. Enclosed can be its enclosing function.e.g . if a function is wrapped inside another function. Global refers to the uppermost level of the executing script itself and Built-in are special names that python reserves for itself
Variable: A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source code ,outside all functions. It will be visible through out the program. A local variable is declared within the body of a function or a block. It is accessible only inside the function and gets deleted at the end of function.
Example:Variables in different scopes: # This is a global variable a = 0 if a == 0: # This is still a global variable b = 1 def my_function (c): # this is a local variable d = 3 print(c) print(d) # Now we call the function, passing the value 7 as the first and only parameter my_function (7) # a and b still exist print(a) print(b) # c and d don’t exist anymore -- these statements will give us name errors! print(c) print(d)
Scope rules in function # global scope a=10 def func (b): #local scope c= a+b return( c ) z= func (1) print(z)
Global and local Variables in Functions Nonlocal Variables: Python3 introduced nonlocal variables as a new kind of variables. nonlocal variables have a lot in common with global variables. One difference to global variables lies in the fact that it is not possible to change variables from the module scope, i.e. variables which are not defined inside of a function, by using the nonlocal statement. Example def f(): global x print(x) x = 3 f() Output: 3
We will change “global” to “nonlocal” in the following program: def f(): nonlocal x print(x) x = 3 f() Output: File “example1.py”, line 2 nonlocal x SyntaxError : no binding for nonlocal ‘x’ found
Function Composition It is the ability to call one function from within another function. It is a way of combining functions such that the result of each function is passed as the argument of the next function. Example: Distance between two points of a circle Sqrt ((x2-x1)**2 +(y2-y1)**2)
Distance between two points of a circle import math def distance(x1,y1,x2,y2): result= math.sqrt (((x2-x1)**2)+((y2-y1)**2)) return result xc =input(“enter x1 value:”)) yc =input(“enter y1 value:”)) xp =input(“enter x2 value:”)) yp =input(“enter y2 value:”)) print(distance( xc,yc,xp,yp ))
Boolean functions Functions can return booleans , which is often convenient for hiding complicated tests inside functions. They are often used in conditional statements. Example def is_divisible (x, y): if x % y == 0: return True else: return False is_divisible (6, 4) Output: False
Recursion Recursion is a way of programming in which a function calls itself again and again until a condition is true. A Recursion function calls itself and has a termination condition. Advantage: Recursive functions make the code look clean and elegant. A complex task can be broken down into simpler sub-problems using recursion. Disadvantage: Sometime it is difficult to understand the logic It is expensive Hard to debug
Example: def factorial(n): if (n == 0): return (1 ) else: return (n* factorial(n-1)) n=input(“Enter a number:”) print(“factorial= %d”%n) Output: Enter a number :5 Factorial=120
STRINGS String are sequence of character enclosing with quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. Example var1 = ‘Hello World!’ var2 = “Python Programming”
Accessing values in strings To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. Example var1 = ‘Hello World!’ var2 = “Python Programming” print (“var1[0]: “, var1[0]) print (“var2[1:5]: “, var2[1:5]) Output var1[0]: H var2[1:5]: ytho
String formatting operator Example print (“My name is %s and weight is %d kg!” % (‘Zara’, 21)) Output My name is Zara and weight is 21 kg!
String formatting operator
Triple Quotes The syntax for triple quotes consists of three consecutive single or double quotes. Example: para_str = “””this is a long string that is made up of several lines and non-printable characters such as TAB ( \t ) and they will show up that way when displayed.NEWLINEs within the string, whether explicitly given like this within the brackets [ \n ], or just a NEWLINE withinthe variable assignment will also show up.“”” print( para_str ) Output: this is a long string that is made up ofseveral lines and non-printable characters such asTAB ( ) and they will show up that way when displayed.NEWLINEs within the string, whether explicitly given likethis within the brackets [ ], or just a NEWLINE withinthe variable assignment will also show up.
String Slices The “slice” refer to sub-parts of sequences, typically strings and lists. The slice s[ start:end ] is the elements beginning at start and extending up to but not including end Example : s = “Hello” s[1:4] is ‘ell’ s[1:] is ‘ ello ’ s[:] is ‘Hello’ s[1:100] is ‘ ello ’ s[-1] is ‘o’ s[-4] is ‘e’ s[:-3] is ‘He’ s[-3:] is ‘ llo ’
String are Immutable Strings are immutable, which means you cannot change an existing string. Greeting = “Hello, world!” newGreeting = ‘J’ + greeting[1:] print( newGreeting ) print(greeting) # same as it was Output Jello , world! Hello, world!
String Functions and Methods S.NO Methods Description 1 capitalize() Capitalizes first letter of string 2 isalnum () Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise. 3 isalpha () Returns true if string has at least 1 character and all characters are alphabetic and false otherwise. 4 isdigit () Returns true if string contains only digits and false otherwise. 5 islower () Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise. 6 isupper () Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise. 7 len (string) Returns the length of the string
LISTS AS ARRAY List basics A list in Python is just an ordered collection of items which can be of any type. myList =[1,2,3,4,5,6]
Comprehensions A comprehension is roughly speaking just an expression that specifies a sequence of values think of it as a compact for loop. In Python a comprehension can be used to generate a list. The simplest form of a list comprehension is [expression for variable in list] Example To create the list equivalent of a ten-element array you could write: myList =[0 for i in range(10)] myList [ i ]=something
Example: myList =[i for i in range(10)] sets myList to [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] and myList=[i*i for i in range(10)] sets myList to [0, 1, 4, 9, 16, 25, 36, 49, 64, 81].
Two dimensions for i in range( len ( myArray )): for j in range( len ( myArray [ i ])): print ( myArray [ i ][j])
Illustrative Program: GCD of a number a= int (input(“enter the value for a:”)) b= int (input(“enter the value for b:”)) result = a%b while result !=0: a=b b=result result= a%b print(“\n GCD of given no. is %d” % (b)) Output: enter the value for a:12 enter the value for b:36 GCD of given no. is 12
SQUARE ROOT OF A NUMBER print(“Square Root Program”) num = input(“Enter a number: “) number = float(num) number_sqrt = number ** 0.5 Print(“Square Root of %d is %0.2f” %(number, number_sqrt )) Output: Square Root Program Enter a number:25 Square Root of 25 is 5.00
Sum the array of numbers def listsum ( numList ): if len ( numList ) == 1: return numList [0] else: return numList [0] + listsum ( numList [1:]) print( listsum ([1,3,5,7,9])) Output: 25
Linear search i =0 j=0 count=0 list=[] N= int (input("Enter the no. of elements")) while i <N: item= int (input("Enter your %d elements to the list:"%(i))) list. append(item) i =i+1 search= int (input("Enter the element to search:")) while j<N: if(search==list[j]): count=1 j=j+1 if(count==1): print("The element %d is present in the list"%search) else: print("The element %d is not present in the list"%search)
Binary search def binary_search ( sortedlist,n,x ): start = 0 end = n - 1 for i in sortedlist : while(start <= end): mid = int ((start + end)/2) if (x == int ( sortedlist [mid])): return mid elif (x < int ( sortedlist [mid])): end = mid - 1 else: start = mid + 1 return -1 n = int (input("Enter the size of the list: ")) sortedlist = [] for i in range(n): sortedlist.append (input()) print( sortedlist ) x = int (input("Enter the number to search: ")) position = binary_search ( sortedlist,n,x ) if(position != -1): print("Entered number %d is present at position: %d"%( x,position )) else: print("Entered number %d is not present in the list"%x)
Exponentiation Program base= int (input('Enter the base value:')) exp= int (input('Enter the exponent value:')) res=1 for _ in range(exp): res=res*base print("\n Exponentiation using loop:",res) # Direct method to find Exponentiation factor=base ** exp print("\ nFactor is:",factor)