0% found this document useful (0 votes)
22 views34 pages

Python Unit-wise 1 Mark Questions

The document contains a series of unit-wise questions and answers focused on Python programming, covering topics such as features of Python, data types, operators, control flow statements, and built-in functions. It provides definitions, examples, and explanations for various concepts, including mutable and immutable data types, the use of the import statement, and the differences between arrays and lists. Additionally, it discusses the Python interpreter's modes and the significance of comments in code.

Uploaded by

praveeen291
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)
22 views34 pages

Python Unit-wise 1 Mark Questions

The document contains a series of unit-wise questions and answers focused on Python programming, covering topics such as features of Python, data types, operators, control flow statements, and built-in functions. It provides definitions, examples, and explanations for various concepts, including mutable and immutable data types, the use of the import statement, and the differences between arrays and lists. Additionally, it discusses the Python interpreter's modes and the significance of comments in code.

Uploaded by

praveeen291
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

Python Programming

Unit-wise 1 Mark Questions


Unit-I

1. List any 5 features of python?

Ans: 1. Interpreted 2. Standard Library [Link] typed language [Link]-level


language 5. Open source

2. Which symbol is used to write multi-line comment in python?

Ans: In Python, the symbol used to write multi-line comments is the triple quotation
marks (''' or """)

3. List sequence type data types in python?


Ans: In Python, the sequence type data types include: 1. Lists [Link] [Link] 4.
Range objects
4. Differentiate between compiler and interpreter?
Ans: Compiler:
1) Converts the entire source code into machine code or bytecode before execution.
2) Generates error messages after the entire program has been compiled.
3) Produces an executable file or intermediate code.
4) Examples: GCC (GNU Compiler Collection) for C/C++, Java Compiler.
Interpreter:
1) Executes the source code line by line.
2) Generates error messages when it encounters an error during execution.
3) Does not produce an executable file but directly executes the code.
4) Examples: Python Interpreter, JavaScript Interpreter.
5. What is the task of PVM in code execution?
Ans: The task of the Python Virtual Machine (PVM) in code execution is to interpret
and execute the bytecode generated by the Python compiler. It manages memory,
runs the bytecode instructions, and provides the runtime environment necessary for
executing Python code.
6. What is extended indexing?
Ans: Extended indexing in Python refers to accessing elements within a data
structure using indexing techniques beyond the basic single index. This includes
techniques such as negative indexing, slicing, and using step values in slicing
operations. These extended indexing methods provide flexibility in accessing and
manipulating elements within lists, strings, tuples, and other sequence-like data
structures.
7. Define a set?
Ans: A set in Python is an unordered collection of unique elements. It is defined
using curly braces {} and can contain various data types such as integers, floats,
strings, and tuples. Sets do not allow duplicate elements, and they support
mathematical set operations like union, intersection, difference, and symmetric
difference.
8. Write 2 examples each for mutable and immutable data types?
Ans: Mutable data types:
List: my_list = [1, 2, 3, 4]
You can modify the elements of the list, such as appending new elements or
changing existing ones: my_list.append(5)
Dictionary: my_dict = {'a': 1, 'b': 2}
You can add, remove, or update key-value pairs in the dictionary: my_dict['c'] = 3
Immutable data types:
Tuple: my_tuple = (1, 2, 3, 4)
Once created, you cannot modify the elements of the tuple: my_tuple[0] = 5 (This
would raise an error)
String: my_string = "hello"
Strings cannot be modified in place; any operation that appears to modify a string
actually creates a new string: my_string = my_string.upper()
9. Which method is used to add element at the end of the list?
Ans: The method used to add an element at the end of a list in Python is .append()
and extend().
10. Write a python statement to create a dictionary?
Ans: A Python statement to create a dictionary is as follows:
my_dict = {'key1': 'value1', 'key2': 'value2'}
This statement creates a dictionary my_dict with two key-value pairs.
11. What are the input and output functions in python?
Ans: In Python, the built-in input function is used to accept input from the user,
while the built-in print function is used to display output to the user.
Input function: input()
Output function: print()

Unit-II
1. Define a variable?
Ans: A variable is a named storage location in computer memory that holds a value.
In Python, variables are used to store data that can be manipulated or referenced in
a program. Variables have a name (identifier) and a value, and they can be of
different data types such as integers, floats, strings, lists, dictionaries, etc.
2. Write an example to demonstrate multiple assignment in a single statement?
Ans: a) Assigning multiple values to multiple variables
Syntax: variable1, variable2,……,variable=value1,value2,…..,valuen
Ex: a, b, c = 1, 2.5, "Hello"
b) Assigning single value to multiple variable
Syntax: variable1= variable2=……=variable=value1
Ex: a=b=c=10
3. List the bitwise operators in python?
Ans: he bitwise operators in Python are as follows:
Bitwise AND: &
Bitwise OR: |
Bitwise XOR: ^
Bitwise NOT: ~
Left Shift: <<
Right Shift: >>
4. What is the use of membership operator?
Ans: The membership operators in Python (in and not in) are used to test whether a
value or variable is found within a sequence (such as strings, lists, tuples,
dictionaries, etc.).
in: Returns True if the value is found in the sequence.
not in: Returns True if the value is not found in the sequence.
These operators are particularly useful for checking the presence or absence of
elements in collections.
5. What are identity operators used for in python?
Ans: Identity operators in Python (is and is not) are used to compare the memory
locations of two objects.
is: Returns True if both operands point to the same object in memory.
is not: Returns True if both operands do not point to the same object in memory.
6. Write the syntax of if..elif..else statement?
Ans: The syntax of the if..elif..else statement in Python is as follows:
if condition1:
# code block to execute if condition1 is True
elif condition2:
# code block to execute if condition1 is False and condition2 is True
else:
# code block to execute if both condition1 and condition2 are False
7. List any 5 built-in functions in python?
Ans: Five built-in functions in Python:
print(): Used to display output to the console.
len(): Returns the length (number of items) of an object.
type(): Returns the type of an object.
input(): Reads input from the user via the console.
range(): Generates a sequence of numbers.
8. List the repetitive statements in python?
Ans: for loop: Used to iterate over a sequence (such as lists, tuples, or strings).
while loop: Executes a block of code repeatedly as long as a condition is true.
9. Why do we need break and continue statements in python?
Ans: break statement: It is used to exit (terminate) the loop prematurely based on a
certain condition. When the break statement is encountered within a loop, the loop
is immediately exited, and the program continues with the next statement after the
loop.
Continue statement: It is used to skip the remaining code within the current
iteration of the loop and proceed to the next iteration. When the continue
statement is encountered within a loop, the loop jumps to the next iteration without
executing the remaining code within the loop for the current iteration.
10. What is pass statement?
Ans: The pass statement in Python is a null operation; it doesn't perform any action.
It acts as a placeholder when a statement is syntactically required but no action is
desired or necessary.

Unit-III

1. Define an array?
Ans: An array is collection of similar objects.
2. What is the use of import statement?
Ans: The import statement in Python is used to import modules, which are files
containing Python code that can be reused in other Python programs.
When you import a module using the import statement, you gain access to the
functions, classes, and variables defined in that module, allowing you to use them
within your current Python script or program.
3. Write the advantages and disadvantages of arrays over lists?
Ans: Advantages of arrays over lists:
Efficient Memory Usage: Arrays typically use less memory than lists because they
store elements of the same data type in contiguous memory locations.
Faster Access: Since arrays have fixed-size elements and are contiguous in memory,
accessing elements by index in arrays is generally faster than in lists.
Predictable Performance: Arrays offer more predictable performance for operations
like indexing and element access due to their fixed-size nature.
Disadvantages of arrays over lists:
Fixed Size: Arrays have a fixed size, meaning you need to know the size beforehand.
Lists, on the other hand, can dynamically resize.
Limited Operations: Arrays usually support fewer operations compared to lists. Lists
have built-in methods for various operations, such as appending, inserting, and
removing elements, which are not directly available for arrays.
Homogeneous Elements: Arrays typically store elements of the same data type. Lists,
however, can contain elements of different types, providing more flexibility in data
storage.

4. How do you create a float array in python using array module?


Ans: To create a float array in Python using the array module, you can use the
array() function with the typecode 'f' representing float. Here's how you can create a
float array:
import array
my_float_array = [Link]('f', [1.0, 2.5, 3.7])
5. What is the use of typecode in creating an array using array module?
Ans: The typecode parameter in creating an array using the array module specifies
the type of elements that will be stored in the array. It essentially defines the data
type of the elements that the array can hold.
Python Programming

Unit-wise Important Questions

Unit-I
1. What are the features of Python?
Ans: Python is the world's most popular and fastest-growing computer programming
language. It was developed by Guido van Rossum in 1991. Features of Python:
1. Python is both procedure and object-oriented structure supports such concepts as
classes, objects, inheritance and polymorphism.
2. Indentation: Indentation is one of the greatest feature in python.
3. It’s free and open source software: Downloading python and installing python is free
and easy.
4. Portable Language: Python runs virtually every major platform used today.
5. Interpreted Language: Python is processed at runtime by python Interpreter.
6. Interactive Programming Language: Users can interact with the python interpreter
directly for writing the programs.
7. Straight forward syntax: The formation of python syntax is simple and straight
forward which also makes it popular.
8. Python is a dynamic typed programming language: Users no need to declare the
type of a variable while assigning a value to a variable in Python.
9. Python is a widely used general-purpose, high level programming language.
10. Python is a scripting programming language.
11. Python is a cross-platform independent programming language.
2. Discuss the two modes of using python interpreter?

Ans: Python interpreter is a program that reads and executes Python code. It uses two
execution modes.
1. Interactive mode
2. Script mode
1. Running Python in interactive mode: Without passing python script file to the
interpreter, directly execute code to Python prompt. Once you are inside the python
interpreter, then you can start.
>>> print("hello world")
hello world # Relevant output is displayed on subsequent lines without the >>> symbol.
2. Running Python in script mode: Alternatively, programmers can store Python script
source code in a file with the .py extension, and use the interpreter to execute the
contents of the file. To execute the script by the interpreter, you have to tell the
interpreter the name of the file.
For example, if you have a script name [Link] and you're working on Unix, to run the
script you have to type:
python [Link]
Working with the interactive mode is better when Python programmers deal with small
pieces of code as you can type and execute them immediately, but when the code is
more than 2-4 lines, using the script for coding can help to modify and use the code in
future.
3. Explain the various data types available in python.
Ans: A data type is the classification of the type of values that can be assigned to variables.
In Python, user no need to declare a variable with explicitly mentioning the data type, but
it’s still important to understand the different types of values that can be assigned to
variables in Python.
Python data types are categorized into two as follows:
1. Mutable Data Types: Data types in python where the value assigned to a variable can be
changed. Ex:Lists,Dictionary,Sets
2. Immutable Data Types: Data types in python where the value assigned to a variable
cannot be changed. Ex:int,float,complex,Boolean,Strings,Tuples
[Link]: int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length.
[Link]: float, or "floating point number" is a number, positive or negative, containing one
or more decimals.
[Link]: Objects of Boolean type may have one of two values, True or False.
Examples:
>>> type(True) <class 'bool'> >>> type(False) <class 'bool'>
4. Complex: Complex number is represented by complex class. It is specified as (real part) +
(imaginary part)j.
Example: 100+5j
[Link] data type :A string is a collection of one or more characters enclosed within a
single quote, double quote or triple quote. In python there is no character data type and it
is represented by str class.
Example:
String1='Welcome to the World'
print(String1)
6. List data type List is a collection of mixed data types which is ordered and changeable.
List allows duplicate members. List is written with square brackets.
Example:
list=[501,"Raju", “1st Year”, "CSE"]
print(list)
[Link] data type Tuple is a collection of mixed data types which is ordered and
unchangeable. Tuple allows duplicate members. Tuples are written with rounded brackets.
Example:
tuple=(501,"Raju", “1st Year”, "CSE")
print(tuple)
[Link] data type A dictionary is a collection of mixed data types which is unordered,
changeable and indexed. In python dictionaries are written with curly brackets, and they
have keys and values.
Example:
dict={"Name":"Raju","Rollno":501,"Year":"1st Year":,"Branch":"CSE"}
print(dict)
[Link] data type Set is a collection of mixed data types which are unordered and unindexed.
Set doesn’t allow duplicate members. Sets are written with curly brackets.
Example:
set={501,"Raju", “1st Year”, "CSE"}
print(set)
4. Define a comment and list out different types of comments with syntax?
Ans: Comments are very important while writing a program. Comments are basically
used to make the code more readable or to know what is exactly going inside the
code. In Python, we use the hash(#) symbol to start writing a comment. It extends
up to the new line character. Comments are for programmers for better
understanding of a program. Python Interpreter ignores comment.
Single -line comments Single-line comments begins with a hash(#) symbol and is
useful in mentioning that the whole line should be considered as a comment until
the end of line.
Example
#This is a comment
#print out Hello
print('Hello')
Multi-line comments If we have comments that extend multiple lines, we can use
triple quotes, either '''or """. These triple quotes are generally used for multi-line
strings. But they can be used as multi-line comment as well.
Example
"""This is also a
Perfect example of
multi-line comments"""
5. With suitable examples discuss any 5 built-in functions on strings?
Ans: A string is a collection of one or more characters enclosed within a single quote,
double quote or triple quote. In python there is no character data type and it is
represented by str class.
Example:
String1='Welcome to the World'
print(String1)
String methods in Python:
[Link](): The isalnum() method returns True if all the characters are
alphanumeric, meaning alphabet letter (a-z) and numbers (0-9), otherwise returns
False.
Syntax: [Link]()
Example:
>>> string="123alpha"
>>>[Link]()
True
[Link](): The isalpha() method returns True if all the characters are alphabet
letters (a-z), otherwise returns False.
Syntax: [Link]()
Example:
>>> string="nikhil"
>>>[Link]()
True
[Link](): The isdigit() method returns True if all the characters are digits, otherwise
returns False.
Syntax: [Link]()
Example:
>>> string="123456789"
>>>[Link]()
True
[Link](): The islower() method returns True if all the characters are in lower case,
otherwise returns False.
Syntax: [Link]()
Example:
>>> string="nikhil"
>>>[Link]()
True
[Link](): The isnumeric() method returns True if all the characters are numeric
(0-9), otherwise returns False.
Syntax: [Link]()
Example:
>>> string="123456789"
>>>[Link]()
True
[Link](): The isspace() method returns True if all the characters in a string are
whitespaces, otherwise returns False.
Syntax: [Link]()
Example:
>>> string=" "
>>>[Link]()
True
[Link]() The istitle() method returns True if all words in a text start with a upper
case letter, and the rest of the word are lower case letters, otherwise returns False.
Syntax: [Link]()
Example:
>>> string="Nikhil Is Learning"
>>>[Link]()
True
[Link]() The isupper() method returns True if all the characters are in upper case,
otherwise returns False.
Syntax: [Link]()
Example:
>>> string="HELLO"
>>>[Link]()
True
6. What is a List? Discuss indexing and slicing a list with suitable examples?
Ans: A list is a data structure in Python that is a mutable, or changeable, ordered
sequence of elements. Each element or value that is inside of a list is called an item.
Just as strings are defined as characters between quotes, lists are defined by having
values between square brackets [ ].
Syntax:
list_name = [element_1, element_2, element_3, ...]
Example:
list=[501,"Raju", “1st Year”, "CSE"]
print(list)
Indexing Lists
In Python, every list with elements has a position or index. Each element of the list
can be accessed or manipulated by using the index number.
They are two types of indexing −
1. Positive Indexing
2. Negative Indexing
Positive Indexing
In positive the first element of the list is at an index of 0 and the following elements
are at +1 and as follows.
In the below figure, we can see how an element is associated with its index or
position.

Example
The following is an example code to show positive indexing of lists.

list= [5,2,9,7,5,8,1,4,3]
print(list[2])
print(list[5])
Output
9
8
Negative Indexing
In negative indexing, the indexing of elements starts from the end of the list. That is
the last element of the list is said to be at a position at -1 and the previous element
at -2 and goes on till the first element.
In the below figure, we can see how an element is associated with its index or
position.
Example
The following is an example code to show the negative indexing of lists.
list= [5,2,9,7,5,8,1,4,3]
print(list[-2])
print(list[-8])
Output
4
2
Slicing List
List slicing is a frequent practice in Python, and it is the most prevalent technique
used by programmers to solve efficient problems. Consider a Python list. You must
slice a list in order to access a range of elements in it. One method is to utilize the
colon as a simple slicing operator (:).
The slice operator allows you to specify where to begin slicing, where to stop slicing,
and what step to take. List slicing creates a new list from an old one.
Syntax:
List_name[Start : Stop : Stride]
where,

 start – index position from where the slicing will start in a list
 stop – index position till which the slicing will end in a list
 step – number of steps, i.e. the start index is changed after every n steps, and list
slicing is performed on that index
Note – In Python, indexing starts from 0, and not 1.
Example
list= [5,2,9,7,5,8,1,4,3]
print(list[0:6])
print(list[Link])
print(list[-1:-5:-2])
Output
[5, 2, 9, 7, 5, 8]
[2, 7, 8, 4]
[3, 1]
7. Explain any 8 methods on lists with suitable examples?
Ans: List methods in Python:
[Link]: The append() method adds an item to the end of the list.
Syntax: [Link](item)
Example:
>>> x=[1,5,8,4]
>>>[Link](10)
>>> x
[1, 5, 8, 4, 10]
[Link]: The extend() method adds the specified list elements to the end of the
current list.
Syntax: [Link](newlist)
Example:
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>>[Link](y)
>>> x
[1, 2, 3, 4, 3, 6, 9, 1]
[Link]: The insert() method inserts the specified value at the specified position.
Syntax: [Link](position,item)
Example:
>>> x=[1,2,4,6,7]
>>>[Link](2,10)
>>> x
[1, 2, 10, 4, 6, 7]
[Link]: The pop() method removes the item at the given index from the list and
returns the removed item.
Syntax: [Link](index)
Example:
>>> x=[1, 2, 10, 4, 6]
>>>[Link](2)
10
>>> x
[1, 2, 4, 6]
[Link]: The remove() method removes the specified item from a given list.
Syntax: [Link](element)
Example:
>>> x=[1,33,2,10,4,6]
>>> [Link](33)
>>> x
[1, 2, 10, 4, 6]
[Link]: The reverse() method reverses the elements of the list.
Syntax: [Link]()
Example:
>>> x=[1,2,3,4,5,6,7]
>>>[Link]()
>>> x
[7, 6, 5, 4, 3, 2, 1]
[Link]: The sort() method sorts the elements of a given list in ascending order.
Syntax: [Link]()
Example:
>>> x=[10,1,5,3,8,7]
>>>[Link]()
>>> x
[1, 3, 5, 7, 8, 10]
[Link]: The clear() method removes all items from the list.
Syntax: [Link]()
Example:
>>> x=[1,2,3,4,5,6,7]
>>>[Link]()
>>> x
[]
9. length(): The len() method is used to find the number of items or values present
in a list.
Syntax: len(list)
Example:
>>> x=[1,2,3,4,5]
>>> len(x)
5 7.
10. Define a dictionary? Illustrate any 5 functions with examples?
Ans: A dictionary is a collection of mixed data types which is unordered,
changeable and indexed. In python dictionaries are written with curly brackets,
and they have keys and values.
Syntax: dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3, ...}
Example:
dict={"Name":"Raju","Rollno":501,"Year":"1st Year":,"Branch":"CSE"}
print(dict)
Dictionary methods in Python:
[Link](): The update() method inserts the specified items to the dictionary.
Syntax: [Link]({“keyname”:”value”})
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> [Link]({"cse":"dileep"})
>>> dict {'brand': 'mrcet', 'model': 'college', 'year': 2004, 'cse': 'dileep'}
[Link](): The pop() method removes the specified item from the dictionary.
Syntax: [Link](keyname)
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> [Link]("model"))
college
>>> dict {'brand': 'mrcet', 'year': 2005}
[Link](): Returns all the items present in the dictionary. Each item will be inside
a tuple as a key-value pair.
Syntax: [Link]()
Example:
>>>dict={"brand":"mrcet","model":"college","year":2004}
>>> [Link]()
dict_items([('brand', 'mrcet'), ('model', 'college'), ('year', 2004)])
[Link](): Returns the list of all keys present in the dictionary.
Syntax: [Link]()
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> [Link]()
dict_keys(['brand', 'model', 'year'])
[Link](): Returns the list of all values present in the dictionary
Syntax: [Link]()
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> [Link]()
dict_values(['mrcet', 'college', 2004])
11. Write in detail about Tuples and Sets ?
Ans: Tuple is a collection of mixed data types which is ordered and
unchangeable. Tuple allows duplicate members. Tuples are written with rounded
brackets.
Syntax:
tuple_name=(element_1,element_2,element_3,...)
Example:
tuple=(501,"Raju", “1st Year”, "CSE")
print(tuple)
Tuple methods
[Link](): The count() method returns the number of times a specified value
appears in the tuple.
Syntax:
[Link](value)
Example:
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>>[Link](2)
4
[Link](): The index() method searches the tuple for a specified value and
returns the position of where it was found.
Syntax:
[Link](value)
Example:
>>> x=(1,2,3,4,5,6)
>>>[Link](2)
1
3. length(): The len() method is used to find the number of items or values present
in a tuple.
Syntax: len(tuple)
Example:
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
> >> len(x)
12
Set: Set is a collection of mixed data types which are unordered and unindexed.
Set doesn’t allow duplicate members. Sets are written with curly brackets.
Syntax:
set_name = {element_1, element_2, element_3, ...}
Example:
set={501,"Raju", “1st Year”, "CSE"} print(set)
Set methods in Python:
[Link](): The add() method adds an element to the set.
Syntax: [Link](element)
Example:
>>> x={"mrcet","college","cse","dept"}
>>>[Link]("autonomous")
>>> x
{'mrcet', 'dept', 'autonomous', 'cse', 'college'}
[Link](): The pop() method removes a random item from the set. This method
returns the removed item.
Syntax: [Link]()
Example:
>>> x={1, 2, 3, 4, 5, 6, 7, 8}
>>>[Link]()
1
>>> x
{2, 3, 4, 5, 6, 7, 8}
12. How are type conversions done in python? Illustrate with suitable examples?
Ans: The process of converting a value from one data type to another data type
is called Typecasting. In Python, the typecasting is performed using built-in
functions.
The following are the constructor functions used to perform typecasting.
[Link]() - constructs an integer number from an integer literal, a float literal (by
rounding down to the previous whole number), or a string literal (providing the
string represents a whole number).
We can use int() function to convert values from other types to int
Examples:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
[Link]() - constructs a float number from an integer literal, a float literal or a
string literal (providing the string represents a float or an integer)
We can use float() function to convert other type values to float
Examples:
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
[Link]() - constructs a string from a wide variety of data types, including strings,
integer literals and float literals.
We can use str() method to convert other type values to str type.
Examples:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

Unit-II
1. What is dynamic typing? Discuss the various ways of defining a variable in python?
Ans: Dynamic typing is a programming language feature where the type of a variable is
determined at runtime, as opposed to compile time. In dynamically typed languages,
variables can hold values of any type, and their types can change during the execution
of the program. This means that you don't have to declare the type of a variable
explicitly before using it, as the type is inferred based on the value assigned to it.
For example, in Python, you can write:
x = 5 # x is inferred to be an integer
x = "hello" # Now x is inferred to be a string
Variable:
A variable is a data name which can be used to store some data value. There is no
specific keyword used to create a variable. Variables are created directly by specifying
the variable name with a value. We don't need to declare a variable before using it. In
Python, we simply assign a value to a variable and it will exist.
Syntax: variable_name = value
Rules for Python variables:
1. A variable name must start with a letter or the underscore character.
2. A variable name cannot start with a number.
3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ ).
4. Variable names are case-sensitive (age, Age and AGE are three different variables).
There are 2 types of variable assignments in Python.
1. Single variable assignment
2. Multiple variable assignment
1. Single variable assignment We use the assignment operator (=) to assign values to a
variable. Any type of value can be assigned to any valid variable.
Example
a=5
b = 3.2
c = "Hello“
2. Multiple variable Assignment Python allows you to assign a single value to several variables
simultaneously.
Example:
a = b = c = 10
a,b,c=2,3.4,”hello”
Here, an integer object is created with the value 10, and all three variables are assigned to the
same memory location.
You can also assign multiple objects to multiple variables.
Example a,b,c = 1,2,"mrcet”
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and
one string object with the value "mrcet" is assigned to the variable c.
3. Explain Arithmetic, Relational and Bitwise operators with their syntax and examples?
Ans:
[Link] operators: Arithmetic operators are used to perform different mathematical
operations between the operands. Python has the following seven arithmetic operators.
 Addition (+)
 Subtraction (-)
 Multiplication (*)
 Division (/)
 Floor division (//)
 Modulus (%)
 Exponentiation (**)
Example:
a=10
b=5
print("a+b=",a+b)
print("a-b=",a-b)
print("a*b=",a*b)
print("a/b=",a/b)
print("a%b=",a%b)
print("a//b=",a//b)
print("a**b=",a**b)
Relational operators are also called comparison operators. It performs a comparison between
two values. It returns a boolean True or False depending upon the result of the comparison.
Python has the following six relational operators.
a. Greater than (>)
b. Less than(<)
c. Equal to(==)
d. Not equal to(!=)
e. Greater than or equal to(>=)
f. Less than or equal to(<=)

Example:

a=10

b=5
print("a>b is",a>b)

print("a>b is",a<b)

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

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

print("a>=b is",a<=b)

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

Bitwise Operators: In Python, bitwise operators are used to performing bitwise operations on
integers. To perform bitwise, we first need to convert integer value to binary (0 and 1) value.
The bitwise operator operates on values bit by bit, so it’s called bitwise. It always returns the
result in decimal format. Python has the following 6 bitwise operators.

 Bitwise AND: &


 Bitwise OR: |
 Bitwise XOR: ^
 Bitwise NOT: ~
 Left Shift: <<
 Right Shift: >>
Example:

a = 10

b = 20

r1 = a & b

r2 = a | b

r3 = a ^ b

r4 = a << 2

r5 = b >> 2

r6 = ~a

print(r1,r2,r3,r4,r5,r6)
4. Define a Boolean expression? What operators are used to evaluate a Boolean
expression?
Ans: A Boolean expression is a logical statement that evaluates to either true or false. These
expressions typically involve relational operators, logical operators, and variables or
constants. They are commonly used in programming and logic to control the flow of execution
or to make decisions based on conditions.
The operators used to evaluate Boolean expressions include:
Relational Operators: These operators compare two values and return either true or false
based on the relationship between them. Common relational operators include:
Equal to: ==
Not equal to: !=
Greater than: >
Less than: <
Greater than or equal to: >=
Less than or equal to: <=
Logical Operators: These operators are used to combine multiple Boolean expressions and
evaluate them together. Common logical operators include:
Logical AND: and or &&
Logical OR: or or ||
Logical NOT: not or !
Bitwise Operators: While less commonly used in Boolean expressions, bitwise operators can
also be used to evaluate Boolean conditions at the bit level. Common bitwise operators
include:
Bitwise AND: &
Bitwise OR: |
Bitwise XOR: ^
Bitwise NOT: ~
These operators can be combined to form complex Boolean expressions that can evaluate
multiple conditions and control the flow of a program accordingly.
5. Discuss with suitable examples, membership and identity operators in python?
Ans: Membership operators: Membership operators are used to check for membership of
objects in sequence, such as string, list, tuple. It checks whether the given value or variable is
present in a given sequence. If present, it will return True otherwise False. Python has the
following two membership operators.
in
not in
Example:
>>>x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
Identity operators: Identity operators are used to check whether the value of two variables is
same or not. If same, it will return True otherwise False. Python has the following two identity
operators.
is
is not.
Example
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
print(x1 is y1)
print(x2 is not y2)
6. Show an example of how precedence of operators effects an expression evaluation?
Ans: When two operators share an operand, the operator with the higher precedence goes
first.
Example

7. What are the different conditional statements available in python? Explain with syntax
and examples. (Or) Illustrate chained and nested conditional execution statements with
syntax and flowcharts?
Ans: Conditional statements are used to execute either a single statement or a group of
statements based on the condition. There are 3 types of conditional statements in python.
[Link] statement
[Link] else statement
[Link] statement
[Link] statement: if statement flowchart:

In conditional statements, The if statement is the simplest form. It takes a condition and
evaluates to either True or False. If the condition is True, then the True block of code will
be executed, and if the condition is False, then the block of code is skipped, and the
controller moves to the next line.
Syntax :
if(condition):
statement 1
statement 2
.
.
.
.
statement n
Example
a=int(input('Enter any no'))
if(a>25):
print('Given no is greater than 25')

[Link] else statement:


flowchart:
The if else statement checks the condition and executes the ‘if’ block of code when the
condition is True, and if the condition is False, it will execute the else block of code.
Syntax
if(condition):
statement 1
else:
statement 2
Example
n=int(input('Enter any no'))
if(n%2==0):
print('given no is even')
else:
print('given no is odd')

3. if-elif-else statement/Chained multiple if statement: if elif else statement flowchart

In Python, the if-elif-else condition statement has an elif keyword used to chain multiple
conditions one after another. The if-elif-else is useful when you need to check multiple
conditions.
Syntax
if(condition1):
statement1
elif(condition2):
statement2
elif(condition3):
statement3
...
else:
statement
Example
a=int(input('Enter the value of a '))
b=int(input('Enter the value of b '))
c=int(input('Enter the value of c '))
if((a>b) and (a>c)):
print('a is largest')
elif((b>a) and (b>c)):
print('b is largest')
else:
print('c is largest')

8. List and explain different iterative statements with syntax?


Ans: In Python, iterative statements allow us to execute a block of code repeatedly as long as
the condition is True. We also call it a loop statements. Python provides us the following two
loop statement to perform some actions repeatedly.
[Link] loop
[Link] loop
[Link] loop: It is used when a group of statements are executed repeatedly until the
specified condition is true. It is also called entry controlled loop. The minimum number of
execution takes place in while loop is 0.
Syntax:
while(condition):
statement 1
statement 2
……..
statement n
Example
i=1
print("The nos from 1 to 10 are ")
while(i<=10):
print(i)
i=i+1
[Link] loop: In Python, the for loop is used to iterate over a sequence such as a list, string,
tuple, other iterable objects such as range. With the help of for loop, we can iterate over each
item present in the sequence and executes the same set of operations for each item. Using a
for loop in Python we can automate and repeat tasks in an efficient manner.
Syntax:
for var in range/sequence:
statement 1
statement 2
………….
statement n
Example :
for i in range(1,11):
print(i)
9. Explain the use of the following statements with examples
i. break
ii. continue
iii. pass

Ans: Normal flow of control can be transferred from one place to another place in the
program. This can be done by using the following unconditional statements in python. There
are 3 types of Unconditional statements in python. They are
1. break
2. continue
3. pass
[Link] statement: break is an unconditional statement used to terminate the loops. When it
is used in loops (while,for) control comes out of the loop and continues with the next
statement in the program.
Syntax:-
statement
break
Example:
for i in range(1,6,1):
if(i==4):
break
printf(i)
[Link] statement: continue is an unconditional statement used to control to be
transferred to the beginning of the loop for the next iteration without executing the
remaining statements in the program.
Syntax:-
statement
continue
Example:
for i in range(1,6,1):
if(i==4):
continue
printf(i)
[Link] statement: The pass statement is a null statement. But the difference between pass
and comment is that comment is ignored by the interpreter whereas pass is not ignored.
The pass statement is generally used as a placeholder i.e. when the user does not know what
code to write. So user simply places pass at that line. pass is just a placeholder for
functionality to be added later. Sometimes, pass is used when the user doesn’t want any code
to execute.
Syntax:
pass
Example:
a=10
b=20
if(a>b):
pass
Unit-III
1. Define array? Explain how to create an array using array module?

Ans: An array is defined as a collection of items sorted at contiguous memory locations. An


array is like a container that holds similar types of multiple items together, this helps in making
calculation easy and faster. In python, the array can be handled by a module called “array”,
which is helpful if we want to manipulate a single type of data value. Below are two important
terms that can help in understanding the concept of an array.
1. Element: Each item stored in an array is called an element.
2. Index: The location of each element is defined by a numerical value called index.
Each element in an array has an index value by which it can be identified.
Array Representation
The array can be declared in multiple ways depending upon the programming language we
are using. But few points are important that need to consider while working with an array:
1. The starting index of an array is 0
2. Each element in an array is accessible by its index
3. The length or size of an array determines the capacity of the array to store the elements
The syntax for Array Representation
import array
arrayName = [Link] (type code, [array,items])
or
import array as arr
arrayName = [Link] (type code, [array,items])
or
from array import *
arrayName = array (type code, [array,items])
 arrayname would be the name of the array.
 The typecode specifies what kind of elements would be stored in the array. Whether it
would be an array of integers, an array of floats or an array of any other Python data
type. Remember that all elements should be of the same data type.
 Inside square brackets you mention the elements that would be stored in the array,
with each element being separated by a comma.
Creating Python Array
In Python, the array can be created by importing the array module. You can now create the
array using [Link](). Instead of using [Link]() all the time, you can use “import array
as arr”, the arr will work as an alias and you can create an array using [Link](). This alias can
be anything as per your preference.
variable_name = array(typecode, [value_list])
For Example:
import array as arr
myarray = [Link] ( ‘i’, [1, 2, 3, 4, 5])
In the above code, the letter ‘i’ represents the type code and the value is of integer type.
The below tables show the type codes:
Type code C Type Python Type Minimum size in bytes

'b' signed char int 1

'B' unsigned char int 1

'u' PY-UNICODE Unicode character 2


'h' signed short int 2

'H' unsigned short int 2

'i' signed int int 2

'I' unsigned int int 2

'l' signed long int 4

'L' unsigned long int 4

'q' signed long long int 8

'Q' unsigned long long int 8

'f' float float 4

'd' double float 8

Accessing Python Array Elements :


We can access the Array elements by using its index. The index is always an integer.
Syntax: variable_name [index_number]
Example:
import array as ar
a = [Link] (‘i’ , [165, 166, 154, 176, 144])
print (a[3])
print (a[0])
print (a[-3])
print (a[-1])
Output:
176
165
154
144
Slicing Python Arrays
The slicing operator “ : “ helps to access the range of elements in an array.
Example:
import array as ar
value = [Link] (‘i’, [5, 2, 7, 1, 34, 54, 22, 7, 87, 2¸ 53, 22, 0, 11])
print (value [1:5])
print (value [7:])
print (value [:])
print (value [:-5])
Output :
array (‘i’ , [2, 7, 1, 34])
array (‘i’ , [22, 7, 87, 2¸ 53, 22, 0, 11])
array (‘i’ , [5, 2, 7, 1, 34, 54, 22, 7, 87, 2¸ 53, 22, 0, 11])
array (‘i’ , [5, 2, 7, 1, 34, 54, 22, 7, 87])
2. List the methods on arrays, discuss their usage with suitable examples?
Ans:
1. Length of an array: To find out the exact number of elements contained in an array, use
the built-in len() method. It will return the integer number that is equal to the total
number of elements in the array you specify.
Example:

import array as arr


numbers = [Link]('i',[10,20,30])
print(len(numbers))
output
3
2. Search Through an Array: You can find out an element's index number by using the index()
method. You pass the value of the element being searched as the argument to the method,
and the element's index number is returned.
Example:
import array as arr
numbers = [Link]('i',[10,20,30])
#search for the index of the value 10
print([Link](10))

output
0
3. [Link] :The typecode character used to create the array.
Example:
import array as arr
numbers = [Link]('i',[10,20,30])
print([Link])

output
‘i’
4. [Link] :The length in bytes of one array item in the internal representation.
Example:
import array as arr
array_num = array('i', [1,3,5,7,9,10,15])
print(array_num.itemsize)
output
4

5. Adding List Elements:


We can add elements to lists in three ways:

a) append() : append() method can add single element or an object in a list.


Syntax : array_name.append (value)
Example:
import array as arr
numbers = [Link]('i',[10,20,30])
[Link](100)
print(numbers)
output
array(‘I’,[10,20,30,100])

b) insert() : insert() method inserts the element at a specific position


Syntax : array_name.insert ( index_value , element)
Example:
import array as arr
numbers = [Link]('i',[10,20,30])
[Link](1,100)
print(numbers)
output
array(‘I’,[10,100,20,30])
c) extend(): extend() method helps to add multiple elements at the end of the lists at the
same time. Both append() and extend() add elements at the end of the array, but extend()
can add multiple elements together with is not possible in append().
Syntax : array_name.extend ([value1, value2, value3, ….. ])
Example:
import array as arr
numbers = [Link]('i',[10,20,30])
[Link]([11,12,13])
print(numbers)
output
array(‘I’,[10,20,30,11,12,13])
6. Removing Python Array Elements
We can remove elements from an array using three methods,
a) remove(): The remove() method will remove only the first occurrence of an item. That
means if the same items are present multiple times in a list the remove() method will
only remove the first occurrence of that item.
Syntax: array_name.remove (value)
Example:
import array as arr
numbers = [Link]('i',[10,20,30])
[Link](30)
print(numbers)
output
array(‘I’,[10,20])

b) pop(): pop() method is another method to remove elements from the lists. It performs
the same tasks as the remove() method, but the only difference is that the remove()
method takes the value as an argument, and the pop() method accepts the index as an
argument. We need to give the index as an argument and the pop() method will pop out
the value present at that particular index. The pop() method returns the value present
at that index.
Syntax : array_name.pop (index_value)
Example:
import array as arr
numbers = [Link]('i',[10,20,30])
[Link](1)
print(numbers)
output
array(‘I’,[10,30])

c) del: The del operator is similar to the pop() method with one important difference. The
del method takes the index as an argument and remove that element from the list but
does not return any value. But the pop() method returns the value present at that index.
Similar to the pop() method, del also raises “IndexError” if the index or the indices
specify are out of range.
Syntax : del array_name[index_value]
Example:
import array as arr
numbers = [Link]('i',[10,20,30])
del numbers[1]
print(numbers)
output
array(‘I’,[10,30])

7. Array Concatenation: In array concatenation, we use concatenate arrays with the help of
the symbol “+”.
Example:
import array as arr
a= [Link]('i',[10,20,30])
b= [Link]('i',[11,12,13])
print(a+b)
output
array('i', [10, 20, 30, 11, 12, 13])

8. count() : Return the number of occurrences of x in the array.


Syntax : array_name.count(value)
Example:
import array as arr
a= [Link]('i',[10,20,30,10,2,10])
print([Link](10))
output
3
9. reverse(): Reverse the order of the items in the array.
Syntax : array_name.reverse()
Example:
import array as arr
a= [Link]('i',[10,20,30])
[Link]()
print(a.)
output
array('i', [30,20,10])

You might also like