Module 4 - Python
Module 4 - Python
2.3.2Raw Strings
If you want to specify a string that should not handle any escape sequences
and want to display exactly as specified then you need to specify that string as
a raw string. A raw string is specified by prefixing r or R to the string.
3. Data types
The variables can hold values of different type called Data Type.
Data type is a set of values and the allowable operations on those values.
Python has a great set of useful data types. Python's data types are built in
the core of the language. They are easy to use and straightforward.
Data
Types
Dictionar
Numbers String Boolean Tuples Lists Sets
ies
3.3 Tuples
A tuple is similar to the list as it also consists of a number of values
separated by commas and enclosed within parentheses.
The main difference between lists and tuples is that you can change the
values in a list but not in a tuple. This means that while tuple is a read only
data type, the list is not.
Note: For writing Multi line comments. Make sure to indent the leading „ „ „
appropriately to avoid an Indentation Error
„„„
This is a multiline
comment.
„„„
8. Indentation
Whitespace at the beginning of the line is called indentation. These
whitespaces or the indentation are very important in Python.
In a Python program, the leading whitespace including spaces and tabs at
the beginning of the logical line determines the indentation level of that logical
line.
1.String concatenation.
2.String repetition or multiplication.
3.String slicing.
10.1String Concatenation
Like numbers we can add two strings in Python. The process of combining
two strings is called concatenation.
Two strings whether created using single or double quote are concatenated
in the same way. Look at the codes given in the following example.
Example: Codes to demonstrate how easily two strings are concatenated.
>>>print(“hello” + “-world”)
output
hello-world
>>>print(―hello‖+‘-world’)
output
hello-world
>>print(‗hello’+‘-world’)
output
hello-world.
Note:we cannot add string to number which generates an error.
10.2 String Repetition or Multiplication
You cannot add string and number but we can multiply string and number
with the help of this string repetition.
When a string is multiplied with an integer n, then the string is repeted n
times.
Thus, the * operator is also called as string repetition operator.
The order of string and integer is not important.
Example
Un-conditional Control:
if Statement
if-else Statement
Nested if statement
if-elif-else statement.
1. 1 if Statement:
An if statement is a selection control statement which is based on the value
of a given Boolean Expression.
Syntax:
if test_expression:
statement 1
.....
statement n
statement x
if structure may include 1 or n statements enclosed within if block.
Python supports if-elif-else statements to test additional conditions apart from the initial
test expression.
The if-elif-else construct works in the same way as a usual if-else statement.
If-elif-else construct is also known as nested-if construct.
A series of if and elif statements have a final else block, which is executed if none of the if
or elif expressions is True.
Syntax:
if (test expression 1):
statement block1
elif (test expression 2):
statement block2
. . . . . . . . . . . . . . ..
elif( test expression N):
statement block N
else:
statement block X
Flowchart:
If the condition is TRUE, only then the statements will be executed
otherwise if the condition is False, the control will jump to statement y, that is
the immediate statement outside the while loop block.
Flowchart:
o If range( ) is called with two arguments, it produces values from the first to
the second. For example, range (0, 10) gives 0-9.
o If range( ) has three arguments then the third argument specifies the interval
of the sequence produced. In this case, the third argument must be an integer.
For example, range(1, 20, 3) gives 1, 4, 7, 10, 13, 16, 19.
Example:
1. Program that accepts an integer (n) and computes the value of n+nn+nnn.
(Eg. If n=5, find 5+55+555).
n = int(input("Enter a number: "))
str_n = str(n)
sum = n
sum_str = str(n)
for i in range(1, 3):
sum_str = sum_str + str_n
sum = sum + int(sum_str)
print(sum)
2. Program that accepts a word from the user and reverse it
s = input("Enter a word: ")
str = ""
for i in s:
str = i + str
print("Reverse of", s, "is:", str)
2.3 Nested Loops :
Python allows its users to have nested loops, that is, loops that can be
placed inside other loops.
Although this feature will work with any loop like while loop as well as for
loop.
A for loop can be used to control the number of times a particular set of
statements will be executed.
Another outer loop could be used to control the number of times that a
whole loop is repeated.
The break statement is widely used with for loop and while loop.
Hence, the break statement is used to exit a loop from any point with in its
body, by passing its normal termination expression. Below, Figure shows the
transfer of control when the break statement is encountered.
Like the break statement, the continue statement can only appear in the
body of a loop.
When the compiler encounters a continue statement then the rest of the
statements in the loop are skipped and the control is unconditionally
transferred to the loop-continuation portion of the nearest enclosing loop.
Syntax:
Continue
Example: Program to demonstrate continue statement
It can be concluded that the continue statement is somewhat the opposite
of the break statement. It forces the next iteration of the loop to take place,
skipping any code in between itself and the test condition of the loop.
The difference between a comment and pass statement is that while the
interpreter ignores a comment entirely, pass is not ignored.
The break statement terminates the execution of the nearest enclosing loop
in which it appears.
The continue statement skips the rest of the statements in the loop
transfer the control un-conditionally to the loop-continuation portion of the
nearest enclosing loop.
In Python you can have the else statement associated with a loop
statements.
If the else statement is used with a for loop, the else statement is executed
when the loop has completed iterating.
But when used with the while loop, the else statement is executed when
the condition becomes false.
Examples:
3. Programs:
3. 1 Write a python program to Test whether a given number is even or odd.
num = int(input("Enter a number: "))
if (num % 2==0):
print(num, "is an even number.")
else:
print(num, "is an odd number.")
Output:
Enter a number: 5
5 is an odd number.
3. 2 Write a python program to Print out the decimal equivalents of 1/1, 1/2,
1/3, 1/4........1/10 using for loop.
i=1
for i in range(1,11):
value=1.0/i
print("1/", i, "=", value)
Output:
1/ 1 = 1.0
1/ 2 = 0.5
1/ 3 = 0.333333333333
1/ 4 = 0.25
1/ 5 = 0.2
1/ 6 = 0.166666666667
1/ 7 = 0.142857142857
1/ 8 = 0.125
6. Explain the utility of break and continue statements with the help of an
example.
10. Write a Python program that accepts a word from the user and reverse it
11. Write a Python program that accepts an integer (n) and computes the value
of n+nn+nnn. (Eg. If n=5, find 5+55+555).
Figure 10: lists the differences between global and local variables.
Comparison between global and Local variables
local variables Global variables
They are defined in the main body They are defined within a function and is local
of the program file. to that function.
They can be accessed throughout They can be accessed from the point of its
the program life. definition until the end of the block in which
it is defined.
Global variables are accessible to They are not related in any way to other
all functions in the program. variables with the same names used outside
the function.
Using the Global Statement
To define a variable defined inside a function as global, you must use the global
statement. This declares the local or the inner variable of the function to have
module scope.
Key points to remember:
You can have a variable with the same name as that of a global variable in the
program. In such a case a new local variable of that name is created which is
different from the global variable.
Keyword Arguments
When we call a function with some values, the values are assigned to the
arguments based on their position. Python also allow functions to be called
using keyword arguments in which the order (or position) of the arguments can
be changed. The values are not assigned to arguments according to their
position but based on their name (or keyword).
Keyword arguments are beneficial in two cases.
First, if you skip arguments.
Second, if in the function call you change the order of parameters.
Example:
Variable-length Arguments
In some situations, it is not known in advance how many arguments will be
passed to a function. In such cases, Python allows programmers to make
function calls with arbitrary (or any) number of arguments.
When we use arbitrary arguments or variable length arguments, then the
function definition use an asterisk (*) before the parameter name. The syntax
for a function using variable arguments can be given as,
Example
Documentation Strings
Docstrings (documentation strings) serve the same purpose as that of
comments, as they are designed to explain code. However, they are more
specific and have a proper syntax.
Recursive Functions
A recursive function is defined as a function that calls itself to solve a smaller
version of its task until a final call is made which does not require a call to
itself. Every recursive solution has two major cases, which are as follows:
base case, in which the problem is simple enough to be solved directly
without making any further calls to the same function.
recursive case, in which first the problem at hand is divided into simpler
sub parts.
Recursion utilized divide and conquer technique of problem solving.
Example:
Recursion vs Iteration:
To import more than one item from a module, use a comma separated list. For
example, to import the value of pi and sqrt() from the math module you can
write,
3. Find the sum of the even-valued terms in the Fibonacci sequence whose
values do not exceed ten thousand.
Strings
Python treats strings as contiguous series of characters delimited by
single, double or even triple quotes. Python has a built-in string class
named "str" that has many useful features. We can simultaneously
declare and define a string by creating a variable of string type. This can
be done in several ways which are as follows:
name = "India" graduate = 'N' country = name nationality = str("Indian")
Indexing: Individual characters in a string are accessed using the
subscript ([ ]) operator. The expression in brackets is called an index. The
index specifies a member of an ordered set and in this case it specifies
the character we want to access from the given set of characters in the
string.
The index of the first character is 0 and that of the last character is n-1
where n is the number of characters in the string. If you try to exceed the
bounds (below 0 or above n-1), then an error is raised.
--------- to be continued