M2 - Python For Machine Learning - Maria S
M2 - Python For Machine Learning - Maria S
M2 - Python For Machine Learning - Maria S
Category : Minor
Offered by : Dept. of Computer Science and Engg.
Faculty in charge : Jaseela Beevi S
üThe simplest form of selection is the if statement. This type of control statement
is also called a one-way selection statement.
if <condition>:
<sequence of 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>
• 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.
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")
• The two conditions can be combined in a Boolean expression that uses the logical operator
or. The resulting expression is compound Boolean expression
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.
üthose that perform the action until the program determines that it
needs to stop (indefinite iteration).
• 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.
#computation of 23
>>> number = 2
>>> exponent = 3
>>> product = 1
>>> for eachPass in range(exponent):
product = product * number
print(product, end = " ")
248
>>> product
8
55
ü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"
• For the most part, off-by-one errors result when the programmer incorrectly
specifies the upper bound of the loop.
Strings are also sequences of characters. The values contained in any sequence can
be visited by running a for loop, as follows:
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 use a field width of 6 and a precision of 3 to format the float value 3.14:
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>
• 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.
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.
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. *
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
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.
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.
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.
A string’s length is the number of characters it contains. Python’s len function returns
this value when it is passed a string.
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.
0 a
1 p
2 p
3 l
4 e
ü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.
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.
ü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
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.
The following example shows how this is done for a three-digit number in base 10:
ü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.
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)
>>> 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())
1) Required Arguments
2) Keyword Arguments
3) Default Arguments
4) Variable-length arguments
2. Keyword Arguments: The caller recognises the arguments by the parameter's names.
This type of argument can also be out of order.
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.
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
def fib(n):
if n < 3:
return 1
else:
return fib(n - 1) + fib(n - 2) Dept. of CSE, TKMCE 99
Factorial using Recursion
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.
Python includes a filter function that is used to produce a list of the odd numbers in
another list:
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
def odd(x):
"""Returns True if x is odd or False otherwise."""
if x % 2 == 1:
return True
else:
return False
>>> odd(5)
True