




























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
Study Notes on Control Flow and Functions
Typology: Study notes
1 / 36
This page cannot be seen from the preview
Don't miss anything!
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, local and global scope, function composition, recursion; Strings: string slices,immutability, string functions and methods, string module; Lists as arrays. Illustrative programs: square root, gcd, exponentiation, sum an array of numbers, linear search, binary search.
Boolean values:
Boolean values are the two constant objects False and True. They are used to represent truth values (other values can also be considered false or true).
Remember that the built-in type Boolean can hold only one of two possible objects: True or False
The built-in function bool() can be used to cast any value to a Boolean, If the value can be interpreted as a truth value.
The Bool() function return the value as False and True,respectively
The syntax of bool is :
Bool ([value])
Example
x= 1<x True 10<x False 3>x True 2==x True
Operators:
Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.
For example:
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output of the operation.
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic Operators
Arithmetic Operators perform various arithmetic calculations like addition, subtraction, multiplication, division, %modulus, exponent, etc. There are various methods for arithmetic calculation in Python like you can use the eval function, declare variable & calculate, or call functions.
Arithmetic operators in Python
Operator Meaning Example
% Modulus - remainder of the division of left operand by the right
Example : For arithmetic operators we will take simple example of addition where we will add two-digit 4+5=
x= 4
y= 5
print x + y
The output of this code is "9."
Similarly, you can use other arithmetic operators like for multiplication(*), division (/), substraction (-), etc.
Comparison(Relational) Operators
These operators compare the values on either side of the operand and determine the relation between them. It is also referred as relational operators. Various comparison operators are ( ==, != , <>, >,<=, etc)
Comparison operators in Python
/= It divides left operand with the right operand and assign the result to left operand
c /= a is equivalent to c = c / a %= It takes modulus using two operands and assign the result to left operand
c %= a is equivalent to c = c % a **= Performs exponential (power) calculation on operators and assign value to the left operand
c **= a is equivalent to c = c ** a
//= It performs floor division on operators and assign value to the left operand
c //= a is equivalent to c = c // a
Example : Python assignment operators is simply to assign the value, for example
a = 21 b = 10 c = 0
c = a + b print "Line 1 - Value of c is ", c
c += a print "Line 2 - Value of c is ", c c *= a print "Line 3 - Value of c is ", c c /= a print "Line 4 - Value of c is ", c c = 2 c %= a print "Line 5 - Value of c is ", c c **= a print "Line 6 - Value of c is ", c c //= a print "Line 7 - Value of c is ", c
When you execute the above program, it produces the following result:
Line 1 - Value of c is 31 Line 2 - Value of c is 52 Line 3 - Value of c is 1092 Line 4 - Value of c is 52 Line 5 - Value of c is 2 Line 6 - Value of c is 2097152 Line 7 - Value of c is 99864
Logical Operators
Logical operators in Python are used for conditional statements are true or false. Logical operators in Python are AND, OR and NOT. For logical operators following condition are applied.
For AND operator – It returns TRUE if both the operands (right side and left side) are true
For OR operator- It returns TRUE if either of the operand (right side or left side) is true For NOT operator- returns TRUE if operand is false
Logical Operators in python
Operator Meaning Example Logical AND If both the operands are true then condition becomes true.
(a and b) is true.
Logical OR If any of the two operands are non- zero then condition becomes true.
(a or b) is true.
Logical NOT Used to reverse the logical state of its operand.
Not(a and b) is false.
Example
a = True
b = False
print(('a and b is',a and b))
print(('a or b is',a or b))
print(('not a is',not a))
Output
a and b is False
a and b is True
not a is False
Bitwise Operators
Bitwise operators are used to perform bit operations. All the decimal values will be
converted into binary values (sequence of bits i.e 0100, 1100, 1000, 1001 etc) and
bitwise operators will work on these bits such as shifting them left to right or converting
bit value from 0 to 1 etc. Below table shows the different Python Bitwise operators and
their meaning.
List of Bitwise Operators
Binary AND(&)
Binary OR(|)
Binary XOR(^)
Binary One‟s Complement(~)
Binary Left-Shift(<<)
Binary Right-Shift(>>)
Decision Control Statements
The decision control statements are the decision making statements that decides the order of execution of statements based on the conditions. In the decision making statements the programmer specify which conditions are to be executed or tested with the statements to be executed if the condition is true or false.
Decision Control Statements are classified into
Selection or Conditional Branching Statements are classified into
Looping Structures or Iterative Control Statements are classified into
SELECTION or CONDITIONAL BRANCHING STATEMENTS
Conditional (if)
Conditional statements give us the ability to check conditions and change the behaviourof the program accordingly.
The syntax for if statement:
if <test_expression>:
Flowchart:
Example:
x= if x> 0 :
print('x is positive')
Alternative execution (if… else)
A second form of the if statement is alternative execution , in which there are
two possibilities and the condition determines which one gets executed
The syntax for if… else statement:
if <test_expression>: <body_1> else: <body_2>
Flowchart:
Example:
x=
if x%2 == 0 :
print('x is even')
else :
print('x is odd')
The conditional statement is written within another conditional statement. This is called nested conditionals. Any number of conditional statements can be nested inside one another
syntax for Nested conditionals statement:
if test expression:
Body of if
else:
if test expression:
Body of if
else:
if test expression:
Body of if
:
else:
Body of else
Flowchart
Example
a= b= if a == b:
print('a and b are equal')
else:
if a < b:
print('a is less than b')
else:
print('a is greater than b')
State of a variable
It is possible to have more than one assignment for the same variable. The value which
is assigned at the last is given to the variable. The new assignment makes an existing
variable assigned with new value by replacing the old value. For example, consider the
following Example.
Example 1:
x=
y=
x=
print x
print y
The result is
4
3
The variable x is first assigned with 5 then it is assigned with 4. The last assignment
statement x=4 replaces the old value of x (x=5).
Example 2:
x = 5
y = x # x and y are now equal
x = 3 # x and y are no longer equal Print x
Print y
The result is
The result is 3 5 Here the variable x is assigned with the value 5. The variable y is assigned with the value of x. Finally, the value of x is updated to 3. So, the value 3 is assigned to x. This is called state of the variable.
The while Loop
A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.
print(range(5))
print(list(range(5)))
print(list(range(2, 5)))
print(list(range(2, 15, 3)))
Result:
range (0, 5)
[0, 1, 2, 3, 4]
[2, 3, 4]
[2, 5, 8, 11, 14]
Python 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)
The result is:
First loop values
0
1
2
3
4
Second loop values
3
4
5
Third loop values
3
5
Nested Loop
Python programming language allows to use one loop inside another loop. Following section shows few examples to illustrate the concept.
Syntax for Nested for Loop
foriterating_var in sequence:
foriterating_var in sequence:
statements(s)
statements(s)
Syntax for Nested while Loop
while expression:
while expression:
statement(s)
statement(s)
Example
i =
while(i <20):
j =
while(j <=(i/j)):
ifnot(i%j):break
j = j +
if(j > i/j):print i," is prime"
i = i +
print"Good bye!"
Output
2 is prime
3 is prime
5 is prime
The continue statement in Python 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.
Syntax for Continue
For var in sequence:
If condition:
Continue
Example 1 :
for letter in'Python':
if letter =='h':
continue
print'Current Letter :', letter
Output :
Current Letter : P Current Letter : y
Current Letter : t Current Letter : o
Current Letter : n
Example 2 :
var=
whilevar>0:
var=var-
ifvar==5:
continue
print'Current variable value :',var
print"Good bye!"
Output:
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye!
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. The pass statement is a null operation; nothing happens when it executes.
Syntax for Pass
For var in sequence:
If condition:
Pass
Example:
for letter in'Python':
if letter =='h':
pass
print'This is pass block'
print'Current Letter :', letter
print"Good bye!"
Output:
Current Letter : P Current Letter : y Current Letter : t This is pass block Current Letter : h Current Letter : o Current Letter : n Good bye!
Fruitful functions are functions that return value. While using fruitful function, the return value must be handled properly by assigning it to a variable or use it as part of expression.
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:
Example
x = "global"
def foo():
print("x inside :", x)
foo()
print("x outside:", x)
output:
x inside : global x outside: global
In above code, we created x as a global variable and defined a foo() to print the global variable x. Finally, we call the foo() which will print the value of x.
Local Variables
A variable declared inside the function's body or in the local scope is known as local
variable.
Example 1:
def foo():
y = "local"
foo()
print(y)
output:
NameError: name 'y' is not defined
The output shows an error, because we are trying to access a local variable y in a global
scope whereas the local variable only works inside foo() or local scope.
Example 2:
def foo():
y = "local"
print(y)
foo()
output
local
Let's take a look to the earlier problem where x was a global variable and we wanted to modify x inside foo().
Function Composition:
Function composition is a way of combining functions such that the result of each function is passed as the argument of the next function. For example, the composition of two functions f and g is denoted f(g(x)). x is the argument of g, the result of g is passed as the argument of f and the result of the composition is the result of f.
As an example, we‟ll write a function that takes two points, the center of the
circle and a point on the perimeter, and computes the area of the circle.
Assume that the center point is stored in the variables xc and yc, and the
perimeter point is in xp and yp. The first step is to find the radius of the circle, which is
the distance between the two points. Fortunately, we‟ve just written a function, distance,
that does just that, so now all we have to do is use it:
radius = distance(xc, yc, xp, yp)
The second step is to find the area of a circle with that radius and return it. Again we will use one of our earlier functions:
result = area(radius)
Return result Wrapping that up in a function, we get:
def area2(xc, yc, xp, yp): radius = distance(xc, yc, xp, yp) result = area(radius) return result
We called this function area2 to distinguish it from the area function defined
earlier. There can only be one function with a given name within a given module. The
temporary variables radius and result are useful for development and debugging, but
once the program is working, we can make it more concise by composing the function calls:
def area2(xc, yc, xp, yp): return area(distance(xc, yc, xp, yp))
Recursion
Recursion is a process in which a function calls itself as a subroutine. This allows the function to be repeated several times, since it calls itself during its execution. Functions that incorporate recursion are called recursive functions.
Recursion is often seen as an efficient method of programming since it requires the least amount of code to perform the necessary functions. However, recursion must be incorporated carefully, since it can lead to an infinite loop if no condition is met that will terminate the function.
Example:
def factorial(n): if n ==1: