Unit 1 Python
Unit 1 Python
. A comment is a text that describes what the program or a particular part of the program is trying to
do and is ignored by the Python interpreter.
Multi-line comment: A multi-line comment in Python can be written using triple quotes (""" or ''').
comment in Python
An exception is an unwanted event that interrupts the normal flow of the program. When an
exception occurs in the program, execution gets terminated. Errors detected during
execution are called exceptions.
Eg: '2' + 2
24.What is use of finally statement ?
The finally statement in Python is used to execute a block of code regardless of whether an
exception is raised or not. This can be useful to close files, free up resources, or perform
other cleanup tasks.
The finally statement is always executed, even if an exception is raised in the try or except
block. This means that the finally block will always be executed, even if the exception is not
handled.
25.Differentiate scope and life time of a variable.
Scope refers to the region of the program where a variable is defined and can be accessed. It
defines the visibility or accessibility of a variable. The scope of a variable determines where
the variable can be referenced and used within the program.
The lifetime of a variable refers to the period during which the variable exists in memory and
retains its value. It is the duration or lifetime of the storage allocated to hold the variable's
value.
26.List any four built in functions in Python
Abs(),min(),max(),len(),pow()
print(num)
greet(name="Alice", age=25)
output:Hello Alice
You are 25 years old.
32.What is default argument? Give example
A default argument is an argument to a function that can be omitted when the function is
called. The default value for the argument is specified in the function definition.
Eg: def greet(name, message="Hello"):
print(message, name, "!")
greet("Alice")
greet("Bob", "Hi")
output: Hello Alice !
Hi Bob !
33.Differentiate *args and **kwargs
*args is used to pass a variable number of positional arguments to a function. The
arguments are stored in a tuple.
**kwargs is used to pass a variable number of keyword arguments to a function. The
arguments are stored in a dictionary.
4m:
1.Explain any five features of Python.
1.Simple
a. More clarity and less stress on understanding the syntax of the
language developing and understanding programs will be easy
2. Easy to Learn
a. Use very few keywords
b. Programs use simple structure
c. Developing programs in python is easy
3. Open Source
a. No need to pay for python software
b. Can be downloaded from www.python.org
c. Its source code can be read, modified can be used by the
programmers as desired
4. High Level Language
a. Low level languages use machine instruction to develop programs.
These instructions directly interact with the CPU
b. Machine language and assembly language are low level languages
c. English like languages where there is no gap between human
speaking languages and high level languages
5. Potable
a. When a program yields same result on any computer in the world ,
then it is called a portable program
6. Huge Library:
a. python has a big day library which can be used on any OS like UNIX,
Windows or Mcintosh.
b. Programmers can develop programs very easily using the modules
available in the python library
7. Scalable
a. A program would be scalable if it could be moved to another OS or
hardware and take full advantage of the new environment in terms of
performance
b. Python programs are scalable since they can run on any platform and
use the features of the new platform effectively
8. Procedure and Oriented
a. Python as Procedure Oriented and Object Oriented Programming
language
b. Object Oriented Programming like: Java
c. Procedure Oriented Programming: C
2. Explain any five flavors of Python
CPython:
This is the standard Python compiler implemented in C language.
In this, any Python program is internally converted into byte code using C
language functions. This byte code is run on the interpreter available in
Python Virtual Machine (PVM) created in C language.
The advantage is that it is possible to execute C and C++ functions and
programs in CPython
Jython:
which is designed to run on Java platform.
Jython compiler first compiles the Python program into Java byte code.
This byte code is executed by Java Virtual Machine (JVM) to produce the
output.
Jython contains libraries which are useful for both Python and Java
programmers.
IronPython:
This is another implementation of Python language for .NET framework.
This is written in C# (C Sharp) language.
This flavor of Python gives flexibility of using both the .NET and Python
libraries.
PyPy:
PyPy is written in a language called RPython which was created in Python
language.
RPython is suitable for creating language interpreters.
PyPy programs run very fast since there is a JIT (Just In Time) compiler
added to the PVM.
RubyPython:
This is a bridge between the Ruby and Python interpreters.
It encloses a Python interpreter inside Ruby applications.
StacklessPython:
Small tasks which should run individually are called tasklets.
Tasklets run independently on CPU and can communicate with others via
channels.
3. Explain various data types in Python.
Number: represents the data that has a numeric value. A numeric value can be an
integer, a floating number, or even a complex number.
>Integers can be of any length
>float number is accurate up to 15 decimal places.
>Complex numbers are written in the form, x + yj, where x is the real part and y is
the imaginary part.
Eg:
a=5
print("Type of a: ", type(a)) # Type of a: <class 'int'>
b = 5.0
print("\nType of b: ", type(b)) # Type of b: <class 'float'>
c = 2 + 4j
print("\nType of c: ", type(c)) # Type of c: <class 'complex'>
Boolean : These data types are used to store Boolean values, which can be either
True or False.
Eg: b = True
String: consists of a sequence of one or more characters, which can include letters,
numbers, and other types of characters.
Eg: s = "Hello, world!"
None: is frequently used to represent the absence of a value.
Example: money = None
4. Explain the Arithmetic operators, logical operators and relational operators
with an example.
Relational operator: When the values of two operands are to be compared then
relational operators are used.
6. How to read different types of input from the keyboard. Give examples
In Python, the input() function is used to read user input from the keyboard. By
default, input() reads the input as a string. To read input as other data types like
integers or floats, you can use type conversion functions (int() and float()) to convert
the input accordingly.
Eg: name = input("Enter your name: ") #string
age = int(input("Enter your age: ")) #int
price = float(input("Enter the price: ")) float
7. Explain use of string.format and f-string with print() function.
String formatting is a way to insert variables, expressions, and other values into a
string.
string.format(): This is the older method of string formatting. It uses a format
string that contains special formatting codes. For example, the following code
uses string.format() to print a string with the name of the user and their age:
eg: name = "Bard"
age = 25
print("Hello, my name is {} and I am {} years old.".format(name, age))
f-strings: This is the newer method of string formatting. It uses f-strings, which
are formatted string literals that are enclosed in parentheses and start with the
letter f. For example, the following code uses f-strings to print a string with the
name of the user and their age:
eg: name = "Bard"
age = 25
print(f"Hello, my name is {name} and I am {age} years old.")
8. Explain any five type conversion functions with example
int(): This function converts a string, floating-point number, or other object to an
integer
eg: num = "10"
num = int(num)
print(num) # Output: 10
float(): This function converts a string, integer, or other object to a floating-point
number eg:
num_str = "3.14"
num_float = float(num_str)
print(num_float) # Output: 3.14
str(): This function converts an object to a string. Eg:
num_int = 42
num_str = str(num_int)
print(num_str) # Output: "42"
chr():Convert an integer to a string of one character whose ASCII code is same as
the integer using chr() function. Eg:
char = chr(100)
print('Character for ASCII value of 100 is {}'.format(char)) #d
hex():Convert an integer number (of any size) to a lowercase hexadecimal string
prefixed with “0x” using hex() function. Eg:
inttohex = hex(100)
print("After Integer to Hex Casting the result is {}".format(inttohex)) #0x64
oct():Convert an integer number (of any size) to an octal string prefixed with “0o”
using oct() function.
int_to_oct = oct(100)
print("After Integer to Hex Casting the result is {}".format(int_to_oct )) #0o144
9. Explain while and for loops with syntax and example.
The while loop repeatedly executes a block of code as long as a specified condition
is true .pretested loop
Syntax: while Boolean_Expression:
statement(s)
eg: i = 1
while i <= 10:
print(i)
i += 1 # 1 to 10
for loop: The for loop iterates over a sequence (such as a list, string, or range) and
executes a block of code for each item in the sequence.
Syntax: for iteration_variable in sequence:
statement(s)
eg: for item in ["hello", "world", "python"]:
print(item)
10.Explain Exception handling in Python with try…except… finally block
Exception handling is a way to deal with errors that occur during the execution of a
Python program. It allows you to gracefully handle errors so that your program does
not crash.
In Python, exception handling is done using the try...except...finally block. The try
block contains the code that you want to execute. The except block contains the
code that you want to execute if an error occurs in the try block. The finally block
contains the code that you want to execute regardless of whether or not an error
occurs in the try block.
try:
statement_1
except Exception_Name_1:
statement_2
.
.
else:
statement_3
finally:
statement_4
eg: try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print(f"The result is: {result}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
finally:
print("Exception handling completed.")
11.Give the syntax of range function. Explain use range function in for loop
with examples.
The range() function in Python is used to generate a sequence of numbers
Syntax: range([start ,] stop [, step])
start → value indicates the beginning of the sequence. If the start argument is not specified, 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 the sequence. The step
value can be both negative and positive but not zero.
print(num) #0 to 9
print(num) #0 2 4 6 8
12.With syntax and example explain how to define and call a function in Python
Defining a function: To define a function in Python, you use the def keyword, followed by the
function name and parentheses. Any parameters that the function accepts are specified within the
parentheses.
# Code block
print(f"Hello, {name}!")
Eg: greet("Alice")
result = add_numbers(3, 5)
print(result)
output:Hello, Alice!
In Python, *args and **kwargs are special keywords that can be used to pass a variable number of
arguments to a function.
*args is a special parameter that can be used to pass a variable number of positional arguments to
a function. The arguments are stored in a tuple.
print(arg)
print_args(1, 2, 3) #1,2,3
**kwargs is a special parameter that can be used to pass a variable number of keyword arguments
to a function. The keyword arguments are stored in a dictionary
Eg def print_kwargs(**kwargs):
print("{}:{}".format(key,value))
age: 25
city: Udupi
14.With example explain keyword arguments and default arguments to the function.
31 and 32 of 2mark
15.With example explain how command line arguments are passed to python program.
Command line arguments are parameters that are passed to a Python program when it is executed
from the command line. They are useful for controlling the behavior of the program.
In Python, command line arguments are stored in the sys.argv variable. The sys.argv variable is a list
of strings, where each string represents a command line argument.
Eg: import sys
if len(sys.argv) != 3:
else:
name = sys.argv[1]
age = sys.argv[2]
greet(name, age)
try:
except ValueError:
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print(f"The result is: {result}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
finally:
print("Exception handling completed.")
output: Enter a number: 1
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 simply separating them with
commas in the return statement. In Python, you can return multiple values from a function by using
tuples, lists, or other data structures. These data structures allow you to bundle multiple values
together and return them as a single entity.