Python Unit- 1
Python Unit- 1
• In immediate mode, you type Python expressions into the Python Interpreter window, and the
interpreter immediately shows the result.
• Alternatively, you can write a program in a file and use the interpreter to execute the contents of the
file. Such a file is called a script. Scripts have the advantage that they can be saved to disk, printed, and so on.
4. What is meant by value in python?
A value is one of the fundamental things—like a letter or a number— that a program manipulates.
5. List the standard data types in python.
Python has five standard data
Types:
• Numbers
• Strings
• List,
• Tuples
• Dictionary
6. What is meant by python numbers?
Number data types store numeric values. Number objects are created when you assign a value to them.
Python supports four different numerical types :
• int (signed integers)
• long (long integers, they can also be represented in octal and
• hexadecimal)
• float (floating point real values)
• complex (complex numbers)
16.What is a statement?
A statement is an instruction that the Python interpreter can execute. When you type a statement on the
command line, Python executes it. Statements don‘t produce any result. For example, a = 1 is an assignment
statement. if statement, for statement, while statement etc. are other kinds of statements.
• Python does not require explicit memory management as the interpreter itself • allocates the
memory to new variables and free them automatically Provide easy readability due to use of
square brackets
• Easy-to-learn for beginners
• Having the built-in data types saves programming time and effort from declaring variables
26.Define module.
A module is a file containing Python definitions and statements. The file name is the module name with the
suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global
variable Name.
Ans:
The purpose of a for loop in Python is to iterate over a sequence (such as a list, tuple, or string) or any iterable
object, executing a block of code for each item in the sequence.
31.How does a while loop differ from a for loop in Python?
Ans:
A while loop in Python continues iterating until a specified condition evaluates to False, whereas a for loop
iterates over a sequence or an iterable object for a predetermined number of times.
32.Explain the role of the range() function in a for loop.
Ans :
The range() function generates a sequence of numbers that are commonly used to iterate over a specific range
in a for loop. It is often used to specify the number of iterations or to generate indices for elements in a
sequence.
33.What is an infinite loop? Provide an example.
Ans:
An infinite loop is a loop that continues indefinitely without a stopping condition.
An example of an infinite loop in Python is:
while True:
print("This is an infinite loop")
34.Describe the break statement and its usage in a loop.
Ans :
The break statement is used to exit a loop prematurely based on a certain condition. When encountered, it
immediately terminates the loop and continues with the next statement outside the loop.
35.How does the continue statement differ from the break statement?
Ans:
The continue statement skips the rest of the current iteration of a loop and continues with the next iteration.
Unlike break, it doesn't exit the loop entirely; it just moves to the next iteration.
36.Explain the concept of nested loops with an example.
Ans:
Nested loops in Python refer to having one loop inside another. This allows for iterating over multiple
sequences or performing repetitive tasks within a loop.
An example of nested loops:
for i in range(3): for j in range(2):
print(i, j)
37.Describe the significance of the enumerate() function in a for loop.
Ans:
The enumerate() function is used in conjunction with a for loop to iterate over a sequence while also keeping
track of the index of each item. It returns tuples containing the index and the corresponding item from the
iterable.
38.What is the purpose of the else block in a for loop?
Give an example. Ans:
The else block in a for loop is executed when the loop completes all iterations without encountering a break
statement. It is typically used for cleanup or finalization tasks.
Example:
for i in range(5): print(i)
else:
print("Loop completed without a break")
39.Discuss the role of the pass statement in Python loops.
Ans:
The pass statement is a null operation in Python. It acts as a placeholder when a statement is syntactically
required but no action needs to be taken. It is often used as a placeholder for loops or function definitions that
are yet to be implemented.
A function is a named container for a block of code. (or) It is a block of statements that will execute for a specific
task.
Functions are nothing but a groupof related statements that perform a specific task.
Built – in functions.
Lambda functions.
Recursive functions.
Lambda function is mostly used for creating small and one-time anonymous function.
Lambda functions are mainly used in combination with the functions like filter(), map() and reduce().
Lambda function can take any number of arguments and must return one value in the form of an expression.
Function blocks begin with the keyword “def” followed by function name and parenthesis ().
The code block always comes after a colon (:) and is indented.
A recursive definition is similar to a circular definition, i.e., “function call itself” this is known as recursion.
Syntax:
def function_name(a):
------------
------------
function_name(b)
------------
abs ( ), ord ( ), bin ( ), min ( ), max( ), sum( ), round( ), pow( ), sqrt( ), floor( ).
1. Functions help us to divide a program into modules. This makes the code easier to
manage.
2. It implements code reuse. Every time you need to execute a sequence of statements, all
3. Functions, allows us to change functionality easily, and different programmers can work on different
functions.
All variables in a program may not be accessible at all locations in that program. This depends on where you
have declared a variable. The scope of a variable determines the portion of the program where you can access
a particular identifier.
There are two basic scopes of variables in Python:
Global variables , Local variables
49.DEFINE GLOBAL SCOPE.
A variable, with global scope can be used anywhere in the program. It can be created by
When you call the “hello()” function, the program displays the following string as
output:
def hello():
return
print (hello())
Output:
hello – Python
None
In situation to call one function from within another function. This ability is called composition.
For example, if we wish to take a numeric value or an expression as a input from the user, we take the input
string from the user using the function input() and apply eval() function to evaluate its value.
The condition thatis applied in any recursive function is known as base condition. A base condition is must
inevery recursive function otherwise it will continue to execute like an infinite loop.
Data sent to one function from another is called parameter. There are two types of parameters are available in
general, they are given below.
a. Formal parameter
b. Actual Parameter
SYNTAX:
def function_name (parameter(s) separated by comma):
The return statement is used when a function is ready to return a value to its caller. So,
only one return statement is executed at run time even though the function contains
multiple return statements.
SYNTAX: return [expression list ]
Required arguments
Keyword arguments
Default arguments
Variable-length arguments.
58.DEFINE ANONYMUOS FUNCTIONS.
normal functions are defined using the def keyword, in Python anonymous functions are
defined using the lambda keyword. Hence, anonymous functions are also called as lambda
functions.
Functions that return values are sometimes called fruitful functions. In many other languages, a function that
doesn’t return a value is called a procedure, but we will stick here with the Python way of also calling it a
function, or if we want to stress it, a non- fruitful function.
A list in Python is known as a “sequence data type” like strings. It is an ordered collection of values enclosed
within square brackets [ ]. Each value of a list is called as element. It can be of any type such as numbers,
characters, strings and even the nested lists as well. The elements can be modified or mutable which means the
elements can be replaced, added or removed.
In python, a list is simply created by using square bracket. The elements of list should be specified within square
brackets. The following syntax explains the creation of list.
Syntax:
Python assigns an automatic index value for each element of a list begins with zero. Index value can be used to
access an element in a list. In python, index value is an integer number which can be positive or negative.
Eg:
Marks 10 23 41 75
Index (positive integer) 0 1 2 3
Index(negative integer) -4 -3 -2 -1
i=0
while i < 4:
print (Marks[i])
i=i+1
Python enables reverse or negative indexing for the list elements. Thus, python lists index in opposite order. The
python sets -1 as the index value for the last element in list and -2 for the preceding element and so on. This is
called as Reverse Indexing.
The len( ) function in Python is used to find the length of a list. (i.e., the number of elements in a list). Usually,
the len( ) function is used to set the upper limit in a loop to read all the elements of a list.
len(MySubject)
Output: 4
i=0
print (MySubject[i])
i=i+1
Output:
Tamil
English
Comp. Science
Maths
69. How to access elements in a list using for loop? Give the syntax.
In Python, the for loop is used to access all the elements in a list one by one. This is just like the for keyword in
other programming language such as C++.
Syntax:
print (index_var)
Here, index_var represents the index value of each element in the list.
70. How to change elements in a list? Give syntax.
In Python, the lists are mutable, which means they can be changed. A list element or range of elements can be
changed or altered by using simple assignment operator (=).
Syntax:
In Python, append( ) function is used to add a single element and extend( ) function is used to add more than
one element to an existing list.
Syntax:
In extend( ) function, multiple elements should be specified within square bracket as arguments of the function.
Eg:
print(Mylist)
Output:
append() extend()
append( ) function is used to add a single In extend( ) function, multiple elements should
element and extend( ) function is used to add be specified within square bracket as
more than one element to an existing list. arguments of the function.
If you want to include an element at your desired position, you can use insert ( ) function. The insert( ) function
is used to insert an element at any position of a list.
Eg:
MyList.insert(3, 'Ramakrishnan')
print(MyList)
Output:
del statement is used to delete elements whose index is known. The del statement can also be used to delete
entire list.
Eg:
del MySubjects[1]
print (MySubjects)
pop() remove()
The remove( ) function can also be used to pop( ) function can also be used to delete an
delete one or more elements if the index value element using the given index value. pop( )
is not known. function deletes and returns the last element of
a list if the index is not given.
The function clear( ) is used to delete all the elements in list, it deletes only the elements and retains the list.
Eg:
MyList=[12,89,34,54,70]
MyList.clear( )
print(MyList)
Output: []
78. squares = [ ]
for x in range(1,11):
s = x ** 2
squares.append(s)
print (squares)
79. s=[ ]
for i in range(21):
if (i%4==0):
s.append(i)
print(s)
PART-B
Five mark Questions
1) Sketch the structure of interpreter and compiler. Detail the differences between them. Explain how python
works in interactive mode and script mode with examples.
Interpreter:
It is a program that reads the high level program (source code) and executes the program line by line. Then,
finally performs computations and prints the output. Thus, the structure of interpreter is shown below.
Compiler:
A compiler is a computer program that transforms code written in a high-level programming language into the
machine code. It is a program which translates the human-readable code to a language a computer processor
understands (binary 1 and 0 bits). The computer processes the machine code to perform the corresponding
tasks.
Script mode:
It is used when the user is working with more than one single code or a block of code.
Example:
squ=26 print(squ*2)
Interactive mode:
Interactive mode is used when a user wants to run one single line or one block of code.
It runs very quickly and gives the output instantly.
Example:
>>>squ=26
>>>print(squ*2)
676
2. What is a numeric literal? Give example.
•A numeric literal is a literal containing only the numeric or digits (0 – 9)
•An optional sign is + or -.
•If a numeric literal contains a decimal point, then it denotes a real value or float.
Example:
12.21
10.00
00.02
•Or, it denotes an integer value.
Example:
12
21
•Commas are never used in numeric literals.
Example:
12,500 (Invalid)
12500 (Valid)
General Example:
3. Define variable. And explain how to declare variable and explain about the scope of the variable.
A variable is nothing but a ‘reserved memory location to store values’. In other words a variable in a program
‘gives data to the computer to work on’.
Every value in Python has a data type. Different data types in Python are Numbers, List, Tuple, Strings,
Dictionary, etc. Variables can be declared by any name or even alphabets like a, aa, abc etc.
Let see an example with declare variable “b” and print it.
b=200
print ( b )
Re-declare a Variable
In this re-declare the variable even after you have declared it once.
Here variable initialized to c=0.
Later, re-assign the variable f to value “welcome”
#Declare a variable and initialize it c = 0;
Print (c)
#re-declaring the variable works C = “welcome” Print (c) Output
0
Welcome
Delete a variable
In delete variable using the command del ”variable name”. In the example below, deleted variable f and when
proceed to print it, get error “variable name is not defined” which means it has deleted the variable. #Declare a
variable and initialize it b = 102; print (b) del b print (b)
NameError: name ‘b’ is not defined
Swap variables
Python swap values in a single line and this applies to all objects in python.
Syntax :
var1, var2 = var2, var1
Scope of the variable
There are two types are available, they are given below.
(i) Local variable
(ii) Global variable
Local & Global Variables
In Python use the same variable for rest of the program or module and declare it global variable, while if want
to use the variable in a specific function or method you use local variable.
Let’s understand this difference between local and global variable with the below program.
Variable “f” is global in scope and is assigned value 101 which is printed in output
Variable f is again declared in function and assumes local scope. It is assigned value “God is great.” which is
printed out as an output. This variable is different from the global variable “f” define earlier
Once the function call is over, the local variable f is destroyed. When it again, print the value of “f” is it displays
the value of global variable f=101.
Example 1:
#Declare a variable and initialize it f
= 101
Print (f)
#Global vs. local variables in functions def someFunction(): #global f f = “God is great” print (f)
somefunction () print
(f)
Output
101
God is great
101
Example 2:
f = 101;
print (f) #Global vs. local variables in function def
someFunction():
global f print
(f) f = “changing global variable”
someFunction ()
print (f) Output 101 101 changing global variable
Single line comments is good for a short, quick comment (or for debugging), while the block comments is often
used to describe something much more in detail or to block out an entire chunk of code.
A hash sign (#) that is not inside a string literal is the beginning of a comment. All characters after the #, up to
the end of the physical line, are part of the comment and the Python interpreter ignores them.
Single line comment
A single line comment starts with the number sign (#) character:
# This is a comment print(‘Hello’)
For each line you want to comment, put the number sign (#) in front.
# print(‘This is not run’) print(‘Hello’)
Multiline comment
Multiple lines can be created by repeating the number sign several times:
# This is a comment # second line x = 4
but this quickly becomes impractical. A common way to use comments for multiple lines
is to use the (”’) symbol:
‘’’ This is a multiline Python comment example.’’’
While Loop:
The while loop in Python is used to execute a block of code repeatedly as long as a specified condition is True.
Syntax:
While condition: Explanation:
The loop continues executing the code block as long as the specified condition evaluates to True.
The condition is checked before each iteration. If it evaluates to False, the loop terminates.
Example: i = 0
while i < 5: print(i)
i += 1
Output:
1
2
3
Example:
for i in range(5): if i == 3:
break elif i == 2:
continue else:
pass print(i)
Output:
0
1
7 . Explain the role of the else block in Python loops.
Ans:
In Python, the else block in a loop serves a specific purpose that might be a bit surprising at first glance.
Basic Understanding:
The else block in a loop is executed when the loop completes all iterations without encountering a break
statement.
This behavior might seem counterintuitive at first because in most other programming languages, the else block
is associated with conditionals (like if), not loops.
Execution Condition:
The else block in a loop executes only if the loop completes normally, without being interrupted by a break
statement.
If a break statement is encountered within the loop, the else block is skipped, and the control moves to the
statement immediately following the loop.
Use Cases:
The else block in loops can be used for cleanup or finalization tasks that need to be performed after all
iterations are completed.
It's also useful for handling scenarios where a specific condition is not met within the loop but is expected to be
met under normal circumstances.
Example:
numbers = [1, 2, 3, 4, 5] for num in numbers:
if num == 6:
•In this example, the loop iterates over the numbers list and checks if 6 is present. If it finds 6, it prints "Number
found!" and exits the loop using break.
•If the loop completes all iterations without finding 6, the else block is executed, and "Number not found!" is
printed.
•Alternative Use:
While the else block in loops is primarily used for cleanup or finalization tasks, it can also be used in conjunction
with certain conditions to handle specific scenarios more elegantly.
•Conclusion:
The else block in Python loops provides a mechanism to execute code after all iterations are completed, but
only if the loop completes normally without being interrupted by a break statement.
8.Describe the purpose of the range() function in Python loops. Provide examples.
Ans:
The range() function in Python is a versatile tool primarily used in loops to generate a sequence of numbers. Its
purpose is to simplify the creation of sequences that are commonly used for iterating over a specific range of
values. Here's a detailed explanation:
•Basic Functionality:
The range() function generates a sequence of numbers according to the specified parameters.
It can take one, two, or three arguments to define the start, stop, and step values for the sequence.
•Syntax:
The syntax for the range() function is as follows: range(stop)
range(start, stop[, step])
•Usage in Loops:
The range() function is commonly used in for loops to iterate over a specific range of values.
It generates the sequence of numbers that determine the number of iterations for the loop.
•Examples:
Using range() with a single argument (stop):
Output:
0
1
2
3
4
Using range() with two arguments (start, stop):
3
In this example, the loop terminates when the value 4 is encountered in the numbers list. As a result, the loop
stops executing, and the subsequent iterations are not processed.
Continue Statement:
• The continue statement is used to skip the remaining code within the current iteration of the loop and
proceed to the next iteration.
• Example:
numbers = [1, 2, 3, 4, 5] for num in numbers:
if num % 2 == 0: continue
print(num)
Output:
1
3
5
In this example, the loop skips printing even numbers (num % 2 == 0) and continues to the next iteration. Only
odd numbers are printed.
• Pass statement:
• The pass statement is a null operation that does nothing. It acts as a placeholder when no action is
required, ensuring that the syntax is valid.
• Example:
for i in range(5): if i == 3:
pass else:
print(i)
Output:
0
1
2
4
• In this example, when i equals 3, the pass statement is executed, and nothing happens.
Conclusion:
o Loop control statements (break, continue, pass) provide flexibility and control over the execution flow
within loops in Python.
10.Create a Python program that demonstrates various types of loops and their usage.
PROGRAM:
def main():
print("Numbers from 1 to 5 using a for loop:") for i in range(1, 6):
print(i)
print("\nNumbers from 1 to 5 using a while loop:") i = 1
while i <= 5: print(i)
i += 1
print("\nNumbers from 1 to 10 with a break statement:") for i in range(1, 11):
if i == 6:
break # Terminate the loop when i equals 6 print(i)
# Using continue statement to skip certain iterations
Output:
Numbers from 1 to 5 using a for loop: 1
2
3
4
5
Numbers from 1 to 5 using a while loop: 1
2
3
4
5
Numbers from 1 to 10 with a break statement: 1
2
3
4
5
Numbers from 1 to 10 skipping multiples of 3:
1
2
4
5
7
8
10
A function is a named container for a block of code. (or) It is a block of statements that will execute for a specific
task.
Functions are nothing but a groupof related statements that perform a specific task.
TYPES:
User – defined functions.
Built – in functions.
Lambda functions.
Recursive functions.
Function blocks begin with the keyword “def” followed by function name and parenthesis ().
The code block always comes after a colon (:) and is indented.
BUILT- IN FUNCTIONS:
LAMBDA FUNCTIONS:
12.WRITE A PYTHON CODE TO FIND GIVEN NUMBER IS PRIME OR NOT USING FUNCTIONS.
def is_prime(number):
if number <= 1:
return False
if number % i == 0:
return False
return True
# Test the function
num = 17
if is_prime(num):
else:
OUTPUT:
17 is a prime number.
The user can not only pass a parameter value into a function, a function can also produce a value.
Functions that return values are sometimes called fruitful functions. In many other languages, a
function that doesn’t return a value is called a procedure, but we will stick here with the Python way of
also calling it a function, or if we want to stress it, a non-fruitful function.
The square function will take one number as a parameter and return the result of squaring that
number. Here is the black-box diagram with the Python code following.
The return statement is followed by an expression which is evaluated. Its result is returned to the caller
as the “fruit” of calling this function.
Example:
def add(a,b):
c=a+b
return c
x = int(input(“Enter Number1:”))
y = int(input(“Enter Number2:”))
z=add(x,y)
Output:
Enter number1:12
Enter number2:25
Parameter is the “input data that is sent from function call to function definition”.
Types:
(ii) Formal parameters : This parameter defined as the part of function definition.
Output:
16. What the different ways to insert an element in a list. Explain with suitable example.
Example:
>>>My list= [34,45,48]
>>>Mylist.append (90)
>>> print (Mylist)
[34,45,48,90]
In the above example, Mylist is created with three elements. Through Mylist.append(90) statement, an
additional value 90 is included with the existing list as last element.
extend() function:
extend() function is used to add more than one element to an existing list.
Syntax:
List.extend ([elements to be added])
Example:
In extend () function, multiple elements should be specified within square bracket as arguments of the
function.
>>>Mylist= [34,45,48]
>>>Mylist.extend([71, 32, 29])
>>>print(Mylist)
[34,45,48, 90, 71, 32,29]
In the above code, extend( ) function is used to include multiple elements, the print statement shows all the
elements of the list after the inclusion of additional elements.
insert() function:
• Append () function in Python is used to add more elements in a list. But, it includes elements at the end
of a list.
• To include an element at your desired position, use the insert () function. The insert() function is used
to insert an element at any position of a list.
• Syntax:
List, insert (position index, element)
Example:
>>>MyList= [34,98,47 .Kannan7, ‘Gowrisankar7, ‘Lenin7, ‘Sreenivasan7]
>>>print(MyList)
[34, 98,47, ‘Karman7, ‘Gowrisankar7, ‘Lenin7, ‘Sreenivasan’]
>>>MyList.insert(3, ‘Rarnakrishnan’)
>>>print(MyList)
[34,98,47, ‘Rarnakrishnan7, ‘Karman7, ‘Gowrisankar7, ‘Lenin7, ‘Sreenivasan’]
17. Explain
18. How can you iterate over the elements of a list in Python using a for loop?
Iterating over the elements of a list using a for loop in Python is a fundamental concept for processing data
stored in lists. Below is an explanation along with examples:
Here, element is a variable that will take on each value in the my_list sequentially.
Example:
numbers = [1, 2, 3, 4, 5]
This code will output each element of the list numbers on a new line.
Processing elements:
Within the loop body, you can perform any operation based on the current element being iterated over. For
instance, you can perform arithmetic operations, modify elements, or even filter elements based on certain
conditions.
squared_numbers = []
print(squared_numbers)
This code will square each number in the numbers list and store the results in the squared_numbers list.
Using Enumerate:
Sometimes, it's useful to have both the index and the value of each element in the list. Python's enumerate()
function helps in such scenarios:
The code will output the index and value of each element in the ‘number’ list.
List slicing in Python is a powerful technique used to extract a portion of elements from a list based on specified
indices. It allows for the creation of new lists containing a subset of elements from the original list. The syntax
for list slicing is as follows:
new_list = original_list[start:stop:step]
Where:
start: The starting index of the slice. It indicates where the slicing begins. If not specified, slicing starts from the
beginning of the list (index 0).
stop: The ending index of the slice. It indicates where the slicing ends. The slice will include elements up to, but
not including, the element at this index.
step: The step size used to specify how many elements to skip. If not specified, the default step size is 1.
List slicing provides flexibility in extracting elements from lists, making it a fundamental feature in Python
programming. Here are examples illustrating various aspects of list slicing:
Basic Slicing:
original_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
sliced_list = original_list[2:5]
# Output: [2, 3, 4]
sliced_list = original_list[0:7:2]
# Output: [0, 2, 4, 6]
# Output: [7, 8, 9]
sliced_list = original_list[:-4]
# Output: [0, 1, 2, 3, 4, 5]
Omitting Indices:
sliced_list = original_list[:6]
# Output: [0, 1, 2, 3, 4, 5]
sliced_list = original_list[3:]
# Output: [3, 4, 5, 6, 7, 8, 9]
# Slice the entire list (creates a shallow copy of the original list)
sliced_list = original_list[:]
# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Can be iterated over using loops or Can be iterated over similarly to lists. Iteration is
Iteration comprehensions. generally faster due to immutability.
PART-C
Ten mark Questions
1. Explain the different types of operators in python.
In computer programming languages operators are special symbols which represent computations, conditional
matching etc. The value of an operator used is called operands. Operators are categorized as Arithmetic,
Relational, Logical, Assignment etc. Value and variables when used with operator are known as operands.
Arithmetic operators:
An arithmetic operator is a mathematical operator that takes two operands and performs a calculation on
them. They are used for simple arithmetic. Most computer languages contain a set of such operators that
can be used within equations to perform different types of sequential calculations.
Eg:
a=100
b=10
Output:
The Difference = 90
The Remainder = 10
A Relational operator is also called as Comparative operator which checks the relationship between two
operands. If the relation is true, it returns True; otherwise it returns False.
Eg:
Output:
A = 35 and B = 56
The a != b = True
Logical operators:
In python, Logical operators are used to perform logical operations on the given relational expressions. There
are three logical operators they are and, or and not.
Eg:
Output:
A = 50 and b = 40
Assignment operators:
In Python, = is a simple assignment operator to assign values to variable. Let a = 5 and b = 10 assigns the value 5
to a and 10 to b these two assignment statement can also be given as a,b=5,10 that assigns the value 5 and 10
on the right to the variables a and b respectively. There are various compound operators in Python like +=, -=,
*=, /=, %=, **= and //= are also available.
Eg:
x+=20
x-=5
x*=5
x/=2
x%=3
x**=2
x//=3
Output:
X = 10
The x is = 10
The x += 20 is = 30
The x -= 5 is = 25
The x *= 5 is = 125
The x /= 2 is = 62.5
The x %= 3 is = 2.5
Ternary operator is also known as conditional operator that evaluate something based on a condition being true
or false. It simply allows testing a condition in a single line replacing the multiline if-else making the code
compact.
Syntax:
Eg:
Delimiters:
Python uses the symbols and symbol combinations as delimiters in expressions, lists, dictionaries and strings.
Following are the delimiters.
( ) { }
, : . =
Literals:
1) Numeric
2) String
3) Boolean
Numeric Literals:
Numeric Literals consists of digits and are immutable (unchangeable). Numeric literals can belong to 3 different
numerical types Integer, Float and Complex.
String Literals:
In Python a string literal is a sequence of characters surrounded by quotes. Python supports single, double and
triple quotes for a string. A character literal is a single character surrounded by single or double quotes. The
value with triple-quote "' '" is used to give multiline string literal. A Character literal is also considered as string
literal in Python.
Boolean Literals:
A Boolean literal can have any of the two values: True or False.
Escape Sequences:
In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in
representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.
For example to print the message "It's raining", the Python command is
3.Explain the concept of iteration in Python. Discuss how iteration is achieved using loops and
iterable objects. Provideexamples to illustrate your explanation.
Ans:
Iteration in Python refers to the process of repeatedly executing a block of code until a certain condition
is met or a sequence is exhausted. It allows the execution of code to be repeated multiple times,
facilitating tasks such as traversal of data structures, performingcalculations, or executing a set of
instructions iteratively.
In Python, iteration is commonly achieved using loops and iterable objects. Let's discusseach of these
concepts in detail:
Loops: Python provides two main types of loops: for loops and while loops.
o For Loops: for loops are used to iterate over a sequence (such as a list, tuple, string, orrange) or an
iterable object.
o Example:
fruits = ["apple", "banana", "cherry"]for fruit in fruits:
print(fruit)
In this example, the for loop iterates over the list fruits, assigning each element to thevariable
fruit, and then printing each fruit.
While Loops: while loops execute a block of code repeatedly as long as a specified,
Example:
i=0
while i < 5:
print(i)
i += 1
This while loop prints numbers from 0 to 4, incrementing the value of iin each iterationuntil ibecomes 5.
Iterable Objects:
Iterable objects are objects capable of returning their elements one at a time. Common examples of
iterable objects in Python include lists, tuples, strings, dictionaries, and sets.
Iterating over Lists: Lists are one of the most commonly used iterable objects in Python.
numbers = [1, 2, 3, 4, 5]
print(num)
This for loop iterates over the list numbers, printing each element.
Iterating over Strings: Strings are also iterable in Python, allowing iteration over eachcharacter in
the string.
word = "hello" for char in
word:
print(char)
o Here, the for loop iterates over the string word, printing each character individually.
Examples:
Let's combine the concepts of loops and iterable objects to iterate over a list of tuples andcalculate the
total sum of the second elements of each tuple:
Program:
# List of tuples
pair in data:
total_sum += pair[1] # Add the second element of each tuple to the total sum
In this example, we use a for loop to iterate over the list of tuples data, and for each tuple,we access the
second element (pair[1]) and add it to the total_sum. Finally, we print the total sum of the second
elements.
This illustrates how iteration in Python can be achieved using loops (for loop in this case)and iterable
objects (the list of tuples data). It demonstrates the versatility of iteration forprocessing data structures
and performing repetitive tasks efficiently.
A for loop is used to iterate over sequences like a list, tuple, set, etc or. And not onlyjust the
sequences but any iterable object can also be traversed using a for loop
FLOWCHART:
The execution will start and look for the first item in the sequence or iterable object.It will check
whether it has reached the end of the sequence or not. After executingthe statements in the block,
it will look for the next item in the sequence and the process will continue until the execution has
reached the last item in the sequence.
1 x = (1,2,3,4,5)
2 for i in x:
3 print(i)
Output: 1
In the above example, the execution started from the first item in the tuple x, and it went on until the
execution reached 5. It is a very simple example of how we can use a for loop in python. Let us also take a
look at how range function can be used with for loop.
In python, range is a Built-in function that returns a sequence. A range function has three parameters
which are starting parameter, ending parameter and a step parameter. Ending parameter does
not include the number declared, let us understand this with an example.
1 a = list(range(0,10,2))
2 print(a)
Output: [0,2,4,6,8]
In the above example, the sequence starts from 0 and ends at 9 because the ending parameter is 10
and the step is 2, therefore the while execution it jumps 2 steps after each item.
Let us take a look at how we can use a break statement in a python for loop.
Break in python is a control flow statement that is used to exit the execution as soon as the break is
encountered. Let us understand how we can use a break statement ina for loop using an example.
Let’s say we have a list with strings as items, so we will exit the loop using the break statement as soon
as the desired string is encountered.
1 company = ['E','D','U','R','E','K','A']
2
3 for x in company:
4 if x == "R":
5 break
6 print(x)
Output: E
In the above example, as soon as the loop encounters the string “R” it enters the if statement block
where the break statement exits the loop. Similarly, we can use the break statement according to the
problem statements.
Python For Loop In List
A list in python is a sequence like any other data type, so it is quite evident on how we can make use
of a list. Let me show you an example where a for loop is used in alist.
Let us also take a look how we can use continue statement in a for loop in python.
In the above example, the continue statement was encountered when the string value was “R”,
so the execution skipped that particular iteration and moved to thenext item in the list.
Let us now look at a few other examples for a better understanding of how we canuse for loop in
Python.
Python For Loop Examples
Here is a simple for loop program to print the product of any five numbers takenfrom the user
1 res = 1
2
3 for i in range(0,5):
4 n = int(input("enter a number"))res *= n
5 print(res)
6
Output:
Here is another simple program to calculate area of squares whose sides are givenin a list.
1 side = [5,4,7,8,9,3,8,2,6,4]
2 area = [x*x for x in side]
3
4 print(area)
Output:
5.Python program to display all numbers within a range except the primenumbers.
Program:
def is_prime(num):if
num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
if not is_prime(num):
display_non_primes(start_range, end_range)
is_prime(num): This function takes a number as input and returns True if the number isprime, and False
otherwise.
display_non_primes(start, end): This function takes the start and end of the range asinput and
displays all the non-prime numbers within that range.
In the display_non_primes function, it iterates through each number in the specified range. If a number
is not prime (determined using the is_prime function), it prints the
Output:
1 4 6 8 9 10 12 14 15 16 18 20
In this output:
• The numbers 1, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, and 20 are displayed.
• These numbers are all within the range from 1 to 20, and they are not primenumbers.
Scope of variable refers to the part of the program, where it is accessible, i.e., area where
you can refer (use) it. We can say that scope holds the current set of variables and their values.
Two types of scopes - local scope and global scope.
LOCAL SCOPE:
A variable declared inside the function's body is known as local variable.
RULES OF LOCAL VARIABLE:
• A variable with local scope can be accessed only within the function that it is created in.
• When a variable is created inside the function the variable becomes local to it.
• A local variable only exists while the function is executing.
• The formal parameters are also local to function.
EXAMPLE:
def loc():
y=0 # local scope
print(y)
loc()
Output:
0
GLOBAL SCOPE:
A variable, with global scope can be used anywhere in the program. It can be created by
defining a variable outside the scope of any function/block.
EAXMPLE:
c = 1 # global variable
def add():
print(c)
add()
Output:
1
Output:
16
local
Arguments are used to call a function and there are primarily 4 types of functions that
one can use:
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments.
REQUIRED ARGUMENTS:
“Required Arguments” are the arguments passed to a function in correct positional
order. Here, the number of arguments in the function call should match exactly with the
function definition. You need atleast one parameter to prevent syntax errors to get the required output.
EXAMPLE:
def printstring(str):
print ("Example - Required arguments ")
print (str)
return
# Now you can call printstring() function
printstring()
Output:
Example - Required arguments
Welcome
KEYWORD ARGUMENTS:
Keyword arguments will invoke the function after the parameters are recognized by
their parameter names. The value of the keyword argument is matched with the parameter
name and so, one can also put arguments in improper order (not in order).
EXAMPLE:
def printdata (name):
print (“Example-1 Keyword arguments”)
print (“Name :”,name)
return
# Now you can call printdata() function
printdata(name = “Gshan”)
Output:
Example-1 Keyword arguments
Name :Gshan
DEFAULT ARGUMENT:
In Python the default argument is an argument that takes a default value if no value
is provided in the function call.
EXAMPLE:
def printinfo( name, salary = 3500):
print (“Name: “, name)
print (“Salary: “, salary)
return
printinfo(“Mani”)
Output:
Name: Mani
Salary: 3500
EXAMPLE:
def sum(x,y,z):
print("sum of three nos :",x+y+z)
sum(5,10,15)
Output:
Sum of three nos: 30
A recursive definition is similar to a circular definition, i.e., “function call itself” this is known as
recursion. The condition that is applied in any recursive function is known as base condition. A base
condition is must in every recursive function otherwise it will continue to execute like an infinite loop.
Syntax:
def function_name(a):
------------
------------
function_name(b)
------------
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input(“Enter N:”))
f=factorial(n)
print(“The factorial of “,n,” is “,f)
Output:
Enter N:5
The factorial of 5 is 120
Explanation
Here is what the stack diagram looks like for this sequence of function calls:
In Python, lists are a versatile data structure that allows for various operations, making them essential for many
programming tasks. Here are the different list operations in Python:
Creating Lists:
Lists are created by enclosing elements within square brackets [ ] and separating them with commas. For
example:
my_list = [1, 2, 3, 4, 5]
Accessing Elements:
Elements in a list can be accessed using index notation. Indexing starts at 0 for the first element and -1 for the
last element. For example:
first_element = my_list[0]
last_element = my_list[-1]
Slicing Lists:
Syntax: list[start:stop:step].
Example:
Modifying Lists:
Lists are mutable, allowing modifications to their elements. You can modify, append, insert, remove, or clear
elements. Example:
Combining Lists:
Lists can be combined using the concatenation operator + or the extend() method. Example:
list1.extend(list2)
Copying Lists:
Lists can be copied using slicing or the copy() method to create a new list with the same elements. Example:
Python provides methods like index() to find the index of a specific element and count() to count occurrences.
Example:
Lists can be sorted using sort() or sorted() and reversed using reverse(). Example:
Lists can be iterated using loops. Membership testing checks if an element exists in a list.
Example:
print(item)
if 3 in my_list:
List Comprehensions:
List comprehensions provide a concise way to create lists based on existing lists.
Example: