0% found this document useful (0 votes)
6 views

Python Unit- 1

The document provides a comprehensive overview of Python programming, covering fundamental concepts such as data types, functions, loops, and variable scopes. It details the evolution of Python, the features of its data structures like lists, tuples, and dictionaries, and explains the significance of functions, including user-defined and built-in functions. Additionally, it discusses the use of control statements, such as for and while loops, and the importance of recursion and parameters in function definitions.

Uploaded by

amalamargret.cse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Python Unit- 1

The document provides a comprehensive overview of Python programming, covering fundamental concepts such as data types, functions, loops, and variable scopes. It details the evolution of Python, the features of its data structures like lists, tuples, and dictionaries, and explains the significance of functions, including user-defined and built-in functions. Additionally, it discusses the use of control statements, such as for and while loops, and the importance of recursion and parameters in function definitions.

Uploaded by

amalamargret.cse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

PART-A

Two mark Questions

1.What is Python? What are the benefits of using Python?


Python is a programming language with objects, modules, threads, exceptions and automatic memory
management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure
and it is an open source.
2.Give the evolution of python.
It is created by GUIDO VAN ROSSUM in the year 1980. The first version of python was released in the
year 1991.
• Python 1.0 was released in the year 1994 • Python 1.5 was released in the year 1997 • Python 2.0 was
released in the year 2000
• Python 3.0 was released in the year 2008
3. What is python interpreter?
The engine that translates and runs Python is called the Python Interpreter: There are two ways to use it:
immediate mode and script mode. The >>> is called the Python prompt. The interpreter uses the prompt to
indicate that it is ready for
instructions.
4. What is the difference between intermediate mode and script mode?

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

7. What are python strings?


Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python
allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ]
and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the

repetition operator. str = 'Hello World!'


print str[0] #
Prints first character of the string o/p: H

8. Mention the features of lists in python


Lists are the most versatile of Python's compound data types. A list contains items separated by commas and
enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between
them is that all the items
belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the
beginning of the list and working their way to end -1.
The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

9. What is tuple ? What is the difference between list and tuple?


• A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values
separated by commas.
• The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
Tuples can be thought of as read-only lists. Eg:

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )

10. Give the features of python dictionaries


Python's dictionaries are kind of hash table type. They work like associative arrays and consist of key-value
pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other
hand, can be any arbitrary Python object.Dictionaries are enclosed by curly braces ({ }) and values can be
assigned and accessed using square braces ([]). For example − dict = {}

dict['one'] = "This is one"

11. What is a variable?


One of the most powerful features of a programming language is the ability to manipulate variables. A variable
is a name that refers to a value.
The assignment statement gives a value to a variable.
Eg:
>>> n = 17
>>> pi = 3.14159

12. What are the rules for naming a variable?


Variable names can be arbitrarily long. They can contain both letters and digits, but they have to begin
with a letter or an underscore. Although it is legal to use uppercase letters, by convention we don‘t. If you do,
remember that case matters. Bruce and bruce are different variables.
The underscore character ( _) can appear in a name.
Eg:
my_name
13. What are keywords?
Keywords are the reserved words in Python. We cannot use a keyword as variable name, function name or any
other identifier. They are used to define the syntax and structure of the Python language In Python, keywords
are case sensitive.
There are 33 keywords in Python.
Eg:
False, class, finally, return

14.What are the rules for writing an identifier?


• Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or
an underscore (_). Names like myClass, var_1 and print_this_to_screen, all are valid example.
• An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
Keywords cannot be used as identifiers.
• We cannot use special symbols like !, @, #, $, % etc. in our identifier. Identifier can be of
any length.

15.what are expressions?


An expression is a combination of values, variables, operators, and calls to functions. If you type an expression
at the Python prompt, the interpreter evaluates it
and displays the result:
>>> 1 + 1=2

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.

17.What is multiline statement?


In Python, end of a statement is marked by a newline character. But we can make a statement extend over
multiple lines with the line continuation character

18. What is docstring?


Doc string is short for documentation string. It is a string that occurs as the first statement in a module,
function, class, or method definition. It is used to explain in brief, what a function does.

19. What is a function? Mention the type of function and use.


A Function can be called as a section of a program that is written once and can be executed whenever required
in the program, thus making code reusability.
There are two types of Functions.
a) Built-in Functions: Functions that are predefined. We have used many predefined functions in
Python.
b) User- Defined: Functions that are created according to the requirements.

20. Mention the types of arguments in python


- Python default arguments
-Python keyword argument
-Python arbitrary argument
21. What is meant by module in python?
A module is a file consisting of Python code. A module can define functions, classes and variables. A module can
also include runnable code.
22. List some built in modules in python
There are many built in modules in Python. Some of them are as follows:math, random , threading , collections ,
os , mailbox , string , time , tkinter etc..
23.What is module and package in Python?
In Python, module is the way to structure program. Each Python program file is a module, which imports other
modules like objects and attributes.

24.Explain how can you access a module written in Python from C?

We can access a module written in Python from C by following method,Module =


=PyImport_ImportModule(―<modulename>‖);

25.Mention five benefits of using Python?


• Python comprises of a huge standard library for most Internet platforms like Email, HTML.

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

27.State the reason to divide programs into functions.


Creating a new function gives an opportunity to name a group of statements, which makes program easier to
read and debug.
Functions can be making a program smaller by eliminating repetitive code.
Dividing a long program into functions allows debugging the parts one at a time and then assembling them into
a working whole.
Well-designed functions are often useful for many programs.

28. Define Parameters.


Inside the function, the arguments are assigned to variables called parameters.
Example:
def print_twice(Flower):
print(Flower) print(Flower)
29. Give the features of python.
Easy to Use:
Expressive Language
Interpreted Language
Cross-platform language
Free and Open Source
Object-Oriented language
Extensible

30.Define the purpose of a for loop in Python.

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.

40. WHAT IS FUNCTION IN PYTHON?

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.

41.WHAT ARE THE TYPES OF FUNCTIONS AVAILABLE IN PYTHON?

User – defined functions.

Built – in functions.

Lambda functions.

Recursive functions.

42. WHAT IS THE USE OF LAMBDA 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.

43.HOW WILL YOU DEFINE A FUNCTION IN PYTHON?

Functions must be defined, to create and use certain functionality.

Function blocks begin with the keyword “def” followed by function name and parenthesis ().

The code block always comes after a colon (:) and is indented.

The statement “return [expression]” exits a function.

SYNTAX: def <function_name ([parameter1, parameter2...] )> :


<Block of Statements>
return <expression / None>

44.DEFINE RECURSIVE FUNCTION IN PYTHON.

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

45.GIVE SOME EXAMPLES FOR BUILT IN FUNCTIONS.

abs ( ), ord ( ), bin ( ), min ( ), max( ), sum( ), round( ), pow( ), sqrt( ), floor( ).

46.WHAT ARE THE MAIN ADVANTAGES OF FUNCTION?

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

you need to do is to call the function.

3. Functions, allows us to change functionality easily, and different programmers can work on different
functions.

47.GIVE THE SYNTAX FOR LAMBDA FUCTION.

SYNTAX: lambda [argument(s)] :expression

48.WHAT ARE THE TYPES OF SCOPES OF VARIBALE?

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

defining a variable outside the scope of any function/block.

50.DEFINE LOCAL SCOPE.

A variable declared inside the function's body is known as local variable.

51.GIVE THE SYNTAX FOR USER DEFINED FUNCTION.

SYNTAX: def <function_name ([parameter1, parameter2...] )> :


<Block of Statements>
return <expression / None>

52.DEFINE FUNCTION CALL AND GIVE EXAMPLE.

When you call the “hello()” function, the program displays the following string as

output:

def hello():

print (“hello - Python”)

return

print (hello())

Output:
hello – Python
None

53. WHAT IS COMPOSITION IN FUNCTIONS?

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.

54.WHAT IS THE BASE CONDITION IN RECURSIVE FUNCTION?

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.

55. DEFINE PARAMETERS AND ITS TYPES.

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

56.WHAT IS THE USE OF RETURN STATEMENT IN FUNCTION?

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 ]

57.WHAT ARE THE VARIOUS TYPES OF FUNCTION ARGUMENTS?

Required arguments

Keyword arguments

Default arguments

Variable-length arguments.
58.DEFINE ANONYMUOS FUNCTIONS.

In Python, anonymous function is a function that is defined without a name. While

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.

SYNTAX: lambda [argument(s)] :expression

59.WHAT IS MEANT BY FRUITFUL 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.

60. Define list.

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.

61. How to create list in python?

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:

Variable = [element-1, element-2, element-3 …… element-n]

62. What is nested list. Give example

Nested list is a list containing another list as an element.

Eg: Mylist = [ “Welcome”, 3.14, 10, [2, 4, 6] ]

63. How to access elements in a list?

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]

Marks 10 23 41 75
Index (positive integer) 0 1 2 3
Index(negative integer) -4 -3 -2 -1

64. Marks = [10, 23, 41, 75]

i=0
while i < 4:

print (Marks[i])

i=i+1

What is the above snippet? Output: 10 23 41 75

65. What is reverse indexing?

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.

66. What is the use of len() function in python?

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.

67. MySubject = [“Tamil”, “English”, “Comp. Science”, “Maths”]

len(MySubject)

What is the output of the above snippet?

Output: 4

68. MySubject = ["Tamil", "English", "Comp. Science", "Maths"]

i=0

while i < len(MySubject):

print (MySubject[i])

i=i+1

What is the output of the above snippet?

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:

for index_var in list:

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:

List_Variable [index of an element] = Value to be changed

List_Variable [index from : index to] = Values to changed

71. How to add elements in a list? Give example.

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:

List.append (element to be added)

List.extend ( [elements to be added])

72. What is the use of extend() function in list?

In extend( ) function, multiple elements should be specified within square bracket as arguments of the function.

Eg:

Mylist=[34, 45, 48]

Mylist.extend([71, 32, 29])

print(Mylist)

Output:

[34, 45, 48, 90, 71, 32, 29]

73. Give the difference between append() and extend()?

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.

74. How to insert element in a list? Give syntax and example.

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.

Syntax: List.insert (position index, element)

Eg:

MyList=[34,98,47,'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan' ]

MyList.insert(3, 'Ramakrishnan')
print(MyList)

Output:

[34, 98, 47, 'Ramakrishnan', 'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan']

75. What is the use of del() function? Give example.

del statement is used to delete elements whose index is known. The del statement can also be used to delete
entire list.

Eg:

MySubjects = ['Tamil', 'Hindi', 'Telugu', 'Maths']

del MySubjects[1]

print (MySubjects)

Output: ['Tamil', 'Telugu', 'Maths']

76. Give the difference between pop() and remove() function?

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.

77. What is the use of clear() function? Give example.

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)

What is the output of the above snippet?

Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

79. s=[ ]

for i in range(21):
if (i%4==0):

s.append(i)

print(s)

What is the output of the above snippet?

Output: [0, 4, 8, 12, 16, 20]

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

4.Briefly explain about the concept of Naming Convention in python.


Python Naming Conventions
1. General
• Avoid using names that are too general or too wordy. Strike a good balance between the two.
• Bad: data_structure, my_list, info_map,
dictionary_for_the_purpose_of_storing_data_representing_word_definitions
• Good: user_profile, menu_options, word_definitions
• Don’t be a jackass and name things “O”, “l”, or “I”
• When using CamelCase names, capitalize all letters of an abbreviation (e.g. HTTPServer)
2. Packages
• Package names should be all lower case
• When multiple words are needed, an underscore should separate them
• It is usually preferable to stick to 1 word names
3. Modules
• Module names should be all lower case
• When multiple words are needed, an underscore should separate them
• It is usually preferable to stick to 1 word names
4. Classes
• Class names should follow the UpperCaseCamelCase convention
• Python’s built-in classes, however are typically lowercase words
• Exception classes should end in “Error”
5. Global (module-level) Variables
• Global variables should be all lowercase
• Words in a global variable name should be separated by an underscore
6. Instance Variables
• Instance variable names should be all lower case
• Words in an instance variable name should be separated by an underscore
• Non-public instance variables should begin with a single underscore
• If an instance name needs to be mangled, two underscores may begin its name
7. Methods
• Method names should be all lower case
• Words in an method name should be separated by an underscore
• Non-public method should begin with a single underscore
• If a method name needs to be mangled, two underscores may begin its name
8. Method Arguments
• Instance methods should have their first argument named ‘self’.
• Class methods should have their first argument named ‘cls’
9. Functions
• Function names should be all lower case
• Words in a function name should be separated by an underscore
10. Constants
• Constant names must be fully capitalized
• Words in a constant name should be separated by an underscore

5. Illustrative comments in Python in briefly.


Comments in Python are also quite different than other languages, but it is pretty easy to get used to.
In Python there are basically two ways to comment:
single line and multiple line.

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

6. Explain looping types in python with example.

In Python, there are mainly two types of loops:


for loops and while loops. Each type serves a different purpose and has its own syntax and use cases.
For Loop:
The for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range) or an iterable
object.
Syntax:
for in
Explanation:
The loop iterates over each item in the sequence one by one.
For each iteration, the variable item takes on the value of the current item in the sequence.
The code block inside the loop is executed for each item in the sequence.
Example:
fruits = ["apple", "banana", "cherry"] for fruit in fruits:
print(fruit)

Output: Apple Banana Cherry

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

Loop Control Statements:


Python provides several loop control statements to alter the flow of loop execution:
break: Terminates the loop prematurely when a certain condition is met.
continue: Skips the remaining code in the current iteration and moves to the next iteration of the loop.
pass: Does nothing and acts as a placeholder when no action is required.

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:

print("Number found!") break


else:
print("Number not found!")

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

•start (optional): The starting value of the sequence (default is 0).


•stop (required): The end value of the sequence (exclusive).
•step (optional): The step size between consecutive numbers in the sequence (default is 1).

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

for i in range(5): print(i)

Output:
0
1
2
3
4
Using range() with two arguments (start, stop):

for i in range(2, 6): print(i)


Output:
2
3
4
5
Using range() with three arguments (start, stop, step): for i in range(1, 10, 2):
print(i) Output:
1
3
5
7
9
•Additional Notes:
The range() function is inclusive of the start value but exclusive of the stop value.
If start is not specified, the default value is 0.
The step argument determines the spacing between consecutive numbers in the sequence. If not specified, the
default value is 1.
•Conclusion:
The range() function is a fundamental tool in Python for creating sequences of numbers, particularly for use in
loops.
It simplifies the process of generating numerical sequences, making it easier to control the number of
iterations in loops and iterate over specific ranges of values.

9.What are loop control statements in Python? Explain with examples.


•Loop control statements in Python are special statements used to alter the flow of execution within loops.
They provide mechanisms for breaking out of a loop prematurely, skipping certain iterations, or executing
specific actions based on certain conditions. The three main loop control statements in Python are break,
continue, and pass.
• Break Statement:
o The break statement is used to terminate the loop prematurely when a specified condition is met. It
immediately exits the loop and continues with the next statement following the loop.
o Example:
numbers = [1, 2, 3, 4, 5] for num in numbers:
if num == 4: break
print(num) Output:
1
2

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

print("\nNumbers from 1 to 10 skipping multiples of 3:") for i in range(1, 11):


if i % 3 == 0:
continue # Skip this iteration if i is a multiple of 3 print(i)
if name == " main ": main()

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

11.EXPLAIN FUNCTIONS AND ITS TYPES.

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.

USER- DEINED FUNCTIONS:

Functions must be defined, to create and use certain functionality.

Function blocks begin with the keyword “def” followed by function name and parenthesis ().

The code block always comes after a colon (:) and is indented.

The statement “return [expression]” exits a function.


SYNTAX: def <function_name ([parameter1, parameter2...] )> :
<Block of Statements>
return <expression / None>

BUILT- IN FUNCTIONS:

1. abs ( ) – Returns an absolute value of a number.


2. ord ( ) – Returns the ASCII value for the given Unicode character.
3. bin ( ) – Returns a binary string prefixed with “0b” for the given integer number.
4. min ( ) – Returns the minimum value in a list.
5. max ( ) – Returns the maximum value in a list.
6. sqrt ( ) – Returns the square root of x

LAMBDA FUNCTIONS:

In Python, anonymous function is a function that is defined without a name. While


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.
SYNTAX: lambda [argument(s)] :expression
• 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.
RECURSIVE FUNCTION:
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)
------------

12.WRITE A PYTHON CODE TO FIND GIVEN NUMBER IS PRIME OR NOT USING FUNCTIONS.

def is_prime(number):

if number <= 1:

return False

for i in range(2, int(number**0.5) + 1):

if number % i == 0:

return False

return True
# Test the function

num = 17

if is_prime(num):

print(f"{num} is a prime number.")

else:

print(f"{num} is not a prime number.")

OUTPUT:

17 is a prime number.

13.EXPLAIN FRUITFUL FUNCTIONS WITH EXAMPLE.V

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)

print(“Addition of two number is “,z)

Output:

Enter number1:12
Enter number2:25

Addition of two number is 37

PARAMETERS IN FRUITFUL FUNCTION

Parameter is the “input data that is sent from function call to function definition”.

Types:

(i) Actual parameters : This parameter defined in the function call.

(ii) Formal parameters : This parameter defined as the part of function definition.

14.EXPLAIN BUILT IN FUNCTIONS WITH EXAMPLES AND ITS USES.


15.WRITE A PYTHON PROGRAM TO REVERSE A GIVEN NUMBER USING RECURSION.

num = int(input("Enter the number: "))


revr_num = 0 # initial value is 0. It will hold the reversed number
def recur_reverse(num):
global revr_num # We can use it out of the function
if (num > 0):
Reminder = num % 10
revr_num = (revr_num * 10) + Reminder
recur_reverse(num // 10)
return revr_num
revr_num = recur_reverse(num)
print("n Reverse of entered number is = %d" % revr_num)

Output:

Enter the number: 5426


The Reverse of entered number is = 6245

16. What the different ways to insert an element in a list. Explain with suitable example.

The different ways to insert an element in a list are

Using append() function


Using extend() function
Using insert() function
append() function:
append() function is used to add a single element.
Syntax:
List.append (element to be added)

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

a) copy() b) count() c) index() d) reverse() e) max()


Function Description Syntax Example
copy() Returns a copy of the List.copy( ) MyList=[12, 12, 36]
list x = MyList.copy()
print(x)
Output: [12, 12, 36]
count() Returns the number List.count(value) MyList=[36 ,12 ,12]
of similar elements x = MyList.count(12)
present in the last. print(x)
Output: 2
index( ) Returns the index List.index(element) MyList=[36 ,12 ,12]
value of the first x = MyList.index(12)
recurring element. print(x)
Output: 1
reverse() Reverses the order of List.reverse( ) MyList=[36 ,23 ,12]
the element in the MyList.reverse()
list. print(MyList)
Output: [12 ,23 ,36]
max() Returns the max(list) MyList=[21,76,98,23]
maximum value in a print(max(MyList))
list. Output: 98

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:

Syntax of for loop:

In Python, the syntax of a for loop is straightforward:

for element in my_list:

Here, element is a variable that will take on each value in the my_list sequentially.

Example:

Let's consider a list of integers named numbers:

numbers = [1, 2, 3, 4, 5]

We can iterate over the elements of numbers using a for loop:

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 = []

for num in numbers:


squared_numbers.append(num ** 2)

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:

for index, value in enumerate(numbers):

print(f"Element at index {index} is {value}")

The code will output the index and value of each element in the ‘number’ list.

19. Explain the concept of list slicing in Python with an example.

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]

# Extract elements from index 2 to index 5 (exclusive)

sliced_list = original_list[2:5]

# Output: [2, 3, 4]

# Extract elements from index 0 to index 7 (exclusive) with a step size of 2

sliced_list = original_list[0:7:2]

# Output: [0, 2, 4, 6]

Using Negative Indices:

# Slice from the end of the list


sliced_list = original_list[-3:]

# Output: [7, 8, 9]

# Slice from the beginning to index -4 (exclusive)

sliced_list = original_list[:-4]

# Output: [0, 1, 2, 3, 4, 5]

Omitting Indices:

# Slice from the beginning to index 6 (exclusive)

sliced_list = original_list[:6]

# Output: [0, 1, 2, 3, 4, 5]

# Slice from index 3 to the end of the list

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]

20. What is the difference between a list and a tuple in Python?

Feature List Tuple


Mutable: elements can be changed, added, or Immutable: elements cannot be changed after
Mutability removed after creation. creation.
Syntax Defined using square brackets [ ]. Defined using parentheses ( ).
Typically used for collections of items where
order and presence of duplicates matter.
Suitable for situations where elements need Used for collections of items that should not be
Use Cases to be modified frequently. changed. Suitable for fixed data or sequences.
Generally consumes more memory and is
slower due to dynamic nature and resizing More memory-efficient and faster due to
Performance operations. immutability, especially for smaller collections.

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

print ("The Sum = ",a+b)

print ("The Difference = ",a-b)

print ("The Product = ",a*b)

print ("The Quotient = ",a/b)

print ("The Remainder = ",a%30)

print ("The Exponent = ",a**2)

print ("The Floor Division =",a//30)

Output:

The Sum = 110

The Difference = 90

The Product = 1000

The Quotient = 10.0

The Remainder = 10

The Exponent = 10000

The Floor Division = 3

Relational or Comparative operators:

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:

a=int (input("Enter a Value for A:"))

b=int (input("Enter a Value for B:"))

print ("A = ",a," and B = ",b)

print ("The a==b = ",a==b)


print ("The a > b = ",a>b)

print ("The a < b = ",a=b)

print ("The a <= b = ",a<=b)

print ("The a != b = ",a!=b)

Output:

Enter a Value for A:35

Enter a Value for B:56

A = 35 and B = 56

The a==b = False

The a > b = False

The a < b = True

The a >= b = False

The a <= b = False

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:

a=int (input("Enter a Value for A:"))

b=int (input("Enter a Value for B:"))

print ("A = ",a, " and b = ",b)

print ("The a > b or a == b = ",a>b or a==b)

print ("The a > b and a == b = ",a>b and a==b)

print ("The not a > b = ",not a>b)

Output:

Enter a Value for A:50

Enter a Value for B:40

A = 50 and b = 40

The a > b or a == b = True

The a > b and a == b = False

The not a > b = False

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=int (input("Type a Value for X : "))

print ("X = ",x)

print ("The x is =",x)

x+=20

print ("The x += 20 is =",x)

x-=5

print ("The x -= 5 is = ",x)

x*=5

print ("The x *= 5 is = ",x)

x/=2

print ("The x /= 2 is = ",x)

x%=3

print ("The x %= 3 is = ",x)

x**=2

print ("The x **= 2 is = ",x)

x//=3

print ("The x //= 3 is = ",x)

Output:

Type a Value for X : 10

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

The x **= 2 is = 6.25

The x //= 3 is = 2.0


Conditional operator:

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:

Variable Name = [on_true] if [Test expression] else [on_false]

Eg:

min= 49 if 49<50 else 49 # min = 49

min= 50 if 49>50 else 49 # min = 49

Delimiters:

Python uses the symbols and symbol combinations as delimiters in expressions, lists, dictionaries and strings.
Following are the delimiters.

( ) { }
, : . =
Literals:

Literal is a raw data given to a variable or constant.

In Python, there are various types of 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

>>> print ("It\'s rainning")


It's rainning

3.Explain the concept of iteration in Python. Discuss how iteration is achieved using loops and
iterable objects. Provideexamples to illustrate your explanation.

Ans:

Concept of Iteration in Python:

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.

Achieving Iteration using Loops and Iterable Objects:

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]

for num in numbers:

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

data = [(1, 2), (3, 4), (5, 6)]


# Initialize total sum
total_sum = 0

# Iterate over the list of tuplesfor

pair in data:

total_sum += pair[1] # Add the second element of each tuple to the total sum

# Print the total sum

print("Total sum of second elements:", 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.

4.Python For loops with example.Ans:

What is Python For Loop?

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.

Python For Loop Syntax


Let us understand the for loop syntax with an example:

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.

Range in Python 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.

Now let us take a look at an example using python for loop.


1 def pattern(n):
2 k=2*n-2
3 for i in range(0,n):
4 for j in range(0,k):
5 print(end=" ")
6 k=k-1
7 for j in range(0, i+1): print("*",
8 end=" ")
9 print("r")
10
11 pattern(15)
Output
In the above example, we were able to make a python pyramid pattern program usinga range function. We
used the range function to get the exact number of white spacesand asterisk values so that we will get the
above pattern.

Let us take a look at how we can use a break statement in a python for loop.

Python For Loop Break

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.

1 color = ["blue", "white"]


2 vehicle = ['car', 'bike', 'truck']
3
4 color_comb = [(x,y) for x in color for y in vehicle]print(color_comb)
5
6
Output: [('blue', 'car'), ('blue', 'bike'), ('blue', 'truck'), ('white', 'car'),('white', 'bike'), ('white', 'truck')]

Let us also take a look how we can use continue statement in a for loop in python.

Continue In Python For Loop


Let us understand this the same example we used in the break statement, instead of break, we will use
the continue statement. It is also a control statement but the only difference is that it will only skip
the current iteration and execute the rest of the iterations anyway.

1 company = ['E', 'D', 'U', 'R', 'E', 'K', 'A']


2
3 for x in company:
4 if x == "R":
5 continue
6 print(x)
Output: E

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:

[25, 16, 49, 64, 81, 9, 64, 4, 36, 16]

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

def display_non_primes(start, end):

print("Non-prime numbers within the range [{}, {}]:".format(start, end))for num in

range(start, end + 1):

if not is_prime(num):

print(num, end=" ")

start_range = int(input("Enter the start of the range: "))end_range =

int(input("Enter the end of the range: "))

display_non_primes(start_range, end_range)

This program defines two functions:

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:

Enter the start of the range: 1Enter the

end of the range: 20

Non-prime numbers within the range [1, 20]:

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.

6.EXPLAIN THE SCOPES OF VARIBALE IN A FUNCTION WITH EXAMPLE.

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.

RULES FOR GLOBAL KEYWORD:


• When we define a variable outside a function, it’s global by default. You don’t have to use
global keyword.
• We use global keyword to read and write a global variable inside a function.
• Use of global keyword outside a function has no effect

EAXMPLE:

c = 1 # global variable
def add():
print(c)
add()

Output:
1

GLOBAL AND LOCAL VAEIABLE IN THE SAME CODE:

x=8 # x is a global variable


def loc():
global x
y = "local"
x=x*2
print(x)
print(y)
loc()

Output:
16
local

7.EXPLAIN FUNTION ARGUMENTS BRIEFLY.

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

VARIABLE – LENGTH ARGUMENTS:


Variable-Length arguments can be used instead. These are not specified in the function’s definition and
an asterisk (*) is used to define such arguments.

EXAMPLE:
def sum(x,y,z):
print("sum of three nos :",x+y+z)
sum(5,10,15)
Output:
Sum of three nos: 30

8.EXPLAIN HOW RECURSIVE FUNCTION WORKS.

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

OVERVIEW OF HOW RECURSIVE FUNCTION WORKS


1. Recursive function is called by some external code.
2. If the base condition is met then the program gives meaningful output and exits.
3. Otherwise, function does some required processing and then calls itself to continue
recursion.

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:

9. Explain the different list operations in python.

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:

Slicing allows extracting a subset of elements from the original list.

Syntax: list[start:stop:step].
Example:

sublist = my_list[1:4] # Extracts elements at index 1, 2, 3

Modifying Lists:

Lists are mutable, allowing modifications to their elements. You can modify, append, insert, remove, or clear
elements. Example:

my_list[0] = 10 # Modify element at index 0

my_list.append(6) # Append 6 to the end

del my_list[2] # Remove element at index 2

Combining Lists:

Lists can be combined using the concatenation operator + or the extend() method. Example:

combined_list = list1 + list2

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:

new_list = my_list[:] # Slicing

copied_list = my_list.copy() # Using copy()

Searching and Counting:

Python provides methods like index() to find the index of a specific element and count() to count occurrences.
Example:

index = my_list.index(3) # Returns the index of first occurrence of 3

count = my_list.count(3) # Returns the number of occurrences of 3

Sorting and Reversing:

Lists can be sorted using sort() or sorted() and reversed using reverse(). Example:

my_list.sort() # Sorts the list in place

sorted_list = sorted(my_list) # Returns a new sorted list

my_list.reverse() # Reverses elements in place

Iteration and Membership Testing:

Lists can be iterated using loops. Membership testing checks if an element exists in a list.

Example:

for item in my_list:

print(item)
if 3 in my_list:

print("3 is in the list")

List Comprehensions:

List comprehensions provide a concise way to create lists based on existing lists.

Example:

squares = [x**2 for x in range(10)]

You might also like