Python Unit1 Solved Questions
Python Unit1 Solved Questions
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
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.
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
• 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.
• 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
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.
Eg:
if 'apple' in fruits:
variable_name = input([prompt])
prompt is a string written inside the parenthesis that is printed on the screen.
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
Eg:
name = "John" # Variable identifier
def calculate_area(self):
return 3.14 * self.radius ** 2
OUTPUT
The values of a is 10 and b is 20The values of b is 20 and a is 10
OUTPUT
Which country do you live in? IndiaI live in India
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
OUTPUT
Sam works in Data Analytics
Alice has interest in Internet of Things
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.
Example:
```python
def my_function(**kwargs):
for key, value in kwargs.items():
print(key, value)
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.
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
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.
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
```
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
```
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
```
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
```
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
result = a >> 2
```
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:
```python
```
```python
num = int(input("Enter an integer: "))
```
```python
```
```python
print("You entered:", a, b, c)
```
```python
```
```python
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
print("You entered:")
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.
• 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.
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.
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}")
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.
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.
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
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.
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
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
```
output:
1.
Enter a number: 42
You entered: 42
2.
Enter a number: abc
Invalid input. Please enter a valid integer.
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.
def calculate_circle(radius):
area = 3.14159 * radius**2
circumference = 2 * 3.14159 * radius
return area, circumference
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.