Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

Python Unit1 Solved Questions

Uploaded by

ABU THAHIR
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Python Unit1 Solved Questions

Uploaded by

ABU THAHIR
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Python Unit-1 Solved Question Bank

-> Two Mark questions


1. How to write a comment line in Python? Mention two types.
Single Line Comment In Python:, use the hash (#) symbol to start writing a comment. Hash (#)
symbol makes alltext following it on the same line into a comment. For example, #This is single line
Python comment Multiline Comments If the comment extends multiple lines, then one way of
commenting those lines is to use hash (#) symbol at the beginning of each line. For example,
#This is #
multiline comments:in Python Another way of doing this is to use triple quotes, either ''' or """.
These triple quotes are gener- ally used for multiline strings. However, they can be used as a
multiline comment as well.For example, '''This is multiline comment in Python using triple quotes'''

2. What is Python Virtual Machine?


Computers can only understand the code written in machine language. Machine
languageusually involves instructions written in binary form i.e 0’s & 1’s. Hence, in other words, we
need a software that can convert our high level code to machine code – we use compiler.

Role of Python Virtual Machine (PVM) is to convert the byte code instructions into machine
code that are understandable by computers. To do this, PVM has interpreter. Interpreter is
responsible for converting byte-code to machine-oriented codes

3. List any four flavors of Python


Flavors of Python simply refers to the different Python compilers. These flavors are usefulto
integrate various programming languages into Python. Let us look at some of these flavors:

1. CPython: CPython is the Python compiler implemented in C programming language. In this, Python
code is internally converted into the byte code using standard C functions. Additionally, it is possible
to run and execute programs written in C/C++ using CPython compiler.

2. Jython: Earlier known as JPython. Jython is an implementation of the Python programming


language designed to run on the Java platform. Jython is extremely usefulbecause it provides the
productivity features of a mature scripting language while runningon a JVM.

3. PyPy:Thisisthe implementation using Python language. PyPy often runsfaster thanCPython


because PyPy is a just-in-time compiler while CPython is an interpreter.

4. IronPython: IronPython is an open-source implementation of the Python programming language


which is tightly integrated with the .NET Framework.

5. RubyPython:RubyPython is a bridge between the Ruby and Python interpreters. Itembeds a


Python interpreter in the Ruby application’s process using FFI (Foreign FunctionInterface).

6. Pythonxy: Python(x,y) is a free scientific and engineering development software for numerical
computations, data analysis and data visualization based on Python.
7. StacklessPython: Stackless Python is a Python programming language interpreter. In practice,
Stackless Python uses the C stack, but the stack is cleared betweenfunction calls

8. AnacondaPython: Anaconda is a free and open-source distribution of the Pythonand R


programming languages for scientific computing, that aims to simplify package management and
deployment. Package versions are managed by the package management system conda.

4. Give 2 step process of Python program execution


The execution of the Python program involves 2 Steps:

• Compilation

• Interpreter

Compilation :The program is converted into byte code. Byte code is a fixed set of instructions that
represent arithmetic, comparison, memory operations, etc. It can run on any operating system and
hardware. The byte code instructions are created in the .pyc file. The .pyc fileis not explicitly created
as Python handles it internally but it can be viewed

Interpreter: The next step involves converting the byte code (.pyc file) into machine code. This step is
necessary as the computer can understand only machine code (binary code). Python Virtual Machine
(PVM) first understands the operating system and processor in the computer and then converts it
into machine code. Further, these machine code instructions are executed by processor and the
results are displayed.

5. List any four standard datatypes supported by Python.


Data types specify the type of data like numbers and characters to be stored and manipu-
lated within a program. Basic data types of Python are:

• Numbers

• Boolean

• Strings

• None

6. How to determine the data type of a variable? Give the syntax and example
The type() Function and Is Operator

The syntax for type() function is,

type(object) #The type() function returns the data type of the given object.

1. >>> type(1)

2. >>> type(6.4)

3. >>> type("A")

4. >>> type(True)

The type() function comes in handy if you forget the type of variable or an object during the course
of writing programs.
7. What is the purpose of membership operators? Give example
Membership operators are used to test the membership of a value within a
sequence, such as a string, list, or tuple. These operators return a Boolean value
indicating whether the value is present or not.

There are two membership operators in Python:

1. in operator: It checks if a value exists in a sequence and returns True if the


value is found, and False otherwise.
2. not in operator: It checks if a value does not exist in a sequence and returns
True if the value is not found, and False otherwise.

Eg:

fruits = ['apple', 'banana', 'orange']

# Check if 'apple' is present in the list

if 'apple' in fruits:

print("We have apples!")

# Check if 'grape' is not present in the list

if 'grape' not in fruits:

print("We don't have grapes!")

8. How to input data in Python? Give syntax and example


In Python, input() function is used to gather data from the user.
The syntax for input function is,

variable_name = input([prompt])
prompt is a string written inside the parenthesis that is printed on the screen.

9. List four type conversion functions.


1.The int() Function
2.The float() Function
3. The str() Function
4. The chr() Function

10.List any four categories of Operators in Python


1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
11.What is indentation? Why it is required?
• In Python, Programs get structured through indentation . Usually, we expect indentation
from any program code, but in Python it is a requirement and not a matter of style.
• This principle makes the code look cleaner and easier to understand and read. Any statements
written under another statement with the same indentation is interpreted to belong to the same 14
code block.
• If there is a next statement with less indentation to the left,then it just means the end of the
previous code block.
• In other words, if a code block has to be deeply nested, then the nested statements need to be
indented further to the right.Usually, four whitespaces are used for indentation and are preferred
over tabs. Incorrect indentation will result in IndentationError.

12.Give syntax of if ..elif statement in Python


The if…elif…else is also called as multi-way decision control statement. When you need to
choose from several possible alternatives, then an elif statement is used along with an ifstatement.
The keyword ‘elif’ is short for ‘else if’ and is useful to avoid excessive indenta- tion. The else
statement must always come last, and will again act as the default action.
The syntax for if…elif…else statement is,
if Boolean_Expression_1:
statement_1
elif Boolean_Expression_2:
statement_2
elif Boolean_Expression_3:
statement_3

13.What is the purpose of else suit in Python loops? Give example


The `else` suite in Python loops provides a way to execute a block of code when the loop completes
normally, without being interrupted by a `break` statement. It is not mandatory to include the `else` suite in a
loop, but it can be useful in certain situations.

Here's an example to demonstrate the usage of the `else` suite in a loop:

fruits = ['apple', 'banana', 'orange']

for fruit in fruits:


if fruit == 'grape':
print("Grapes found! Exiting the loop.")
break
print(fruit)
else:
print("All fruits processed.")

print("Loop finished.")

Output
apple
banana
orange
All fruits processed.
Loop finished.
14.What are the rules for naming identifiers?
• 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 myCountry, other_1 and good_morning, all are valid examples.
• A Python identifier can begin with an alphabet (A – Z and a – z and _).
• An identifier cannot start with a digit but is allowed everywhere else. 1plus is invalid, but plus1 is
perfectly fine.
• Keywords cannot be used as identifiers.
• One cannot use spaces and special symbols like !, @, #, $, % etc. as identifiers.
• Identifier can be of any length

15.What is an identifier? Give example


An identifier is a name given to a variable, function, class or module. Identifiers may be one
or more characters. It is essentially a user-defined name given to a programming element,
which helps in referring to and accessing that element in the code.

Eg:
name = "John" # Variable identifier

def calculate_sum(a, b): # Function identifier


return a + b

class Circle: # Class identifier


def __init__(self, radius):
self.radius = radius

def calculate_area(self):
return 3.14 * self.radius ** 2

16.What are python keywords? Give example


Keywords are a list of reserved words that have predefined meaning. Keywords are special
vocabulary and cannot be used by programmers as identifiers for variables, functions, constants or
with any identifier name. Attempting to use a keyword as an identifier namewill cause an error
17.What are python Variables?
• Variable is a named placeholder to hold any type of data which the program can use to
assign and modify during the course of execution.
• In Python, there is no need to declarea variable explicitly by specifying whether the variable is an
integer or a float or any othertype.
• To define a new variable in Python, we simply assign a value to a name. If a need for vari- able
arises you need to think of a variable name based on the rules mentioned in the fol- lowing
subsection and use it in the program.

18.What are the rules for naming variables?


Follow the below-mentioned rules for creating legal variable names in Python
. • Variable names can consist of any number of letters, underscores and digits.
• Variable should not start with a number.
• Python Keywords are not allowed as variable names.
• Variable names are case-sensitive. For example, computer and Computer are dif- ferent variables.

19.Give syntax and example for assigning values to variables


The general format for assigning values to variables is as follows:
variable_name = expression

1. >>> number =100


2. >>> miles =1000.0
3. >>> name ="Python"
4. >>> number
100
5. >>> miles
1000.0
6. >>> name
'Python'

20.Give the syntax and example for str.format() method


The syntax for format() method is,
str.format(p0, p1, ..., k0=v0, k1=v1, ...)

Program : Program to Demonstrate the Positional Change of Indexes of Arguments


1. a = 10
2. b = 20
3. print("The values of a is {0} and b is {1}".format(a, b))
4. print("The values of b is {1} and a is {0}".format(a, b))

OUTPUT
The values of a is 10 and b is 20The values of b is 20 and a is 10

21.What is f-string literal? Give an example


• Formatted strings or f-strings were introduced in Python 3.6. A f-string is a string literal thatis
prefixed with “f”.
• These strings may contain replacement fields, which are expressions enclosed within curly braces
{}. The expressions are replaced with their values.
• In the realworld, it means that you need to specify the name of the variable inside the curly braces
to display its value. An f at the beginning of the string tells Python to allow any currently valid
variable names within the string.
Program : Code to Demonstrate the Use of f-strings with print() Function
1. country = input("Which country do you live in?")
2. print(f"I live in {country}")

OUTPUT
Which country do you live in? IndiaI live in India

22.What are syntax errors? Give example


Syntax errors, also known as parsing errors, are perhaps the most common kind of com-
plaint you get while you are still learning Python.
For example,
1. while True
2. print("Hello World)
OUTPUT
File " ", line 1while True ^
SyntaxError: invalid syntax

23.What are Exceptions? Give Example


An exception is an unwanted event that interrupts the normal flow of the program. When an
exception occurs in the program, execution gets terminated.
In such cases,we get a system-generated error message. However, these exceptions can be
handledin Python. By handling the exceptions, we can provide a meaningful message to the user
about the issue rather than a system-generated message, which may not be understandable to the
user.
Example:
1. >>> 10 * (1/0)
Traceback (most recent call last): File "", line 1, in ZeroDivisionError: division by zero
2. >>> 4 + spam*3
Traceback (most recent call last): File "", line 1, in NameError: name 'spam' is not defined 27
3. >>> '2' + 2
Traceback (most recent call last): File "", line 1, in TypeError: Can't convert 'int' object to str
implicitly

24.What is use of finally statement ?


The finally statement in Python is used in exception handling to define a block of
code that will be executed regardless of whether an exception occurs or not. It ensures that
certain actions or cleanup tasks are performed, even if an exception is raised and caught.

25.Differentiate scope and life time of a variable


Scope of a Variable: The scope of a variable determines where it can be
accessed or referenced within the code. It defines the portion of the code where the
variable is visible and can be used. The scope of a variable is usually defined by the
block of code in which it is declared.
Common types of variable scopes in Python are:
• Global scope: Variables declared outside of any function or class have a global
scope. They can be accessed from anywhere within the program.
• Local scope: Variables declared inside a function or a block have a local scope.
They are only accessible within that specific function or block.
Lifetime of a Variable: The lifetime of a variable refers to the duration of time
during which the variable exists and holds a valid value in memory. It is determined
by when the variable is created and when it is destroyed or becomes inaccessible.
The lifetime of a variable depends on its scope and can be categorized as:
• Global variables: They have a lifetime throughout the execution of the
program. They are created when the program starts and are destroyed when
the program ends.
• Local variables: They have a lifetime within the scope in which they are
defined. They are created when the function or block is executed and are
destroyed when the function or block exits.

26.List any four built in functions in Python


1.abs()
2.min()
3.max()
4.pow()
5.len()

27.Give the Syntax of user defined function.


def function_name(parameter_1, parameter_2, …, parameter_n):
statement(s)
28.Give the syntax and example for range() function.
The syntax for range() function is,
range([start ,] stop [, step])
Both start and step arguments are optional and the range argument value should alwaysbe an
integer.
start → value indicates the beginning of the sequence. If the start argument is notspecified, then the
sequence of numbers start from zero by default.
stop → Generates numbers up to this value but not including the number itself.
step → indicates the difference between every two consecutive numbers in thesequence. The step
value can be both negative and positive but not zero

Program : Demonstrate for Loop Using range() Function

8. print("Only ''stop'' argument value specified in range function")


9. for i in range(3):
10. print(f"{i}")
11.print("Both ''start'' and ''stop'' argument values specified in range function")
12.for i in range(2, 5):
13. print(f"{i}")
14. print("All three arguments ''start'', ''stop'' and ''step'' specified in range function")
15.for i in range(1, 6, 3):
16. print(f"{i}")
OUTPUT
Only ''stop'' argument value specified in range function
0
1
2
Both ''start'' and ''stop'' argument values specified in range function
2
3
4
All three arguments ''start'', ''stop'' and ''step'' specified in range function
1
4

29.What is the meaning of __name__ == __main__ ?


Before executing the code in the source program, the Python interpreter automatically
definesfew special variables. If the Python interpreter is running the source program as a stand-
alonemain program, it sets the special built-in name variable to have a string value " main ".After
setting up these special variables, the Python interpreter reads the program to executethe code
found in it. All of the code that is at indentation level 0 gets executed. Block ofstate-ments in the
function definition is not executed unless the function is called.

if name == " main ":


statement(s)

The special variable, name with " main ", is the entry point to your program. When Python
interpreter reads the if statement and sees that name does equal to " main ", it will execute the
block of statements present there.
30.Give example of function returning multiple values
Program : Program to Demonstrate the Return of Multiple Values from aFunction Definition
1. def world_war():
2. alliance_world_war = input("Which alliance won World War 2?")
3. world_war_end_year = input("When did World War 2 end?")
4. return alliance_world_war, world_war_end_year
5. def main():
6. alliance, war_end_year = world_war()
7. print(f"The war was won by {alliance} and the war ended in {war_end_year}")
8. if name == " main ":
9. main()

OUTPUT
Which alliance won World War 2?
Allies
When did World War 2 end?
1945
The war was won by Allies and the war ended in 1945

31.What is keyword argument? Give example


• whenever you call a function with some values as its arguments, these values get assigned to the
parameters in the function definition according to their position. In the calling function, you can
explicitly specify the argument name along with their value in the form kwarg = value.
• In the calling function, keyword arguments must follow positional arguments. All the keyword
arguments passed must match one ofthe parameters in the function definition and their order is not
important. No parameter in the function definition may receive a value more than once

Program: Program to Demonstrate the Use of Keyword Arguments

20.def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):


21. print(f"This parrot wouldn't {action}, if you put {voltage}, volts through it.")
22. print(f"Lovely plumage, the {type}")
23. print(f"It's {state} !!!)
24.parrot(1000)
25.parrot(voltage=1000)
26. parrot(voltage=1000000, action='VOOOOOM')
27.parrot('a thousand', state='pushing up the daisies')

32.What is default argument? Give example


In some situations, it might be useful to set a default value to the parameters of the func-
tion definition. This is where default parameters can help. Each default parameter has a default value
as part of its function definition. Any calling function must provide argu- ments for all required
parameters in the function definition but can omit arguments for default parameters. If no argument
is sent for that parameter, the default value is used. Usually, the default parameters are defined at
the end of the parameter list, after any required parameters and non-default parameters cannot
follow default parameters. The default value is evaluated only once.
Program : Program to Demonstrate the Use of Default Parameters
13.def work_area(prompt, domain="Data Analytics"):
14. print(f"{prompt} {domain}")
15.def main():
16. work_area("Sam works in")
17. work_area("Alice has interest in", "Internet of Things")
18.if name == " main ":
19. main()

OUTPUT
Sam works in Data Analytics
Alice has interest in Internet of Things

33.Differentiate *args and **kwargs


In Python, `*args` and `**kwargs` are used to pass a variable number of arguments to a function. They
allow functions to accept an arbitrary number of positional and keyword arguments, respectively.

Here's the difference between `*args` and `**kwargs`:

1. `*args` (Positional Arguments):


- `*args` is used to pass a variable number of positional arguments to a function.
- The `*args` syntax allows you to pass multiple arguments to a function without explicitly defining them in
the function signature.
- The arguments passed using `*args` are treated as a tuple within the function.
- The name `args` is arbitrary; you can use any valid variable name preceded by `*` to collect the positional
arguments.

Example:

```python
def my_function(*args):
for arg in args:
print(arg)

my_function(1, 2, 3) # Output: 1 2 3
my_function('Hello', 'World') # Output: Hello World
```

In this example, the `my_function` accepts any number of positional arguments using `*args`. Inside the
function, the arguments are treated as a tuple, and we can iterate over them or perform any other desired
operations.

2. `**kwargs` (Keyword Arguments):


- `**kwargs` is used to pass a variable number of keyword arguments to a function.
- The `**kwargs` syntax allows you to pass multiple keyword arguments to a function without explicitly
defining them in the function signature.
- The arguments passed using `**kwargs` are treated as a dictionary within the function.
- The name `kwargs` is arbitrary; you can use any valid variable name preceded by `**` to collect the keyword
arguments.

Example:

```python
def my_function(**kwargs):
for key, value in kwargs.items():
print(key, value)

my_function(name='John', age=25) # Output: name John, age 25


my_function(city='London', country='UK') # Output: city London, country UK
```

In this example, the `my_function` accepts any number of keyword arguments using `**kwargs`. Inside the
function, the arguments are treated as a dictionary, and we can iterate over them or access their key-value
pairs for further processing.

Long Answer Questions


1. Explain any five features of Python.
Python provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming, procedural programming
approaches and provides dynamic memory allocation.
1. Easy to Learn and Use: Python is easy to learn as compared to other programming languages. Its
syntax is straightforward and much the same as the English language. There is no use of the
semicolon or curly-bracket, the indentation defines the code block
2. Expressive Language: Python can perform complex tasks using a few lines of code. A simple
example, the helloworld program you simply type print("Hello World"). It will take only one line to
execute,while Java or C takes multiple lines.
3. Interpreted Language: Python is an interpreted language; it means the Python program is
executed one line at atime. The advantage of being interpreted language, it makes debugging easy
andportable.
4. Cross-platform Language: Python can run equally on different platforms such as Windows, Linux,
UNIX, andMacintosh, etc. So, we can say that Python is a portable language. It enables
programmersto develop the software for several competing platforms by writing a program only
once.
5. Free and Open Source: Python is freely available for everyone. It is freely available on its official
website www.python.org. It has a large community across the world that is dedicatedly working
UNIT-1 PYTHON PROGRAMMING 2 towards make new python modules and functions. Anyone can
contribute to the Python community. The open-source means, "Anyone can download its source
code without paying any penny."
6. Object-Oriented Language: Python supports object-oriented language and concepts of classes and
objects come into existence. It supports inheritance, polymorphism, and encapsulation, etc. The
object- oriented procedure helpsto programmer to write reusable code and develop applicationsin
less code.
7. Extensible: It implies that other languages such as C/C++ can be used to compile the code and
thusit can be used further in our Python code. It converts the program into byte code, and
anyplatform can use that byte code.
8. Large Standard Library: It provides a vast range of libraries for the various fields such as machine
learning, web developer, and also for the scripting. There are various machine learning libraries, such
as Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular
framework for Python web development.
9. GUI Programming Support :Graphical User Interface is used for the developing Desktop
application. PyQT5, Tkinter, Kivy are the libraries which are used for developing the web application.
10. Integrated :It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code
line by line like C, C++ Java. It makes easy to debug the code.
11. Embeddable: The code of the other programming language can use in the Python source code.
We canuse Python source code in another programming language as well. It can embed other
language into our code.
12. Dynamic Memory Allocation: In Python, we don't need to specify the data-type of the variable.
When we assign some value to the variable, it automatically allocates the memory to the variable at
run time. Suppose we are assigned integer value 15 to x, then we don't need to write int x =15, Just
write x = 15

2. Explain any five flavors of Python


Flavors of Python simply refers to the different Python compilers. These flavors are usefulto
integrate various programming languages into Python.
Let us look at some of these flavors:
1. CPython: CPython is the Python compiler implemented in C programming language. In this,
Python code is internally converted into the byte code using standard C functions. Additionally, it is
possible to run and execute programs written in C/C++ using CPython compiler.
2. Jython: Earlier known as JPython. Jython is an implementation of the Python programming
language designed to run on the Java platform. Jython is extremely usefulbecause it provides the
productivity features of a mature scripting language while runningon a JVM.
3. PyPy:Thisisthe implementation using Python language. PyPy often runsfaster thanCPython
because PyPy is a just-in-time compiler while CPython is an interpreter.
4. IronPython: IronPython is an open-source implementation of the Python programming language
which is tightly integrated with the .NET Framework.
5. RubyPython:RubyPython is a bridge between the Ruby and Python interpreters. Itembeds a
Python interpreter in the Ruby application’s process using FFI (Foreign FunctionInterface).
6. Pythonxy: Python(x,y) is a free scientific and engineering development software for numerical
computations, data analysis and data visualization based on Python.
7. StacklessPython: Stackless Python is a Python programming language interpreter. In practice,
Stackless Python uses the C stack, but the stack is cleared betweenfunction calls
8. AnacondaPython: Anaconda is a free and open-source distribution of the Python and R
programming languages for scientific computing, that aims to simplify package management and
deployment. Package versions are managed by the package management system conda.

3. Explain various data types in Python.


Data types specify the type of data like numbers and characters to be stored and manipu-
lated within a program. Basic data types of Python are
• Numbers
• Boolean
• Strings
• None
Numbers Integers, floating point numbers and complex numbers fall under Python numbers
category. They are defined as int, float and complex class in Python. Integers can be of any length; it
is only limited by the memory available. A floating point number is accurate upto 15 decimal places.
Integer and floating points are separated by decimal points. 1 is an integer, 1.0 is floating point
number. Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part.
Boolean Booleans may not seem very useful at first, but they are essential when you start
using conditional statements. In fact, since a condition is really just a yes-or-no question, the answer
to that question is a Boolean value, either True or False. The Boolean values, True and False are
treated as reserved words.
Strings A string consists of a sequence of one or more characters, which can include letters,
num-bers, and other types of characters. A string can also contain spaces. You can use single quotes
or double quotes to represent strings and it is also called a string literal. Multiline strings can be
denoted using triple quotes, ''' or """. These are fixed values, not variables that you literally provide
in your script.
For example,
1. >>> s = 'This is single quote string'
2. >>> s = "This is double quote string" None

None is another special data type in Python. None is frequently used to represent the
absence of a value. For example,
1. >>> money = None #None value is assigned to variable money

4. Explain the Arithmetic operators, logical operators and relational operators


with an example.
Arithmetic Operators: Arithmetic operators are used to execute arithmetic operations
such as addition, sub- traction, division, multiplication etc. The following TABLE shows all the
arithmetic operators

Logical Operators :The logical operators are used for comparing or negating the logical
values of their operands and to return the resulting logical value. The values of the operands on
which the logical operators operate evaluate to either True or False. The result of the logical
operatoris always a Boolean value, True or False. TABLE shows all the logical operators.
Relational operators or Comparison Operators: When the values of two operands are
to be compared then comparison operators are used.The output of these comparison operators is
always a Boolean value, either True or False.The operands can be Numbers or Strings or Boolean
values. Strings are compared letter by letter using their ASCII values, thus, “P” is less than “Q”, and
“Aston” is greater than “Asher”. TABLE shows all the comparison operators.

5. Explain the bitwise operators with examples.


Bitwise operators are operators used to perform operations on individual
bits of binary numbers. They manipulate the binary representation of numbers at a bit level.
Bitwise operators work by comparing or manipulating the corresponding bits of two or more
binary numbers.

1. Bitwise AND (&): Performs a bitwise AND operation on two numbers, resulting in a number where
each bit is set to 1 only if both corresponding bits of the operands are 1. Otherwise, the bit is set to
0.
Example:

```python

a = 13 # 1101 in binary

b = 7 # 0111 in binary

result = a & b

print(result) # Output: 5 (0101 in binary)

```

2. Bitwise OR (|): Performs a bitwise OR operation on two numbers, resulting in a number where
each bit is set to 1 if at least one of the corresponding bits of the operands is 1. If both bits are 0, the
resulting bit is set to 0.

Example:

```python

a = 13 # 1101 in binary

b = 7 # 0111 in binary

result = a | b

print(result) # Output: 15 (1111 in binary)

```

3. Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation on two numbers, resulting in a
number where each bit is set to 1 if the corresponding bits of the operands are different (one bit is 1
and the other is 0). If the corresponding bits are the same (both 1 or both 0), the resulting bit is set
to 0.

Example:

```python

a = 13 # 1101 in binary

b = 7 # 0111 in binary

result = a ^ b

print(result) # Output: 10 (1010 in binary)

```

4. Bitwise NOT (~): Performs a bitwise complement operation on a single number, resulting in a
number where each bit is flipped, changing 0 to 1 and 1 to 0.

Example:

```python

a = 13 # 1101 in binary
result = ~a

print(result) # Output: -14 (depending on the number of bits used for representation)

```

5. Left shift (<<): Shifts the bits of a number to the left by a specified number of positions. Zeros are
shifted in from the right side, and the leftmost bits are discarded.

Example:

```python

a = 5 # 0101 in binary

result = a << 2

print(result) # Output: 20 (10100 in binary)

```

6. Right shift (>>): Shifts the bits of a number to the right by a specified number of positions. In
Python, the sign bit (the leftmost bit) is used to fill the new bits when shifting right. For positive
numbers, zeros are shifted in from the left side, and for negative numbers, ones are shifted in.

Example:

```python

a = -10 # 11111111111111111111111111110110 in binary

result = a >> 2

print(result) # Output: -3 (11111111111111111111111111111101 in binary)

```

These are the bitwise operators and their usage in Python. They allow you to perform bit-level
operations on numbers.

6. How to read different types of input from the keyboard. Give examples
In Python, we can read different types of input from the keyboard using various
methods. Here are some examples:

1. Reading a single line of text input:

```python

text = input("Enter some text: ")

print("You entered:", text)

```

2. Reading an integer input:

```python
num = int(input("Enter an integer: "))

print("You entered:", num)

```

3. Reading a floating-point number input:

```python

num = float(input("Enter a number: "))

print("You entered:", num)

```

4. Reading multiple values from a single line:

```python

a, b, c = input("Enter three values separated by spaces: ").split()

print("You entered:", a, b, c)

```

5. Reading a list of integers from a single line:

```python

numbers = list(map(int, input("Enter a list of integers separated by spaces: ").split()))

print("You entered:", numbers)

```

6. Reading a multiline input:

```python

lines = []

print("Enter multiple lines of text (press Enter twice to finish):")

while True:

line = input()

if line:

lines.append(line)

else:

break

print("You entered:")

for line in lines:

print(line)
```

These examples demonstrate different ways to read input from the keyboard in Python, including
single-line input, parsing values, and handling multiple lines of text. Remember to handle exceptions
appropriately, such as when the input cannot be converted to the desired data type.

7. Explain use of string.format and f-string with print() function.


str.format() Method:
• Use str.format() method if you need to insert the value of a variable, expression or an objectinto
another string and display it to the user as a single string.

• The format() method returns a new string with inserted values. The format() method works for all
releases of Python 3.x.

• The format() method uses its arguments to substitute an appropriate value for each formatcode in
the template.

The syntax for format() method is,


str.format(p0, p1, ..., k0=v0, k1=v1, ...)

Program : Program to Demonstrate the Positional Change of Indexes of Arguments


1. a = 10
2. b = 20
3. print("The values of a is {0} and b is {1}".format(a, b))
4. print("The values of b is {1} and a is {0}".format(a, b))

OUTPUT
The values of a is 10 and b is 20The values of b is 20 and a is 10

. f-strings:
• Formatted strings or f-strings were introduced in Python 3.6. A f-string is a string literal thatis
prefixed with “f”.
• These strings may contain replacement fields, which are expressions enclosed within curly braces
{}. The expressions are replaced with their values.
• In the realworld, it means that you need to specify the name of the variable inside the curly braces
to display its value. An f at the beginning of the string tells Python to allow any currently valid
variable names within the string.

Program : Code to Demonstrate the Use of f-strings with print() Function

1. country = input("Which country do you live in?")


2. print(f"I live in {country}")

OUTPUT
Which country do you live in? IndiaI live in India
8. Explain any five type conversion functions with example.
The int() Function To explicitly convert a float number or a string to an integer,
cast the number using int() function.
Program : Program to Demonstrate int() Casting Function
1. float_to_int = int(3.5)
2. string_to_int = int("1") #number treated as string
3. print(f"After Float to Integer Casting the result is {float_to_int}")
4. print(f"After String to Integer Casting the result is {string_to_int}")

The float() Function The float() function returns a floating point number
constructed from a number or string.
Program : Program to Demonstrate float() Casting Function
1. int_to_float = float(4)
2. string_to_float = float("1") #number treated as string
3. print(f"After Integer to Float Casting the result is {int_to_float}")
4. print(f"After String to Float Casting the result is {string_to_float}")

The str() Function The str() function returns a string which is fairly human
readable.
Program : Program to Demonstrate str() Casting Function
1. int_to_string = str(8)
2. float_to_string = str(3.5)
3. print(f"After Integer to String Casting the result is {int_to_string}")
4. print(f"After Float to String Casting the result is {float_to_string}")
The chr() Function Convert an integer to a string of one character whose ASCII
code is same as the integerusing chr() function. The integer value should be in the range of 0–255.
Program : Program to Demonstrate chr() Casting Function
1. ascii_to_char = chr(100)
2. print(f'Equivalent Character for ASCII value of 100 is {ascii_to_char}')
The ord() Function The ord() function returns an integer representing Unicode
code point for the givenUnicode character.
Program : Program to Demonstrate ord() Casting Function
1. unicode_for_integer = ord('4')
2. unicode_for_alphabet = ord("Z")
3. unicode_for_character = ord("#")
4. print(f"Unicode code point for integer value of 4 is {unicode_for_integer}")
5. print(f"Unicode code point for alphabet 'A' is {unicode_for_alphabet}")
6. print(f"Unicode code point for character '$' is {unicode_for_character}")

9. Explain while and for loops with syntax and example


1. While Loop:
The while loop executes a block of code repeatedly as long as a specified condition is true. It
continues iterating until the condition becomes false.
Syntax:
```python
while condition:
# Code block to be executed
```
Example:
```python
count = 0
while count < 5:
print("Count:", count)
count += 1
```
Output:
```
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
```
2. For Loop:
The for loop iterates over a sequence (such as a list, tuple, or string) or any other iterable object.
It executes a block of code for each item in the sequence.
Syntax:
```python
for item in iterable:
# Code block to be executed
```
Example:
```python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("Fruit:", fruit)
```
Output:
```
Fruit: apple
Fruit: banana
Fruit: cherry
```
Another Example:
```python
sentence = "Hello, World!"
for char in sentence:
print("Character:", char)
```
Output:
```
Character: H
Character: e
Character: l
Character: l
Character: o
Character: ,
Character:
Character: W
Character: o
Character: r
Character: l
Character: d
Character: !
```
In addition to iterating over sequences, you can use the `range()` function to generate a sequence
of numbers and iterate over it using a for loop.
Both while and for loops are fundamental constructs in Python for executing repetitive tasks. The
choice between using a while loop or a for loop depends on the specific requirements and the
structure of the data you are iterating over.

10.Explain Exception handling in Python with try…except… finally block


Exception handling in Python allows you to handle and manage errors or
exceptional conditions that may occur during the execution of a program. It helps prevent the
program from crashing and provides a way to gracefully handle errors. The `try`, `except`, and
`finally` blocks are used for exception handling in Python.
1. `try` block: The `try` block is used to enclose the code that might raise an exception. It is followed
by one or more `except` blocks.
2. `except` block: An `except` block is used to catch and handle specific exceptions that may occur
within the corresponding `try` block. Multiple `except` blocks can be used to handle different
exceptions separately.
3. `finally` block: The `finally` block is optional and is used to specify code that should be executed
regardless of whether an exception occurred or not. It is typically used to release resources or
perform cleanup operations.
Syntax:
```python
try:
# Code that might raise an exception
except ExceptionType1:
# Exception handling code for ExceptionType1
except ExceptionType2:
# Exception handling code for ExceptionType2
...
finally:
# Code that will be executed regardless of exceptions
```

Example:
```python
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except ValueError:
print("Invalid input. Please enter valid numbers.")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
finally:
print("Execution complete.")
```
In this example, the `try` block contains code that may raise a `ValueError` if the user inputs non-
numeric values or a `ZeroDivisionError` if the user inputs zero as the second number. If any of these
exceptions occur, the corresponding `except` block is executed. The `finally` block is always executed,
regardless of whether an exception occurred or not.

If the user enters valid numbers and no exceptions are raised, the program will execute the code
within the `try` block, calculate the result, and print it. After that, the `finally` block will be executed
to indicate the completion of execution.

Exception handling allows you to handle and recover from errors gracefully, ensuring that your
program continues to run without abruptly terminating when an exception occurs.

11.Give the syntax of range function. Explain use range function in for loop with
examples.
The syntax of the `range()` function in Python is as follows:
```python
range(start, stop, step)
```
The `range()` function generates a sequence of numbers that can be used in a `for` loop or other
similar scenarios. It takes three parameters:

- `start` (optional): The starting value of the range (inclusive). If not specified, the default value is 0.
- `stop` (required): The ending value of the range (exclusive). This is the value at which the range
stops generating numbers.
- `step` (optional): The increment (or decrement) between each number in the range. If not specified,
the default value is 1.

Now, let's see how the `range()` function can be used in a `for` loop with examples:
Example 1: Generating numbers using `range()` in a `for` loop:
```python
for num in range(5):
print(num)
```
Output:
```
0
1
2
3
4
```
In this example, `range(5)` generates a sequence of numbers from 0 to 4 (exclusive). The `for` loop
iterates over these numbers, and each number is printed.
Example 2: Generating a sequence of even numbers using `range()` in a `for` loop:
```python
for num in range(0, 10, 2):
print(num)
```
Output:
```
0
2
4
6
8
```
In this example, `range(0, 10, 2)` generates a sequence of even numbers from 0 to 8 (inclusive), with
a step of 2. The `for` loop iterates over these numbers, and each number is printed.
Example 3: Generating a sequence of numbers in reverse order using `range()` in a `for` loop:
```python
for num in range(10, 0, -1):
print(num)
```
Output:
```
10
9
8
7
6
5
4
3
2
1
```
In this example, `range(10, 0, -1)` generates a sequence of numbers from 10 to 1 (exclusive) in
reverse order, with a step of -1. The `for` loop iterates over these numbers, and each number is
printed.
The `range()` function is versatile and allows you to generate a range of numbers with different
starting points, ending points, and steps. It is commonly used in `for` loops when you need to iterate
over a specific range of numbers.
12.With syntax and example explain how to define and call a function in Python
In Python, you can define your own functions to encapsulate reusable blocks of code. Functions
allow you to organize your code into logical units and make it more modular. Here's the syntax and
an example of defining and calling a function in Python:
Syntax for defining a function:
```python
def function_name(parameter1, parameter2, ...):
# Code block or statements
# ...
return value
```
Explanation:
- `def` keyword is used to define a function.
- `function_name` is the name you give to your function. Choose a descriptive name that reflects the
purpose of the function.
- `parameter1`, `parameter2`, ... are optional input parameters that the function can accept. You can
have zero or more parameters.
- The code block or statements within the function are indented and contain the logic to be executed
when the function is called.
- `return` statement (optional) is used to specify the value that the function should return. If omitted,
the function returns `None`.

Example:
```python
def greet(name):
message = "Hello, " + name + "! How are you?"
return message
# Calling the function
result = greet("Alice")
print(result)
```
Output:
```
Hello, Alice! How are you?
```
In this example, we define a function named `greet()` that takes a parameter `name`. The function
concatenates the `name` with a greeting message and returns it. We then call the function and store
the result in the `result` variable, which we subsequently print.
Functions can be called multiple times with different arguments, allowing you to reuse the code
within the function block. You can define and use functions to structure your code, promote code
reusability, and improve overall maintainability and readability.

13.Explain *args and **kwargs with example


In Python, `*args` and `**kwargs` are used to pass a variable number of arguments to a function. They allow
functions to accept an arbitrary number of positional and keyword arguments, respectively.

Here's the difference between `*args` and `**kwargs`:

1. `*args` (Positional Arguments):


- `*args` is used to pass a variable number of positional arguments to a function.
- The `*args` syntax allows you to pass multiple arguments to a function without explicitly defining them in
the function signature.
- The arguments passed using `*args` are treated as a tuple within the function.
- The name `args` is arbitrary; you can use any valid variable name preceded by `*` to collect the positional
arguments.

Example:

```python
def my_function(*args):
for arg in args:
print(arg)

my_function(1, 2, 3) # Output: 1 2 3
my_function('Hello', 'World') # Output: Hello World
```

In this example, the `my_function` accepts any number of positional arguments using `*args`. Inside the
function, the arguments are treated as a tuple, and we can iterate over them or perform any other desired
operations.

2. `**kwargs` (Keyword Arguments):


- `**kwargs` is used to pass a variable number of keyword arguments to a function.
- The `**kwargs` syntax allows you to pass multiple keyword arguments to a function without explicitly
defining them in the function signature.
- The arguments passed using `**kwargs` are treated as a dictionary within the function.
- The name `kwargs` is arbitrary; you can use any valid variable name preceded by `**` to collect the keyword
arguments.

Example:

```python
def my_function(**kwargs):
for key, value in kwargs.items():
print(key, value)
my_function(name='John', age=25) # Output: name John, age 25
my_function(city='London', country='UK') # Output: city London, country UK
```

In this example, the `my_function` accepts any number of keyword arguments using `**kwargs`. Inside the
function, the arguments are treated as a dictionary, and we can iterate over them or access their key-value
pairs for further processing.

14.With example explain keyword arguments and default arguments to the function
keyword arguments:
• whenever you call a function with some values as its arguments, these values get assigned to the
parameters in the function definition according to their position. In the calling function, you can
explicitly specify the argument name along with their value in the form kwarg = value.
• In the calling function, keyword arguments must follow positional arguments. All the keyword
arguments passed must match one ofthe parameters in the function definition and their order is not
important. No parameter in the function definition may receive a value more than once

Program: Program to Demonstrate the Use of Keyword Arguments

20.def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):


21. print(f"This parrot wouldn't {action}, if you put {voltage}, volts through it.")
22. print(f"Lovely plumage, the {type}")
23. print(f"It's {state} !!!)
24.parrot(1000)
25.parrot(voltage=1000)
26. parrot(voltage=1000000, action='VOOOOOM')
27.parrot('a thousand', state='pushing up the daisies')

default arguments:
In some situations, it might be useful to set a default value to the parameters of the func- tion
definition. This is where default parameters can help. Each default parameter has a default value as
part of its function definition. Any calling function must provide argu- ments for all required
parameters in the function definition but can omit arguments for default parameters. If no argument
is sent for that parameter, the default value is used. Usually, the default parameters are defined at
the end of the parameter list, after any required parameters and non-default parameters cannot
follow default parameters. The default value is evaluated only once.

Program : Program to Demonstrate the Use of Default Parameters


13.def work_area(prompt, domain="Data Analytics"):
14. print(f"{prompt} {domain}")
15.def main():
16. work_area("Sam works in")
17. work_area("Alice has interest in", "Internet of Things")
18.if name == " main ":
19. main()

OUTPUT
Sam works in Data Analytics
Alice has interest in Internet of Things
15.With example explain how command line arguments are passed to python
program
In Python, command-line arguments can be passed to a program by using the `sys` module or the
`argparse` module. Here's an example of how command-line arguments can be passed to a Python
program using the `sys` module:

```python
import sys

# Accessing command-line arguments


arguments = sys.argv

# Printing the command-line arguments


print("Command-line arguments:", arguments)
```

When you run the above script from the command line and provide arguments, they will be stored in
the `sys.argv` list. The first element of the list, `sys.argv[0]`, contains the name of the script itself, and
the subsequent elements contain the command-line arguments.

For example, if you save the script as `script.py` and run it with the following command:

```
python script.py argument1 argument2 argument3
```

The output will be:


```
Command-line arguments: ['script.py', 'argument1', 'argument2', 'argument3']
```
You can access and process these command-line arguments as needed within your Python program.

16.Write a program to check for ‘ValueError’ exception


try:
number = int(input("Enter a number: "))
print("You entered:", number)
except ValueError:
print("Invalid input. Please enter a valid integer.")

output:
1.
Enter a number: 42
You entered: 42
2.
Enter a number: abc
Invalid input. Please enter a valid integer.

17.Write a program to check for ZeroDivisionError Exception


try:
dividend = int(input("Enter the dividend: "))
divisor = int(input("Enter the divisor: "))
result = dividend / divisor
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")

Output:
1. Enter the dividend: 10
Enter the divisor: 2
Result: 5.0
2. Enter the dividend: 10
Enter the divisor: 0
Error: Division by zero is not allowed.

18.How to return multiple values from a function definition? Explain with an


example
In Python, you can return multiple values from a function definition by utilizing tuples,
lists, or other data structures that can hold multiple elements. Here's an example that
demonstrates how to return multiple values from a function:

def calculate_circle(radius):
area = 3.14159 * radius**2
circumference = 2 * 3.14159 * radius
return area, circumference

# Calling the function and unpacking the returned values


circle_area, circle_circumference = calculate_circle(5)

# Printing the returned values


print("Circle Area:", circle_area)
print("Circle Circumference:", circle_circumference)

In this example, the `calculate_circle()` function takes a radius as an input parameter. It


calculates the area and circumference of a circle based on the given radius. Instead of
returning a single value, it returns both the area and circumference as a tuple.
When the function is called, the returned values are assigned to the variables `circle_area`
and `circle_circumference` by unpacking the tuple. The variables can then be used
independently to display the calculated values.

Output:
Circle Area: 78.53975
Circle Circumference: 31.4159
By returning multiple values from a function, you can efficiently package and utilize
related information without the need for separate functions or complex data structures.

You might also like