M2 - Python For Machine Learning - Maria S

Download as pdf or txt
Download as pdf or txt
You are on page 1of 112

Course Code : CST283

Category : Minor
Offered by : Dept. of Computer Science and Engg.
Faculty in charge : Jaseela Beevi S

Python for Machine Learning


Dept. of CSE, TKMCE 1
Syllabus - Module II

Building Python Programs:


Control statements - Selection structure (if-else, switch-case), Iteration structure(for,
while), Testing the control statements, Lazy evaluation. Functions - Hiding
redundancy and complexity, Arguments and return values, Variable scopes and
parameter passing, Named arguments, Main function, Working with recursion,
Lambda functions. Strings and number systems - String function, Handling numbers
in various formats.

Dept. of CSE, TKMCE 2


Control Statements
control statements—statements that allow the computer to select or repeat an
action.

üSelection structure : statements which determines whether other statements


will be executed
e.g. if-else, switch-case

üIteration structure : statements which determines how many time to execute


another statements.
e.g. for, while

Dept. of CSE, TKMCE 3


Selection: if and if-else Statements
• if-else statement:
ü It is also called a two-way selection statement, because it directs the computer
to make a choice between two alternative courses of action.
üIt is often used to check inputs for errors and to respond with error messages if
necessary.
if <condition>:
<sequence of statements–1>
else:
<sequence of statements–2>
ü The condition in the if-else statement must be a Boolean expression—that is, an
expression that evaluates to either true or false.

Dept. of CSE, TKMCE 4


if-else Statements
e.g., prints the maximum and minimum of two input numbers.

Dept. of CSE, TKMCE 5


Selection: if and if-else Statements
• if statement:

üThe simplest form of selection is the if statement. This type of control statement
is also called a one-way selection statement.

üit consists of a condition and just a single sequence of statements. If the


condition is True, the sequence of statements is run. Otherwise, control
proceeds to the next statement following the entire selection statement.

if <condition>:
<sequence of statements>

Dept. of CSE, TKMCE 6


if - Statements

if x < 0:
x = –x
Dept. of CSE, TKMCE 7
The process of testing several conditions and responding accordingly can be
described in code by a multi-way selection statement.

if <condition-1>:
<sequence of statements-1>
.
.
.
elif <condition-n>:
<sequence of statements-n>
else:
<default sequence of statements>

Dept. of CSE, TKMCE 8


Multiway if statement

Dept. of CSE, TKMCE 9


Introduction to Python Switch Statement
• A switch statement is a very useful and powerful programming feature. It is an
alternate to if-else-if ladder statement and provides better performance and more
manageable code than an if-else-if ladder statement.

• Python language does not provide any inbuilt switch statements. We can
implement this feature with the same flow and functionality but with different
syntax and implementation using Python Dictionary.

Dept. of CSE, TKMCE 10


Flow Chart

Dept. of CSE, TKMCE 11


Syntax of Switch Statement
1. Switch in Other Languages (c, Java,..)
switch(N)
{
case 1: Statement if N = 1;
break;
case 2: Statement if N = 2;
break;
::
case n: Statement if N = n;
break;
default: Statement if N doesn't match any
}
Dept. of CSE, TKMCE 12
2. Switch Implementation in Python

switcher=
{
key_1: value_1/method_1(),
key_2: value_2/method_2(),
key_3: value_3/method_3(),
::
key_n: value_n/method_n(),
}
key = N
value = switcher.get(key, "default")

Dept. of CSE, TKMCE 13


Implementation of Switch statement in Python
def get_week_day(argument):
switcher = {
0: "Sunday",
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday"
}
return switcher.get(argument, "Invalid day")
print (get_week_day(6))
print (get_week_day(8))
print (get_week_day(0))

Dept. of CSE, TKMCE 14


The Boolean Type, Comparisons, and Boolean
Expressions
Boolean Data Type: The Boolean data type consists of only two data values—true
and false. Simple Boolean expressions consist of the Boolean values True or False,
variables bound to those values, function calls that return Boolean values, or
comparisons.

Dept. of CSE, TKMCE 15


Logical Operators and Compound Boolean Expressions
number = int(input("Enter the numeric grade: "))
if number > 100:
print("Error: grade must be between 100 and 0")
elif number < 0:
print("Error: grade must be between 100 and 0")
else:
# The code to compute and print the result goes here

• The two conditions can be combined in a Boolean expression that uses the logical operator
or. The resulting expression is compound Boolean expression

number = int(input("Enter the numeric grade: "))


if number > 100 or number < 0:
print("Error: grade must be between 100 and 0")
else:
# The code to compute and print the result goes here

Dept. of CSE, TKMCE 16


• Another way to describe this situation using and operator is

number = int(input("Enter the numeric grade: "))


if number >= 0 and number <= 100:
# The code to compute and print the result goes here
else:
print("Error: grade must be between 100 and 0")

Dept. of CSE, TKMCE 17


Precedence of Logical Operators
>>> A = True
>>> B = False
>>> A and B
False
>>> A or B
True
>>> not A
False
The logical operators are evaluated after comparisons but before the assignment
operator. The not operator has a higher precedence than the and operator, which has
a higher precedence than the or operator.
Thus, in our example, not A and B evaluates to False, whereas not (A and B) evaluates
to True.

Dept. of CSE, TKMCE 18


Dept. of CSE, TKMCE 19
Short-Circuit Evaluation
The Python virtual machine sometimes knows the value of a Boolean expression before it
has evaluated all of its operands.

For instance, in the expression A and B, if A is false, there is no need to evaluate B.


Likewise, in the expression A or B, if A is true, there is no need to evaluate B.

This approach, in which evaluation stops as soon as possible, is called short-circuit


evaluation.
count = int(input("Enter the count: "))
sum = int(input("Enter the sum: "))
if count > 0 and sum // count > 10:
print("average > 10")
else:
print("count = 0 or average <= 10")

Dept. of CSE, TKMCE 20


Exercises:
• 1. Assume that x is 3 and y is 5. Write the values of the following expressions:
a) x == y
b) x > y – 3
c) x <= y – 2
d) x == y or x > 2
e) x != 6 and y > 10
f) x > 0 and x < 100

2. Assume that x refers to a number. Write a code segment that prints the number’s
absolute value without using Python’s abs function.

Dept. of CSE, TKMCE 21


Definite Iteration: The for Loop
Loops - They are the control statements with repetition statements, also known as
loops, which repeat an action. Each repetition of the action is known as a pass or
an iteration.
There are two types of loops—

üthose that repeat an action a predefined number of times (definite iteration)

üthose that perform the action until the program determines that it
needs to stop (indefinite iteration).

Dept. of CSE, TKMCE 22


Syntax:

for <variable> in range(<an integer expression>):


<statement-1>
.
.
<statement-n>

• The first line of code in a loop is sometimes called the loop header.
• The integer value or expression in the range() tells the loop how many times to call
the below statements.
• The loop body comprises the statements in the remaining lines of code, below the
header. These statements are executed in sequence on each pass through the loop.

Dept. of CSE, TKMCE 23


• Implementation of exponentiation operator using for loop

#computation of 23
>>> number = 2
>>> exponent = 3
>>> product = 1
>>> for eachPass in range(exponent):
product = product * number
print(product, end = " ")
248
>>> product
8

Dept. of CSE, TKMCE 24


Count-Controlled Loops
üLoops that count through a range of numbers are also called count-
controlled loops.
üIt counts from 0 to the value of the header’s integer expression minus 1.
üOn each pass through the loop, the header’s variable is bound to the
current value of this count.
e.g.,
>>> for count in range(4):
print(count, end = " ")
0123
üTo count from an explicit lower bound, the programmer can supply a second integer
expression in the loop header. When two arguments are supplied to range, the
count ranges from the first argument to the second argument minus 1.

Dept. of CSE, TKMCE 25


Syntax:

for <variable> in range(<lower bound>, <upper bound + 1>):


<loop body>

# method - 2 : computation of factorial of 4 # method - 1 : computation of factorial of 4


>>> product = 1 >>> product = 1
>>> for count in range(1, 5): >>> for count in range(4):
product = product * count product = product * (count + 1)
>>> product >>> product
24 24

Dept. of CSE, TKMCE 26


# program to find the sum of first 10 integer numbers:

>>> lower = int(input("Enter the lower bound: "))


Enter the lower bound: 1
>>> upper = int(input("Enter the upper bound: "))
Enter the upper bound: 10
>>>
>>>theSum = 0
>>>for number in range(lower, upper+1):
theSum = theSum + number
>>>print(theSum)

55

Dept. of CSE, TKMCE 27


Augmented Assignment
• The assignment symbol can be combined with the arithmetic and concatenation
operators to provide augmented assignment operations.

üa = 17
üs = "hi"
üa += 3 # Equivalent to a = a + 3
üa -= 3 # Equivalent to a = a - 3
üa *= 3 # Equivalent to a = a * 3
üa /= 3 # Equivalent to a = a / 3
üa %= 3 # Equivalent to a = a % 3
üs += " there" # Equivalent to s = s + " there"

All these examples have the format


<variable> <operator>= <expression>

Dept. of CSE, TKMCE 28


Loop Errors: Off-by-One Error
• Once we get the syntax correct, we need to be concerned about only one other
possible error: The loop fails to perform the expected number of iterations.
Because this number is typically off by one, the error is called an off-by-one error.

• For the most part, off-by-one errors result when the programmer incorrectly
specifies the upper bound of the loop.

• # Count from 1 through 4, we think


• >>> for count in range(1,4):
• print(count)

• 123

Dept. of CSE, TKMCE 29


Traversing the Contents of a Data Sequence
• The for loop itself visits each number in a sequence of numbers generated by the
range function.
• The sequence of numbers generated by the function range is fed to Python’s
list function, which returns a special type of sequence called a list.
>>> list(range(4))
[0, 1, 2, 3]
>>> list(range(1, 5))
[1, 2, 3, 4]

Strings are also sequences of characters. The values contained in any sequence can
be visited by running a for loop, as follows:

for <variable> in <sequence>:


<do something with variable>

Dept. of CSE, TKMCE 30


Specifying the Steps in the Range
• In some programs we might want a loop to skip some numbers.
• A variant of Python’s range function expects a third argument that allows you to
nicely skip some numbers. The third argument specifies a step value, or the interval
between the numbers used in the range.

>>> list(range(1, 6, 1)) # Same as using two arguments


[1, 2, 3, 4, 5]
>>> list(range(1, 6, 2)) # Use every other number
[1, 3, 5]
>>> list(range(1, 6, 3)) # Use every third number
[1, 4]

Dept. of CSE, TKMCE 31


Suppose you had to compute the sum of the even numbers between 1 and 10.
>>> theSum = 0
>>> for count in range(2, 11, 2):
theSum += count
>>> theSum
30

Loops that Count Down


When the step argument is a negative number, the range function generates a
sequence of numbers from the first argument down to the second argument plus 1.
Thus, in this case, the first argument should express the upper bound, and the second
argument should express the lower bound minus 1.

Dept. of CSE, TKMCE 32


Exercises
1. Write the outputs of the following loops:
a. for count in range(5):
print(count + 1, end = " ")

b. for count in range(1, 4):


print(count, end = " ")

c. for count in range(1, 6, 2):


print(count, end = " ")

d. for count in range(6, 1, –1):


print(count, end = " ")

Dept. of CSE, TKMCE 33


Formatting Text for Output
To maintain the margins between columns of data, left-justification requires the addition
of spaces to the right of the datum, whereas right-justification requires adding spaces to
the left of the datum. A column of data is centered if there are an equal number of
spaces on either side of the data within that column.

The total number of data characters and additional spaces for a given datum in a
formatted string is called its field width.
how to right-justify and left-justify the string "four" within a field width of 6:
>>> "%6s" % "four" # Right justify
' four'
>>> "%-6s" % "four" # Left justify
'four '
Dept. of CSE, TKMCE 34
The simplest form of this operation is the following:
<format string> % <datum>

üThe format string can contain string data and other information about the format of
the datum.
ü When the field width is positive, the datum is right-justified; when the field width is
negative, you get left-justification.
üIf the field width is less than or equal to the datum’s print length in characters, no
justification is added.

ü To format a sequence of data values,


<format string> % (<datum–1>, ..., <datum–n>)

Dept. of CSE, TKMCE 35


The format information for a data value of type float has the form
%<field width> . <precision>f

>>> salary = 100.00


>>> print("Your salary is $" + str(salary))
Your salary is $100.0

>>> print("Your salary is $%0.2f" % salary)


Your salary is $100.00

To use a field width of 6 and a precision of 3 to format the float value 3.14:

>>> "%6.3f" % 3.14


' 3.140'

Dept. of CSE, TKMCE 36


Exercises:
• 1. Assume that the variable amount refers to 24.325. Write the outputs of the following
statements:
a. print("Your salary is $%0.2f" % amount)
b. print("The area is %0.1f" % amount)

2. Write a code segment that displays the values of the integers x, y, and z on a single
line, such that each value is right-justified with a field width of 6.

3. Write a format operation that builds a string for the float variable amount that has
exactly two digits of precision and a field width of zero.

4. Write a loop that outputs the numbers in a list named salaries. The outputs should be
formatted in a column that is right-justified, with a field width of 12 and a precision of 2.
Dept. of CSE, TKMCE 37
Conditional Iteration: The while Loop
In many situations, however, the number of iterations in a loop is unpredictable. The
loop eventually completes its work, but only when a condition changes. The process
continues to repeat as long as a condition remains true. This type of process is called
conditional iteration, meaning that the process continues to repeat as long as a
condition remains true.

Syntax:
while <condition>:
<sequence of statements>

Dept. of CSE, TKMCE 38


The Structure and Behavior of the Loop
• The form of this statement is almost identical to that of the one-way selection
statement.
• The use of the reserved word while instead of if indicates that the sequence of
statements might be executed many times, as long as the condition remains true.
• Clearly, something eventually has to happen within the body of the loop to make the
loop’s continuation condition become false. Otherwise, the loop will continue forever,
an error known as an infinite loop.
• At least one statement in the body of the loop must update a variable that affects the
value of the condition.

Dept. of CSE, TKMCE 39


Consider the pseudocode given below:

set the sum to 0.0


input a string
while the string is not the empty string
convert the string to a float
add the float to the sum
input a string
print the sum

• The first input statement initializes a variable to a value that the loop condition can
test. This variable is also called the loop control variable.
• The second input statement obtains the other input values, including one that will
terminate the loop.

Dept. of CSE, TKMCE 40


theSum = 0.0
data = input("Enter a number or just enter to quit: ")
while data != "":
number = float(data)
theSum += number
data = input("Enter a number or just enter to quit: ")
print("The sum is", theSum)

Output:
Enter a number or just enter to quit: 3 The while loop is also called an entry-
Enter a number or just enter to quit: 4 control loop, because its condition is
Enter a number or just enter to quit: 5 tested at the top of the loop. This
Enter a number or just enter to quit: implies that the statements within
The sum is 12.0 the loop can execute zero or more
times.

Dept. of CSE, TKMCE 41


Count Control with a while Loop
# Summation with a for loop # Summation with a while loop
theSum = 0 theSum = 0
for count in range(1, 11): count = 1
theSum += count while count <= 10:
print(theSum) theSum += count
count += 1
print(theSum)

It includes a Boolean expression and two extra statements that refer to the count
variable. This loop control variable must be explicitly initialized before the loop header
and incremented in the loop body. *

Dept. of CSE, TKMCE 42


The while True Loop and the break Statement
#Computation of sum using break within while loop

theSum = 0.0
while True:
data = input("Enter a number or just enter to quit: ")
if data == "":
break
number = float(data)
theSum += number
print("The sum is", theSum)

Within this body, the input datum is received. It is then tested for the loop’s termination
condition in a one-way selection statement. If the user wants to quit, the input will equal the
empty string, and the break statement will cause an exit from the loop. Otherwise, control
continues beyond the selection statement to the next two statements that process the input.
Dept. of CSE, TKMCE 43
The “break” Statement

Dept. of CSE, TKMCE 44


The “continue” Statement

Dept. of CSE, TKMCE 45


Random Numbers
üTo simulate randomness in computer applications, programming languages include
resources for generating random numbers.
üThe function random.randint returns a random number from among the numbers
between the two arguments and including those numbers.

#Code to simulate the role of a die 10 times.

>>> import random


>>> for roll in range(10):
print(random.randint(1, 6), end = " ")
2464323622

Dept. of CSE, TKMCE 46


Develop a simple guessing game using random.randint

At start-up, the user enters the smallest number and the largest number in the
range. The computer then selects a number from this range. On each pass through the
loop, the user enters a number to attempt to guess the number selected by the
computer. The program responds by saying “You’ve got it,” “Too large, try again,” or “Too
small, try again.” When the user finally guesses the correct number, the program
congratulates him and tells him the total number of guesses.

Dept. of CSE, TKMCE 47


import random
smaller = int(input("Enter the smaller number: "))
larger = int(input("Enter the larger number: "))
myNumber = random.randint(smaller, larger)
count = 0
while True:
count += 1
userNumber = int(input("Enter your guess: "))
if userNumber < myNumber:
print("Too small!")
elif userNumber > myNumber:
print("Too large!")
else:
print("Congratulations! You've got it in", count,"tries!")
break

Dept. of CSE, TKMCE 48


Exercises

1. Translate the following for loops to equivalent while loops:


a. for count in range(100):
print(count)
b. for count in range(1, 101):
print(count)
c. for count in range(100, 0, –1):
print(count)

2. The factorial of an integer N is the product of the integers between 1 and N, inclusive.
Write a while loop that computes the factorial of a given integer N.

Dept. of CSE, TKMCE 49


Exercises

3. Write a program that accepts the lengths of three sides of a triangle as inputs.
The program output should indicate whether or not the triangle is an equilateral
triangle.

4. Write a program that accepts the lengths of three sides of a triangle as inputs.
The program output should indicate whether or not the triangle is a right triangle. Recall
from the Pythagorean theorem that in a right triangle, the square of one side equals the
sum of the squares of the other two sides.

Dept. of CSE, TKMCE 50


Strings and Number System
The Structure of Strings:

String is a data structure.


A string is a sequence of zero or more characters.
eg. "Hi there!"
empty string “”

A string’s length is the number of characters it contains. Python’s len function returns
this value when it is passed a string.

>>> len("Hi there!")


9
>>> len("")
0
Dept. of CSE, TKMCE 51
The positions of a string’s characters are numbered from 0, on the left, to the length of
the string minus 1, on the right.

The string is an immutable data structure. This means that its internal data elements,
the characters, can be accessed, but cannot be replaced, inserted, or removed.

The Subscript Operator:


a simple for loop can access any of the characters in a string, sometimes you just want
to inspect one character at a given position without visiting them all. The subscript
operator [] makes this possible.
<a string>[<an integer expression>]

Dept. of CSE, TKMCE 52


The integer expression is also called an index.

>>> name = "Alan Turing"


>>> name[0]
'A'
>>> name[3]
'n'
>>> name[len(name)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> name[len(name) - 1]
'g'
>>> name[-l]
'g'
>>> name[-2]
'n'
Dept. of CSE, TKMCE 53
The next code segment uses a count-controlled loop to display the characters and their
positions:

>>> data = "apple"


>>> for index in range(len(data)):
print(index, data[index])

0 a
1 p
2 p
3 l
4 e

Slicing for Substrings


You can use Python’s subscript operator to obtain a substring through a process called
slicing. To extract a substring, the programmer places a colon (:) in the subscript.
Dept. of CSE, TKMCE 54
>>> name = "myfile.txt" # The entire string
>>> name[0 : ]
'myfile.txt'
>>> name[0 : 1] # The first character
'm'
>>> name[ 0 : 2] # The first two characters
'my'
>>> name[ : len(name)] # The entire string
'myfile.txt'
>>> name[-3 : ] # The last three characters
'txt'
>>> name[ 2 : 6] # Drill to extract 'file'
'file'

Dept. of CSE, TKMCE 55


Testing for a Substring with the in Operator
Python’s in operator : We can search for a substring or a character using this operator.

üWhen used with strings, the left operand of in is a target substring, and the right
operand is the string to be searched.
üThe operator in returns True if the target string is somewhere in the search string, or
False otherwise.

eg.,
>>> fileList = ["myfile.txt", "myprogram.exe", "yourfile.txt"]
>>> for fileName in fileList:
if ".txt" in fileName:
print(fileName)
o/p - myfile.txt
yourfile.txt
Dept. of CSE, TKMCE 56
Exercises

1. Assume that the variable data refers to the string "myprogram.exe". Write the values
of the following expressions:
a. data[2]
b. data[-1]
c. len(data)
d. data[0:8]

2. Assume that the variable data refers to the string "myprogram.exe". Write the
expressions that perform the following tasks:
a. Extract the substring "gram" from data.
b. Truncate the extension ".exe" from data.
c. Extract the character at the middle position from data.

Dept. of CSE, TKMCE 57


3. Assume that the variable myString refers to a string. Write a code segment that
uses a loop to print the characters of the string in reverse order.

4. Assume that the variable myString refers to a string, and the variable
reversedString refers to an empty string. Write a loop that adds the characters
from myString to reversedString in reverse order.

Dept. of CSE, TKMCE 58


Number System
The value of each digit in a number can be determined using −
ü The digit
ü The position of the digit in the number
ü The base of the number system (where the base is defined as the total number of
digits available in the number system)

1) decimal number system - base 10 number system


0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 as digits
2) binary number system - base 2 number system
binary 0 and 1
3) octal number system - base 8 number system
0, 1, 2, 3, 4, 5, 6, and 7
4) hexadecimal number system - base 16 number system
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F

Dept. of CSE, TKMCE 59


To identify the system being used, you attach the base as a subscript to the number.

415 in binary notation 1100111112


415 in octal notation 6378
415 in decimal notation 41510
415 in hexadecimal notation 19F16
üThe digits used in each system are counted from 0 to n – 1, where n is the system’s base.
üThus, the digits 8 and 9 do not appear in the octal system.

üTo represent digits with values larger than 910, systems such as base 16 use letters. Thus,
A16 represents the quantity 1010, whereas 1016 represents the quantity 1610

Dept. of CSE, TKMCE 60


The Positional System for Representing Numbers
positional notation—that is, the value of each digit in a number is determined by the
digit’s position in the number. In other words, each digit has a positional value.

How to find positional value of a digit in a number?

The positional value of a digit is determined by raising the base of the system to the
power specified by the position . (baseposition)
For an n-digit number, the positions are numbered from n – 1 down to 0, starting with
the leftmost digit and moving to the right.

eg., the positional values of the three-digit number 41510 are:


100 (10 ) 2 , 10 (10 )1 , and 1 (10 ) 0 , moving from left to right in the number.

Dept. of CSE, TKMCE 61


To determine the quantity represented by a number in any system from base 2 through
base 10, you multiply each digit (as a decimal number) by its positional value and add
the results.

The following example shows how this is done for a three-digit number in base 10:

Dept. of CSE, TKMCE 62


Converting Binary to Decimal
conversion process : Multiply the value of each bit (0 or 1) by its positional value and
add the results.

Dept. of CSE, TKMCE 63


Converts a string of bits to a decimal integer.

bitString = input("Enter a string of bits: ")


decimal = 0
exponent = len(bitString) - 1
for digit in bitString:
decimal = decimal + int(digit) * 2 ** exponent
exponent = exponent - 1
print("The integer value is", decimal)

Enter a string of bits: 1111


The integer value is 15

Dept. of CSE, TKMCE 64


Converting Decimal to Binary
1) This algorithm repeatedly divides the decimal number by 2.
2) After each division, the remainder (either a 0 or a 1) is placed at the beginning of a
string of bits.
3) The quotient becomes the next dividend in the process.
4) The string of bits is initially empty, and the process continues while the decimal
number is greater than 0.

Dept. of CSE, TKMCE 65


decimal = int(input("Enter a decimal number: "))
if decimal == 0:
print(0)
else:
bitString = ""
while decimal > 0:
remainder = decimal % 2
decimal = decimal // 2
bitString = str(remainder) + bitString

print("The binary representation is", bitString)

Enter a decimal number: 156


The binary representation is 00111001

Dept. of CSE, TKMCE 66


Conversion Shortcuts

Dept. of CSE, TKMCE 67


üNote the rows that contain exact powers of 2 (2, 4, and 8 in decimal).
üEach of the corresponding binary numbers in that row contains a 1 followed by a
number of zeroes that equal the exponent used to compute that power of 2.

üThus, a quick way to compute the decimal value of the number 100002 is 24 or 1610.

üThe rows whose binary numbers contain all 1s correspond to decimal numbers that are
one less than the next exact power of 2.

üFor example, the number 1112 equals 23-1 , or 710.


Thus, a quick way to compute the decimal value of the number 111112 is 25 -1 or 3110.

Dept. of CSE, TKMCE 68


Octal Number System
• It requires only 3 bits to represent value of any digit.
• Octal numbers are indicated by the addition of either an 0o prefix or an 8 subscript.
• Position of every digit has a weight which is a power of 8.
• Numeric value of an octal number is determined by multiplying each digit of the
number by its positional value and then adding the products.
• The main advantage of using Octal numbers is that it uses less digits than decimal and
Hexadecimal number system. So, it has fewer computations and less computational
errors.

Dept. of CSE, TKMCE 69


Conversions

Dept. of CSE, TKMCE 70


Binary to Octal Conversion

Dept. of CSE, TKMCE 71


Octal to Binary Conversion

Dept. of CSE, TKMCE 72


Octal to Decimal Conversion

Dept. of CSE, TKMCE 73


Decimal to Octal Conversion

Dept. of CSE, TKMCE 74


Binary to Octal Conversion
bitString = input("Enter a string of bits: ")
decimal = 0
exponent = len(bitString) - 1
for digit in bitString:
decimal = decimal + int(digit) * 2 ** exponent
exponent = exponent - 1

i=1
octal=0
while decimal != 0:
octal += int(decimal % 8)*i
decimal /= 8
i *= 10
print("octal number is: ",octal)
Dept. of CSE, TKMCE 75
Octal to Binary Conversion
oc = int(input("Enter the octal number: "))
dec = 0
i=0
while oc != 0:
dec = dec + (oc % 10) * pow(8,i)
oc = oc // 10
i = i+1

bi = ""
while dec != 0:
rem = dec % 2
dec = dec // 2
bi = str(rem) + bi
print("binary number is:", bi)

Dept. of CSE, TKMCE 76


Hexadecimal Number System
• It requires only 4 bits to represent value of any digit.
• Hexadecimal numbers are indicated by the addition of either an 0x prefix or an 16
as subscript.
• Position of every digit has a weight which is a power of 16.
• Numeric value of a hexadecimal number is determined by multiplying each digit
of the number by its positional value and then adding the products.
• So, it is also a positional (or weighted) number system.

Dept. of CSE, TKMCE 77


Binary to Hexadecimal Conversion
Factor the bits into groups of four and look up the corresponding hex digits.

Dept. of CSE, TKMCE 78


Hexadecimal to Binary Conversion
• Each digit in the hexadecimal number is equivalent to four digits in the binary
number.
• Thus, to convert from hexadecimal to binary, you replace each hexadecimal digit
with the corresponding 4-bit binary number.

Dept. of CSE, TKMCE 79


String Methods
• Python includes a set of string operations called methods.
• A method behaves like a function but has a slightly different syntax.
• Unlike a function, a method is always called with a given data value called an object,
which is placed before the method name in the call.
<an object>.<method name>(<argument-1>,..., <argument-n>)
Methods can also expect arguments and return values.
A method knows about the internal state of the object with which it is called.

Dept. of CSE, TKMCE 80


Dept. of CSE, TKMCE 81
Dept. of CSE, TKMCE 82
some string methods in action:
>> s = "Hi there!" >>> s.isalpha() >>> " ". join(words)
>>> len(s) False 'Hi there!'
9
>>> 'abc'.isalpha() >>> s.lower()
>>> s.center(11)
True 'hi there!'
' Hi there! '
>>> s.count('e') 2 >>> "326".isdigit() >>> s.upper()
>>> s.endswith("there!") True 'HI THERE!'
True
>>> words = s.split() >>> s.replace('i', 'o')
>>> s.startswith("Hi") >>> words 'Ho there!'
True ['Hi', 'there!']
>>> s.find("the")
>>> " ".join(words)
3
'Hithere!'
Dept. of CSE, TKMCE 83
• Extracting a filename’s extension using split() method
• >>> "myfile.txt". split('.')
['myfile', 'txt']
• >>> "myfile.py". split('.')
['myfile', 'py']
• >>> "myfile.html". split('.')
['myfile', 'html']

To write a general expression for obtaining any filename’s extension, as follows:


filename.split('.')[-1]

>>> filename="myfile.txt"
>>> filename.split('.')[-1]
'txt'
Dept. of CSE, TKMCE 84
• Exercises
1. Assume that the variable data refers to the string "Python rules!". Use a string
method from perform the following tasks:
a. Obtain a list of the words in the string.
b. Convert the string to uppercase.
c. Locate the position of the string "rules".
d. Replace the exclamation point with a question mark.

• 2. Using the value of data from Exercise 1, write the values of the following
expressions:
a. data.endswith('i')
b. " totally ". join(data.split())

Dept. of CSE, TKMCE 85


Functions
Functions are the primary and most important method of code organization and
reuse in Python. Functions can also help make your code more readable by giving a name
to a group of Python statements.
Functions are declared with the def keyword and returned from with the return key- word:

def my_function(x, y, z=1.5):


if z > 1:
return z * (x + y)
else:
return z / (x + y)

Dept. of CSE, TKMCE 86


There are many built-in functions provided by Python such as dir(), len(), abs(), etc.
Users can also build their own functions, which are called user-defined functions.
There are many advantages of using functions:

a) They reduce duplication of code in a program.


b) They break the large complex problems into small parts.
c) They help in improving the clarity of code.
d) A piece of code can be reused as many times as we want with the help of functions.

Dept. of CSE, TKMCE 87


When a function is called, any expressions supplied as arguments are first evaluated.
Their values are copied to temporary storage locations named by the parameters in the
function’s definition.
The parameters play the same role as variables in the code that the function then
executes.
A function may have one or more return statements, whose purpose is to terminate the
execution of the function and return control to its caller.
A return statement may be followed by an expression. In that case, Python evaluates the
expression and makes its value available to the caller when the function stops execution.

Dept. of CSE, TKMCE 88


Built-In Functions
• They are already defined in Python Programming Language.
• We can directly invoke them to perform a specific task.

• Examples of Built-In Functions


a) Type Conversion / explicit conversion - int(), float(), char()
b) Type Coercion / implicit conversion
c) Mathematical Functions - sin(), log(), cos(), cosec(), etc.
d) Date and Time
e) dir() Function
f) help() Function

Dept. of CSE, TKMCE 89


ü Functions as Abstraction Mechanisms
ü Functions Eliminate Redundancy
ü Functions Hide Complexity

Dept. of CSE, TKMCE 90


Functions As Abstract Mechanism,
An abstraction hides detail and thus allows a person to view many things as just one thing.
Functions Eliminate Redundancy
The first way that functions serve as abstraction mechanisms is by eliminating redundant,
or repetitious, code.

def summation(lower, upper):


result = 0
while lower <= upper:
result += lower
lower += 1
return result

>>> summation(1,4) #The summation of the numbers 1..4


10
>>> summation(50,100) # The summation of the numbers 50..100
3825

Dept. of CSE, TKMCE 91


User Defined Functions
• Python also allows users to define their own functions.
• To use their own functions in Python, users have to define the function first -
Function Definition.
• In a function definition, users have to define a name for the new function and also
the list of the statements that will execute when the function will be called.
Syntax:
def functionname(parameters):
“function docstring”
statement(s)
return [expression]

Dept. of CSE, TKMCE 92


Parameters and Arguments
They are the values or expressions passed to the functions between paranthesis.
The value of the argument is always assigned to a variable known as parameter.
There can be four types of formal arguments using which a function can be called
which are as follows:

1) Required Arguments
2) Keyword Arguments
3) Default Arguments
4) Variable-length arguments

Dept. of CSE, TKMCE 93


1. Required Arguments : When we assign the parameters to a function at the time of
function definition, at the time of calling, the arguments should be passed to a function
in correct positional order; furthermore, the no: of arguments should match the defined
no: of parameters.

2. Keyword Arguments: The caller recognises the arguments by the parameter's names.
This type of argument can also be out of order.

3. Default Arguments: We can assign a value to a parameter at the time of function


definition. This value is considered the default value to that parameter. If we do not
provide a value to the parameter at the time of calling, it will not produce an error.
Instead it will pick the default value and use it.

4. Variable Length Arguments: The names for these arguments are not specified in the
function definition. Instead we use * before the name of the variable which holds the
value for all non-keyword variable arguments.

Dept. of CSE, TKMCE 94


Function Calls
A function is called using the name with which it was defined earlier, followed by a
pair of parantheses. Any input parameters or arguments are to be placed within
these calling parantheses.
All parameters which are passed in functions are always passed by reference
in Python. This means that if the values of the parameters are changed in the
function, it will also reflect the change in the calling function.

The 'return' Statement


The return statement is used to exit a function.
If a function returns a value, it is passed back by the return statement as argument to
the caller.
If it does n't return a value, we simply write return with no arguments.

Dept. of CSE, TKMCE 95


Design with Recursive Functions
In some cases, you can decompose a complex problem into smaller problems of the
same form. In these cases, the subproblems can all be solved by using the same
function. This design strategy is called recursive design, and the resulting functions
are called recursive functions.

Defining a Recursive Function


A recursive function is a function that calls itself. To prevent a function from repeating
itself indefinitely, it must contain at least one selection statement. This statement
examines a condition called a base case to determine whether to stop or to continue
with another recursive step.

Dept. of CSE, TKMCE 96


def displayRange(lower, upper):
"""Outputs the numbers from lower through upper."""
while lower <= upper:
print(lower)
lower = lower + 1

How would we go about converting this function to a recursive one? First, you should
note two important facts:
1. The loop’s body continues execution while lower <= upper.
2. When the function executes, lower is incremented by 1, but upper never changes

Dept. of CSE, TKMCE 97


def displayRange(lower, upper):
"""Outputs the numbers from lower through upper."""
if lower <= upper:
print(lower)
displayRange(lower + 1, upper)

Dept. of CSE, TKMCE 98


Using Recursive Definitions to Construct Recursive Functions
Define recursive definitions for Fibonacci Series:
Fibonacci sequence is a series of values with a recursive definition. The first and second
numbers in the Fibonacci sequence are 1. Thereafter, each number in the sequence is the
sum of its two predecessors, as follows:
1 1 2 3 5 8 13 . . .

A recursive definition of the nth Fibonacci number is the following:


Fib(n) = 1, when n = 1 or n = 2
Fib(n) = Fib(n - 1) + Fib(n - 2), for all n > 2

def fib(n):
if n < 3:
return 1
else:
return fib(n - 1) + fib(n - 2) Dept. of CSE, TKMCE 99
Factorial using Recursion

Dept. of CSE, TKMCE 100


Infinite Recursion
• When a function continue executing forever, that situation is known as infinite recursion.
• Infinite recursion arises when the programmer fails to specify the base case or to reduce
the size of the problem in a way that terminates the recursive process.
• Infinite recursion arises when the programmer fails to specify the base case or to reduce
the size of the problem in a way that terminates the recursive process.
• This will results in stack overflow error.

>>> def runForever(n):


if n > 0:
runForever(n)
else:
runForever(n - 1)
>>> runForever(1)

Dept. of CSE, TKMCE 101


The Costs and Benefits of Recursion
• At program startup, the PVM reserves an area of memory named a call stack.
• For each call of a function, recursive or otherwise, the PVM must allocate on the call
stack a small chunk of memory called a stack frame.
• In this type of storage, the system places the values of the arguments and the
return address for each function call.
• Space for the function call’s return value is also reserved in its stack frame.
• When a call returns or completes its execution, the return address is used to locate
the next instruction in the caller’s code, and the memory for the stack frame is
deallocated.

Dept. of CSE, TKMCE 102


The stack frames for displayRange(1, 3)
Dept. of CSE, TKMCE 103
Higher-Order Functions
A function is called Higher Order Function if it contains other functions as a parameter
or returns a function as an output.
i.e, The functions that operate with another function are known as Higher order
Functions.

Functions as First-Class Data Objects:


In Python, functions can be treated as first-class data objects. This means that
- they can be assigned to variables
- passed as arguments to other functions
- returned as the values of other functions
- and stored in data structures such as lists and dictionaries.

Dept. of CSE, TKMCE 104


üPassing a function as an argument to another function is no different from passing any
other datum.
üThe function argument is first evaluated, producing the function itself, and then the
parameter name is bound to this value.
üThe function can then be applied to its own argument with the usual syntax.

eg.,
>>> def example(functionArg, dataArg):
return functionArg(dataArg)
>>> example(abs, -4)
4
>>> example(math.sqrt, 2)
1.4142135623730951
Dept. of CSE, TKMCE 105
Mapping, Filtering, Reducing
Mapping : The first type of useful higher-order function to consider is called a mapping.
This process applies a function to each value in a sequence (such as a list, a tuple, or a string) and returns a
new sequence of the results.
Python includes a map function for this purpose.

Suppose we have a list named words that contains strings that represent integers. We want to replace each
string with the corresponding integer value.

>>> words = ["231", "20", "-45", "99"]


>>> map(int, words) # Convert all strings to ints
<map object at 0xl4cbd90>
>>> words # Original list is not changed
['231', '20', '-45', '99']
>>> words = list(map(int, words)) # Reset variable to change it
>>> words
[231, 20, -45, 99]

Dept. of CSE, TKMCE 106


Filtering : A second type of higher-order function is called a filtering. In this process, a
function called a predicate is applied to each value in a list.
If the predicate returns True, the value passes the test and is added to a filter object
(similar to a map object). Otherwise, the value is dropped from consideration.

Python includes a filter function that is used to produce a list of the odd numbers in
another list:

>>> def odd(n):


return n % 2 == 1
>>> list(filter(odd, range(10)))
[1, 3, 5, 7, 9]

Dept. of CSE, TKMCE 107


Reducing: Here we take a list of values and repeatedly apply a function to accumulate a
single data value. A summation is a good example of this process. The first value is added
to the second value, then the sum is added to the third value, and so on, until the sum of
all the values is produced.

eg.,
>>> from functools import reduce
>>> def add(x, y): return x + y
>>> def multiply(x, y): return x * y
>>> data = [1, 2, 3, 4]
>>> reduce(add, data)
10
>>> reduce(multiply, data)
24

Dept. of CSE, TKMCE 108


Boolean Functions
• A Boolean function usually tests its argument for the presence or absence of some property.
• The function returns True if the property is present, or False otherwise.

def odd(x):
"""Returns True if x is odd or False otherwise."""
if x % 2 == 1:
return True
else:
return False

>>> odd(5)
True

Dept. of CSE, TKMCE 109


Using lambda to Create Anonymous Functions
• Python includes a mechanism called lambda that allows the programmer to create
functions in this manner.
• A lambda is an anonymous function. It has no name of its own, but it contains the
names of its arguments as well as a single expression.
• When the lambda is applied to its arguments, its expression is evaluated, and its
value is returned.

The syntax of a lambda is very tight and restrictive:


lambda <argname-1, ..., argname-n>: <expression>

>>> mul = lambda a,b : a*b


>>> print(mul(12,12))
144

Dept. of CSE, TKMCE 110


Use of range, reduce, and lambda to simplify the definition of the summation
function

from functools import reduce


def summation(lower, upper)
if lower > upper:
return 0
else:
return reduce(lambda x,y : x+y , range(lower,upper+1))

Dept. of CSE, TKMCE 111


Dept. of CSE, TKMCE 112

You might also like