Sie sind auf Seite 1von 42

GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

UNIT III CONTROL FLOW, FUNCTIONS


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.

The boolean type


A boolean expression (or logical expression) evaluates to one of two states true or false.
Python provides the boolean type that can be either set to False or True. Many functions
and operations returns boolean objects.
The not keyword can also be used to inverse a boolean type.
>>> not True
False
What is False ?
Every object has a boolean value. The following elements are false:
 None
 False
 0 (whatever type from integer, float to complex)
 Empty collections: “”, (), [], {}
 Objects from classes that have the special method __nonzero__
 Objects from classes that implements __len__ to return False or zero

Example of a class with type set to False:


>>> class A():
... def __len__(self):
... return 0
...
>>> class B():
... def __nonzero__(self):
... return 0
...
>>> a = A()
>>> bool(a)
False
>>> b = B()
>>> bool(b)
False
All other objects are True.
9.3. Comparison operators

1 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

The <, <=, >, >=, ==, != operators compare the values of 2 objects and returns True or False.
Comparison depends on the type of the objects. See the Classes to see how to refedine the
comparison operator of a type.
10 == 10
10 <= 10.
9.4. Chaining comparison operators
Comparison operators can be chained. Consider the following examples:
>>> x = 2
>>> 1 < x < 3
True
>>> 10 < x < 20
False
>>> 3 > x <= 2
True
>>> 2 == x < 4
True
The comparison is performed between each pair of terms to be evaluated. For instance in
the first example, 1<x is evaluated to True AND x<2 is evaluated. It is not as if 1<x is
evaluated to True and then True<3 is evaluated to True !!! Each term is evaluated once.
Evaluation of logical and comparison operators and membership operators
The evaluation using the and and or operators follow these rules:
 and and or evaluates expression from left to right.
 with and, if all values are True, returns the last evaluated value. If any value is
false, returns the first one.
 or returns the first True value. If all are False, returns the last value
operators descriptions
not x Returns True if x is True, False otherwise
x and y Returns x if x is False, y otherwise
x or y Returns y if x is False, x otherwise
See Examples for more details.
Membership operators
 in evaluates to True if it finds a variable in a specified sequence and false
otherwise.
 not in evaluates to False if it finds a variable in a sequence, True otherwise.
>>> 'good' in 'this is a great example'
False
>>> 'good' not in 'this is a great example'
True
Identity operators
 is evaluates to True if the variables on either side of the operator point to the
same object and False otherwise
 is not evaluates to False if the variables on either side of the operator point to the
same object and True otherwise

2 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

>>> p = 'hello'
>>> ps = p
>>> ps is p
True
Bitwise operators
Bitwise operators are used to compare integers in their binary formats.
When performing a binary operations between 2 integers, there are first converted into
binary numbers.
Let us show a few examples to explain the bitwise operations. The and operation between 2
the values 5 and 4 is actually the and operations between 1011 and 1001 binaries. It is
therefore equal to 1001:
>>> cmp(4, 5)
-1
bitwise operators descriptions
>> bitwise left shift
<< bitwise rightshift
& bitwise and
^ bitwise xor
bitwise or
~ bitwise not
The left and right shifts can divide or multiply by power of 2 easily (integer conversion is
made):
>>> 25 >> 2
6
>>> 25 << 2
100
Warning

There is no overflow check. so if a right shift exceeds 2^31, the operation deletes extra bits
and flips the sign.
The not operator works as follows:
>>> ~38
-39
>>> ~-38
37
Order of evaluation
The order of evaluation from highest to order is as shown in this table:
operators descriptions
(), [], {}, ‘’ tuple, list, dictionnary, string
x.attr, x[], x[i:j], f() attribute, index, slide, function call
+x, -x, ~x unary negation, bitwise invert

3 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

operators descriptions
** exponent
*, /, % multiplication, division, modulo
+, - addition, substraction
<<, >> bitwise shifts
& bitwise and
^ bitwise xor
bitwise or
<, <=, >=, > comparison operators
==, !=, is, is not, in, comparison operators (continue)
not in comparison operators (continue)
not boolean NOT
and boolean AND
or boolean OR
lambda lamnda expression
Here is the precedence table for the boolean operators only
operator
==
!=
and
or
Boolean Examples
Short-circuit evaluations
To speed up boolean evaluations, Python uses short-circuit evaluations. It means that
boolean evaluation may stop if one of its expression is False. For instance the following
expression is always False
False and X
Returned values
In logical test, the returned value is the one that has been evaluated last. Consider these
examples:
>>> print (True and "OK" or "KO")
OK
>>> print (False and "OK" or "KO")
KO
in the first statement, True and "OK" is True. There is not need to
test or"KO", so this is the end of the logical test, and the returned value is
Explanation: the one that has been evaluated last in True and "OK". In the second
statement, False and "OK" is False. So, or "KO" must be evaluated. So, the
last evaluated expression is "KO", hence the returned value.

4 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

Control Structures :
Conditional Structure
1.Sequential structure(if)

2.Selection structure/branching/decision making


• if statement
• If..else statement
• If..elif..else statement

3.Repetition structure/looping/iterative
• while
• For

Unconditional Structure
• Break
• Continue
• Pass

Decision making is required when we want to execute a code only if a certain condition is
satisfied.

The if…elif…else statement is used in Python for decision making.


Python if Statement Syntax

if test expression:
statement(s)

Here, the program evaluates the test expression and will execute statement(s) only if the
text expression is True.

If the text expression is False, the statement(s) is not executed.

In Python, the body of the if 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 True. None and 0 are interpreted as False.
Python if Statement Flowchart

5 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

Example: Python if Statement


# If the number is positive, we print an appropriate message

num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")

num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")

When you run the program, the output will be:

3 is a positive number
This is always printed
This is also always printed.

In the above example, num > 0 is the test expression.

The body of if is executed only if this evaluates to True.

When variable num is equal to 3, test expression is true and body inside body of if is
executed.

If variable num is equal to -1, test expression is false and body inside body of if is skipped.

The print() statement falls outside of the if block (unindented). Hence, it is executed
regardless of the test expression.

6 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

Python if...else Statement


Syntax of if...else

if test expression:
Body of if
else:
Body of else

The if..else statement evaluates test expression and will execute body of if only when test
condition is True.

If the condition is False, body of else is executed. Indentation is used to separate the blocks.
Python if..else Flowchart

7 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

Example of if...else
# Program checks if the number is positive or negative
# And displays an appropriate message

num = 3

# Try these two variations as well.


# num = -5
# num = 0

if num >= 0:
print("Positive or Zero")
else:
print("Negative number")

n the above example, when num is equal to 3, the test expression is true and body of if is
executed and body of else is skipped.

If num is equal to -5, the test expression is false and body of else is executed and body
of if is skipped.

If num is equal to 0, the test expression is true and body of if is executed and body of else is
skipped.
Python if...elif...else
Syntax of if...elif...else

if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else

• The elif is short for else if. It allows us to check for multiple expressions.
• If the condition for if is False, it checks the condition of the next elif block and so on.
• If all the conditions are False, body of else is executed.
• Only one block among the several if...elif...else blocks is executed according to the
condition.
• The if block can have only one else block. But it can have multiple elif blocks.

8 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

Flowchart of if...elif...else

Example of if...elif...else
# In this program,
# we check if the number is positive or
# negative or zero and
# display an appropriate message

num = 3.4

# Try these two variations as well:


# num = 0
# num = -4.5

if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

9 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

When variable num is positive, Positive number is printed.

If num is equal to 0, Zero is printed.

If num is negative, Negative number is printed


Python Nested if statements

We can have a if...elif...else statement inside another if...elif...else statement. This is called
nesting in computer programming.

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 if we can.
Python Nested if Example
# In this program, we input a number
# check if the number is positive or
# negative or zero and display
# an appropriate message
# This time we use nested if

num = float(input("Enter a number: "))


if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Output 1
Enter a number :5
Positive number

Output 2
Enter a number : -1
Negative number

Output 3
Enter a number : 0
Zero

FOR LOOP:

The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects. Iterating over a sequence is called traversal.

10 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

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 last item in the sequence. The body of for loop is
separated from the rest of the code using indentation.
Flowchart of for Loop

Example: Python for Loop


# Program to find the sum of all numbers stored in a list

# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# variable to store the sum


sum = 0

11 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

# iterate over the list


for val in numbers:
sum = sum+val

# Output: The sum is 48


print("The sum is", sum)

when you run the program, the output will be:

The sum is 48

The range() function

We can generate a sequence of numbers using range() function. range(10) will generate
numbers from 0 to 9 (10 numbers).

We can also define the start, stop and step size as range(start,stop,step size). step size
defaults to 1 if not provided.

This function does not store all the values in memory, it would be inefficient. So it
remembers the start, 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 list().

The following example will clarify this.

# Output: range(0, 10)


print(range(10))

# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10)))

# Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))

# Output: [2, 5, 8, 11, 14, 17]


print(list(range(2, 20, 3)))

# Program to iterate through a list using indexing

genre = ['pop', 'rock', 'jazz']

# iterate over the list using index


for i in range(len(genre)):
print("I like", genre[i])

12 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

When you run the program, the output will be:

I like pop
I like rock
I like jazz

for loop with else

A for loop can have an optional else block as well. The else part is executed if the items in
the sequence used in for loop exhausts.

break statement can be used to stop a for loop. In such case, the else part is ignored.

Hence, a for loop's else part runs if no break occurs.

Here is an example to illustrate this.


digits = [0, 1, 5]

for i in digits:
print(i)
else:
print("No items left.")

When you run the program, the output will be:

0
1
5
No items left.

Here, the for loop prints items of the list until the loop exhausts. When the for loop
exhausts, it executes the block of code in the else and prints

No items left.

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.
13 I. Rajasubramanian, AP / CSE, DRGUPCE
GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

Syntax of while Loop in Python

while test_expression:
Body of while

In while loop, test expression is checked first. The body of the loop is entered only if
the test_expression evaluates to True. After one iteration, the test expression is checked
again. This process continues until the test_expression evaluates to False.

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. None and 0 are interpreted as False.
Flowchart of while Loop

Example: Python while Loop


# Program to add natural
# numbers upto
# sum = 1+2+3+...+n

# To take input from the user,

14 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

# n = int(input("Enter n: "))

n = 10

# initialize sum and counter


sum = 0
i=1

while i <= n:
sum = sum + i
i = i+1 # update counter

# print the sum


print("The sum is", sum)

When you run the program, the output will be:

Enter n: 10
The sum is 55

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).

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.


while loop with else

Same as that of for loop, we can have an optional else block with while loop as well.

The else part is executed if the condition in the while loop evaluates to False. The while
loop can be terminated with a break statement.

In such case, the else part is ignored. Hence, a while loop's else part runs if no break occurs
and the condition is false.

Here is an example to illustrate this.


# Example to illustrate
# the use of else statement
# with the while loop

15 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

counter = 0

while counter < 3:


print("Inside loop")
counter = counter + 1
else:
print("Inside else")

Output

Inside loop
Inside loop
Inside loop
Inside else

Here, we use a counter variable to print the string Inside loop three times.

On the forth iteration, the condition in while becomes False. Hence, the else part is
executed.

Break:

In Python, break and continue statements can alter the flow of a 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 cheking test expression.

The break and continue statements are used in these cases.


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

16 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

Flowchart of break

The working of break statement in for loop and while loop is shown below.

Example: Python break


# Use of break statement inside loop

for val in "string":


if val == "i":

17 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

break
print(val)
print("The end")

Output

s
t
r
The end

In this program, we iterate through the "string" sequence. We check if the letter is "i", upon
which we break from the loop. Hence, we see in our output that all the letters up till "i" gets
printed. After that, the loop terminates.
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

continue

Flowchart of continue

18 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

The working of continue statement in for and while loop is shown below.

Example: Python continue


# Program to show the use of continue statement inside loops

for val in "string":


if val == "i":
continue
print(val)

print("The end")

Output

s
t
r
n
g
The end

19 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

This program is same as the above example except the break statement has been replaced
with continue.

We continue with the loop, if the string is "i", not executing the rest of the block. Hence, we
see in our output that all the letters except "i" gets printed.

Pass:
It 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. The pass is also
useful in places where your code will eventually go, but has not been written yet.
Syntax of pass

pass

We generally use it as a placeholder.

Suppose we have a loop or a function that is not 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 pass statement to construct a body that does nothing.

#!/usr/bin/python

for letter in 'Python':

if letter == 'h':

pass

print 'This is pass block'

print 'Current Letter :', letter

print "Good bye!"

When the above code is executed, it produces following result −

Current Letter : P
Current Letter : y
Current Letter : t
This is pass block

20 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

Difference between various iterations Pass Continue Break

Recursive Function :

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.

Following is an example of 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.

21 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

Example of recursive function


# An example of a recursive function to

# find the factorial of a number

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))

num = 4

print("The factorial of", num, "is", calc_factorial(num))

In the above example, calc_factorial() is a recursive functions as it calls 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.

calc_factorial(4) # 1st call with 4


4 * calc_factorial(3) # 2nd call with 3
4 * 3 * calc_factorial(2) # 3rd call with 2
4 * 3 * 2 * calc_factorial(1) # 4th call with 1
4*3*2*1 # return from 4th call as number=1
4*3*2 # return from 3rd call
4*6 # return from 2nd call
24 # return from 1st call

22 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

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

1. Recursive functions make the code look clean and elegant.


2. A complex 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.

Fruitful Function :
A fruitful function is a function that returns a value when it is called. Most of the
builtin functions that we have used are fruitful. For example, the function abs returns a new
number namely, the absolute value of its argument:
>>> abs(−42)
42

Some functions are not fruitful. For example, suppose franklin refers to a Turtle object, the
function call franklin.forward(100) does not return anything. Instead it causes franklin to
move forward. In addition, all of the functions defined in the previous handout are not
fruitful.

2 Defining a fruitful function


If we want a function to return a result to the caller of the function, we use the return
statement. For example, here we define two fruitful functions. The second one, circle area,
calls the first one, square, to square the radius.

import math

def square(x):
return x ∗ x
def circle_area (diameter ):
radius = diameter / 2.0
return math.pi ∗ square(radius)

23 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

In general, a return statement consists of the return keyword followed by an expression,


which is evaluated and returned to the function caller.

How python evaluates a return statement Python evaluates fruitful functions pretty
much the same way as non-fruitful ones (see last handout). The only thing new is how it
executes a return statement. Here’s roughly how it works:

1. Evaluate the expression to produce a data value.

2. Pass that data value back to the caller.

3. Leave the function immediately and return to the location where the function was called.

Python returns immediately when it reaches a return statement. The print statement in the
function body below will never be executed:

def square(x):

return x ∗ x # p yt h o n l e a v e s f u n c t i o n h e r e . .
.

print "I am NEVER printed!" # . . . and n e v e r g e t s t o h e r e .

3 Return vs. print, which one to use?

Many beginning programmers get confused about the difference between return and print.
The return statement sends a data value back to the caller of the function; the print
statement displays a data value on the screen. You will need to use both. But when to use
which? Here’s a general rule of thumb: Use return to share the result with another part of
your program; use print to share the result with the user.

The square function must use a return statement because it is called inside the circle area
function. In other words, the point of this function is to share the result (i.e., the squared
number) with another part of our program (i.e., the circle area function).

4 NoneType error

In python, every function is fruitful even if the body does not contain a return statement. In
this case, the function will return a special value called None, which has type NoneType.

Example: suppose we change the return in square to print. Here’s what happens when we
call circle area passing in 4 as its argument.

>>> circle_area (8)

16.0

24 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

Traceback (most recent call last ):

File "<stdin>", line 1, in <module>

File " fruitful_functions .py", line 8, in circle_area

return math.pi * square(radius)

TypeError : unsupported operand type(s) for *: ’float ’ and ’NoneType ’

We get an error about a NoneType because circle area is trying to multiply math.pi with the
return value of square, which is None, and so it crashes. Also notice that just before the
error, the program prints the number 16.0 (which is (8/2)2 ).

The return statement


The return statement is used to exit a function and go back to the place from 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 return statement itself is not present
inside a function, then the function will return the None object.
For example:

>>> print(greet("May"))
Hello, May. Good morning!
None

Here, None is the returned value.

def absolute_value(num):
"""This function returns the absolute
value of the entered number"""

if num >= 0:

25 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

return num
else:
return -num

# Output: 2
print(absolute_value(2))

# Output: 4
print(absolute_value(-4))

Local and Global Scope :

The scope of a variable refers to the places that you can see or access a variable.

If you define a variable at the top level of your script or module or notebook, this is a global
variable:

>>>

>>> my_var = 3

The variable is global because any Python function or class defined in this module or
notebook, is able to access this variable. For example:

>>>

>>> def my_first_func():

... # my_func can 'see' the global variable

... print('I see "my_var" = ', my_var, ' from "my_first_func"')


>>>

>>> my_first_func()

I see "my_var" = 3 from "my_first_func"

Variables defined inside a function or class, are not global. Only the function or class can
see the variable:

26 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

>>>

>>> def my_second_func():

... a = 10

... print('I see "a" = ', a, 'from "my_second_func"')


>>>

>>> my_second_func()

I see "a" = 10 from "my_second_func"

But here, down in the top (global) level of the notebook, we can’t see that variable:

>>>

>>> a

Traceback (most recent call last):

...

NameError: name 'a' is not defined

The variable a is therefore said to be local to the function. Put another way, the
variable a has local scope. Conversely the variable my_var has global scope.

The full rules on variable scope cover many more cases than these simple examples.

Parameter

Scalar – an atomic single-item value or variable. Integers, floating point numbers, strings,
and booleans are types of scalars.

Object-- Multi-item data, such as a Python list. We'll also learn object-oriented
programming and how to define objects with named sub-items.

Global variable -- a variable defined in the "main" program. A variable is defined the first
time it appears on the left-hand-side of an assignment statement.
Local variable -- a variable defined within a function. Local variables are temporary,
scratch memory. When a function completes, its local variables are de-allocated (they
die!). Consider the code below:

27 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

def func():
x = 33
return 99

x = 88
y = func()

The x defined within func is a local variable. The x and y defined with main
are global variables.

Parameter -- Data sent to one function from another.

Formal parameter -- The parameter defined as part of the function definition, e.g., x in:

def cube(x):
return x*x*x

Actual Parameter -- The actual data sent to a function. It's found in the function call, e.g., 7
in

result = cube(7)

or y in:

y=5
res = cube(y)

STRINGS
Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data
Science by completing interactive coding challenges and watching videos by expert
instructors. Start Now!
Strings in python are contiguous series of characters delimited by single or double quotes.
Python don’t have any separate data type for characters so they are represented as a single
character string.
Creating Strings
1 >>> name = "tom" # a string
2 >>> mychar = 'a' # a character

28 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

you can also use the following syntax to create strings.

1 >>> name1 = str() # this will create empty string object


2 >>> name2 = str("newstring") # string object containing 'newstring'
Strings in python are immutable.
What this means to you is that once string is created it can’t be modified. Let’s take an
example to illustrate this point.

>>> str1 = "welcome"


>>> str2 = "welcome"

here str1 and str2 refers to the same string object "welcome" which is stored somewhere
in memory. You can test whether str1 refers to same object as str2 usingid() function.
What is id() : Every object in python is stored somewhere in memory. We can use id() to
get that memory address.

>>> id(str1)
1
78965411
2
>>> id(str2)
3
78965411
4
As both str1 and str2 points to same memory location, hence they both points to the same
object.
Let’s try to modify str1 object by adding new string to it.

1 >>> str1 += " mike"


2 >>> str1
3 welcome mike
4 >>> id(str1)
5 >>> 78965579

29 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

As you can see now str1 points to totally different memory location, this proves the point
that concatenation doesn’t modify original string object instead it creates a new string
object. Similarly Number (i.e int type) is also immutable.
Operations on string
String index starts from 0 , so to access the first character in the string type:
>>> name[0] #
t
+ operator is used to concatenate string and * operator is a repetition operator for string.
1 >>> s = "tom and " + "jerry"
2 >>> print(s)
3 tom and jerry

1 >>> s = "this is bad spam " * 3


2 >>> print(s)
3 this is bad spam this is bad spam this is bad spam
Slicing string
You can take subset of string from original string by using [] operator also known as slicing
operator.
Syntax: s[start:end]
this will return part of the string starting from index start to index end - 1 .
Let’s take some examples.

1 >>> s = "Welcome"
2 >>> s[1:3]
3 el
Some more examples.

1 >>> s = "Welcome"
2 >>> s[ : 6]
3 'Welcom'

30 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

4
5 >>> s[4 : ]
6 'ome'
7
8 >>> s[1 : -1]
9 'elcom'
Note: start index and end index are optional. If omitted then the default value ofstart index
is 0 and that of end is the last index of the string.
ord() and chr() Functions
ord() – function returns the ASCII code of the character.
chr() – function returns character represented by a ASCII number.
1 >>> ch = 'b'
2 >>> ord(ch)
3 98
4 >>> chr(97)
5 'a'
6 >>> ord('A')
7 65
String Functions in Python

FUNCTION NAME FUNCTION DESCRIPTION

len() returns length of the string

max() returns character having highest ASCII value

min() returns character having lowest ASCII value

1 >>> len("hello")
25
3 >>> max("abc")
4 'c'

31 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

5 >>> min("abc")
6 'a'
in and not in operators
You can use in and not in operators to check existence of string in another string. They are
also known as membership operator.
1 >>> s1 = "Welcome"
2 >>> "come" in s1
3 True
4 >>> "come" not in s1
5 False
6 >>>
String comparison
You can use ( > , < , <= , <= , == , != ) to compare two strings. Python compares string
lexicographically i.e using ASCII value of the characters.
Suppose you have str1 as "Mary" and str2 as "Mac" . The first two characters fromstr1
and str2 ( M and M ) are compared. As they are equal, the second two characters are
compared. Because they are also equal, the third two characters ( r and c ) are compared.
And because 'r' has greater ASCII value than 'c' , str1 is greater thanstr2 .
Here are some more examples:
1 >>> "tim" == "tie"
2 False
3 >>> "free" != "freedom"
4 True
5 >>> "arrow" > "aron"
6 True
7 >>> "right" >= "left"
8 True
9 >>> "teeth" < "tee"
10 False
11 >>> "yellow" <= "fellow"

32 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

12 False
13 >>> "abc" > ""
14 True
15 >>>
Iterating string using for loop
String is a sequence type and also iterable using for loop (to learn more about for loop click here).

1 >>> s = "hello"
2 >>> for i in s:
3 ... print(i, end="")
4 hello
Note: By default print() function prints string with a newline , we change this behavior by
supplying a second argument to it as follows.
1 print("my string", end="\n") #this is default behavior

1 print("my string", end="") # print string without a newline

1 print("my string", end="foo") # now print() will print foo after every string
Testing strings
String class in python has various inbuilt methods which allows to check for different
types of strings.

METHOD NAME METHOD DESCRIPTION

isalnum() Returns True if string is alphanumeric

isalpha() Returns True if string contains only alphabets

isdigit() Returns True if string contains only digits

isidentifier() Return True is string is valid identifier

islower() Returns True if string is in lowercase

isupper() Returns True if string is in uppercase

33 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

METHOD NAME METHOD DESCRIPTION

isspace() Returns True if string contains only whitespace

1 >>> s = "welcome to python"


2 >>> s.isalnum()
3 False
4 >>> "Welcome".isalpha()
5 True
6 >>> "2012".isdigit()
7 True
8 >>> "first Number".isidentifier()
9 False
10 >>> s.islower()
11 True
12 >>> "WELCOME".isupper()
13 True
14 >>> " \t".isspace()
15 True

The String Module

The string module provides additional tools to manipulate strings. Some methods available
in the standard data structure are not available in the string module.

>>> string.digits
'0123456789'

>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

>>> string.lowercase
'abcdefghijklmnopqrstuvwxyz'

>>> string.letters

34 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

>>> string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

3.2. Lists
Python has two data structures, lists and tuples, that consist of a list of one or more
elements. The elements of lists or tuples can be numbers or strings, or both. Lists (we will
discuss tuples later) are defined by a pair of square brackets on either end with individual
elements separated by commas. Here are two examples of lists:
In [1]: a = [0, 1, 1, 2, 3, 5, 8, 13]
In [2]: b = [5., "girl", 2+0j, "horse", 21]
We can access individual elements of a list using the variable name for the list with square
brackets:
In [3]: b[0]
Out[3]: 5.0

In [4]: b[1]
Out[4]: 'girl'

In [5]: b[2]
Out[5]: (2+0j)
The first element of b is b[0], the second is b[1], the third is b[2], and so on. Some computer
languages index lists starting with 0, like Python and C, while others index lists (or things
more-or-less equivalent) starting with 1 (like Fortran and Matlab). It’s important to keep in
mind that Python uses the former convention: lists are zero-indexed.
The last element of this array is b[4], because b has 5 elements. The last element can also
be accessed as b[-1], no matter how many elements b has, and the next-to-last element of
the list is b[-2], etc. Try it out:
In [6]: b[4]
Out[6]: 21

In [7]: b[-1]
Out[7]: 21

In [8]: b[-2]
Out[8]: 'horse'
Individual elements of lists can be changed. For example:
In [9]: b
Out[9]: [5.0, 'girl', (2+0j), 'horse', 21]

In [10]: b[0] = b[0]+2

35 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

In [11]: b[3] = 3.14159

In [12]: b
Out[12]: [7.0, 'girl', (2+0j), 3.14159, 21]
Here we see that 2 was added to the previous value of b[0] and the string 'horse' was
replaced by the floating point number 3.14159. We can also manipulate individual
elements that are strings:
In [13]: b[1] = b[1] + "s & boys"

In [14]: b
Out[14]: [10.0, 'girls & boys', (2+0j), 3.14159, 21]
You can also add lists, but the result might surprise you:
In [15]: a
Out[15]: [0, 1, 1, 2, 3, 5, 8, 13]

In [16]: a+a
Out[16]: [0, 1, 1, 2, 3, 5, 8, 13, 0, 1, 1, 2, 3, 5, 8, 13]

In [17]: a+b
Out[17]: [0, 1, 1, 2, 3, 5, 8, 13, 10.0, 'girls & boys', (2+0j),
3.14159, 21]
Adding lists concatenates them, just as the “+” operator concatenates strings.
3.2.1. Slicing lists
You can access pieces of lists using the slicing feature of Python:
In [18]: b
Out[18]: [10.0, 'girls & boys', (2+0j), 3.14159, 21]

In [19]: b[1:4]
Out[19]: ['girls & boys', (2+0j), 3.14159]

In [20]: b[3:5]
Out[20]: [3.14159, 21]
You access a subset of a list by specifying two indices separated by a colon “:”. This is a
powerful feature of lists that we will use often. Here are a few other useful slicing
shortcuts:
In [21]: b[2:]
Out[21]: [(2+0j), 3.14159, 21]

In [22]: b[:3]
Out[22]: [10.0, 'girls & boys', (2+0j)]

36 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

In [23]: b[:]
Out[23]: [10.0, 'girls & boys', (2+0j), 3.14159, 21]
Thus, if the left slice index is 0, you can leave it out; similarly, if the right slice index is the
length of the list, you can leave it out also.
What does the following slice of an array give you?
In [24]: b[1:-1]
You can get the length of a list using Python’s len function:
In [25]: len(b)
Out[25]: 5
3.2.2. Creating and modifying lists
Python has functions for creating and augmenting lists. The most useful is
the range function, which can be used to create a uniformly spaced sequence of integers.
The general form of the function is range([start,] stop[, step]), where the arguments are all
integers; those in square brackets are optional:
In [26]: range(10) # makes a list of 10 integers from 0 to 9
Out[26]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [27]: range(3,10) # makes a list of 10 integers from 3 to 9


Out[27]: [3, 4, 5, 6, 7, 8, 9]

In [28]: range(0,10,2) # makes a list of 10 integers from 0 to 9


# with increment 2
Out[28]: [0, 2, 4, 6, 8]
You can add one or more elements to the beginning or end of a list using the “+” operator:
In [29]: a = range(1,10,3)

In [30]: a
Out[30]: [1, 4, 7]

In [31]: a += [16, 31, 64, 127]

In [32]: a
Out[32]: [1, 4, 7, 16, 31, 64, 127]

In [33]: a = [0, 0] + a

In [34]: a
Out[34]: [0, 0, 1, 4, 7, 16, 31, 64, 127]
You can insert elements into a list using slicing:
In [35]: b = a[:5] + [101, 102] + a[5:]

37 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

In [36]: b
Out[36]: [0, 1, 1, 4, 7, 101, 102, 16, 31, 64, 127]
TWO MARK QUESTIONS

38 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

39 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

40 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

41 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITIII

42 I. Rajasubramanian, AP / CSE, DRGUPCE

Das könnte Ihnen auch gefallen