0% found this document useful (0 votes)
2 views17 pages

Unit 1 Python

The document provides an overview of various Python programming concepts, including comments, the Python Virtual Machine, data types, and operators. It explains how to write comments, execute Python programs, and the significance of indentation and variable naming. Additionally, it covers features of Python, its flavors, type conversion functions, and string formatting methods.

Uploaded by

pujarinidhi3
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)
2 views17 pages

Unit 1 Python

The document provides an overview of various Python programming concepts, including comments, the Python Virtual Machine, data types, and operators. It explains how to write comments, execute Python programs, and the significance of indentation and variable naming. Additionally, it covers features of Python, its flavors, type conversion functions, and string formatting methods.

Uploaded by

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

2m:

1.How to write a comment line in Python? Mention two types.

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

Single-line comment: A single-line comment in Python is denoted by a hash (#) symbol.

Eg: #This is single line Python comment

Multi-line comment: A multi-line comment in Python can be written using triple quotes (""" or ''').

Eg: '''This is multiline

comment in Python

using triple quotes'''

2.What is Python Virtual Machine?


The Python Virtual Machine (PVM) is a program that executes Python bytecode. Bytecode is a
simplified form of Python code that is generated by the Python compiler. The PVM converts
bytecode into machine code, which is then executed by the computer's processor.

3. List any four flavors of Python.

Cpython,jython,pypy,pythonxy,ironpython, Anaconda Python, RubyPython.


4.Give 2 step process of Python program execution
Compilation: The Python interpreter first compiles the Python code into bytecode.
Bytecode is a simplified form of Python code that is executed by the Python Virtual
Machine (PVM).
Interpretation: The PVM then interprets the bytecode and executes the Python
program. The PVM keeps track of the program's state, including the values of
variables, the call stack, and the execution flow.
5. List any four standard datatypes supported by Python.
• Numbers • Boolean • Strings • None
6. How to determine the data type of a variable? Give the syntax and example
In Python, you can determine the data type of a variable using the type() function.
The type() function takes an object as its argument and returns the data type of that
object.
Syntax: type(object)
Eg: . >>> type(1)
<class 'int'>
7. What is the purpose of membership operators? Give example
membership operators are used to test whether a value or variable exists in a
sequence (string, list, tuples, sets, dictionary) or not. They return a Boolean value, True
or False, based on the membership condition. Python provides two membership operators:

1. in operator: It returns True if a value is found in the specified sequence or


collection; otherwise, it returns False.
2. not in operator: It returns True if a value is not found in the specified
sequence or collection; otherwise, it returns False.
Eg: fruits = ["apple", "banana", "orange", "mango"]
print("banana" in fruits) # Output: True
print("grape" in fruits) # Output: False
print("kiwi" not in fruits) # Output: True
print("orange" not in fruits) # Output: False

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


The input() function reads a line of text entered by the user through the keyboard
and returns it as a string.
Syntax: variable_name = input([prompt])
Eg: num=input("hello world")
print(num)

9. List four type conversion functions.


 int(): Converts a string or a floating-point number to an integer.
 float(): Converts a string or an integer to a floating-point number.
 str(): Converts a s a list, a tuple, a set, or a dictionary to a string.
 chr():Convert an integer to a string of one character whose ASCII code is same as the integer
using 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?
indentation is the use of whitespace to indicate a block of code. Indentation is
required in Python because it is used to group statements together and to indicate
the logical structure of the code. This principle makes the code look cleaner and
easier to understand and read.
12.Give syntax of if ..elif statement in Python
if Boolean_Expression_1:
statement_1
elif Boolean_Expression_2:
statement_2
else:
statement_last
13.What is the purpose of else suit in Python loops? Give example
The purpose of the else suite in Python loops is to associate a block of code with the
loop, which should be executed when the loop condition becomes false or when all
iterations of the loop have been completed.
Eg: for i in range(1, 11):
if i == 5:
break
else:
print(i)# output 1 2 3 4
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 (_).
• 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.
Eg: my_variable = 42
name = "John"
16.What are python keywords? Give example
Keywords are a list of reserved words that have predefined meaning
Eg:if,else,elif,True,False
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.
18.What are the rules for naming variables?
Refer 14 2mark
19.Give syntax and example for assigning values to variables
Syntax: variable_name = expression
Eg: number=200
20.Give the syntax and example for str.format() method
Syntax: str.format(p0, p1, ..., k0=v0, k1=v1, ...)
Eg: . a = 10
b = 20
print("The values of a is {0} and b is {1}".format(a, b))
21.What is f-string literal? Give an example
A f-string is a string literal that is prefixed with “f”. These strings may contain
replacement fields, which are expressions enclosed within curly braces {}. The
expressions are replaced with their values.

Eg: country = input("Which country do you live in?")

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

22.What are syntax errors? Give example


syntax errors occur when the code violates the rules and structure of the programming
language's syntax.
Eg:print(“hello
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. 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()

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.
Syntax: range([start ,] stop [, step])
Eg: for num in range(10):

print(num)

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


the expression __name__ == '__main__' is commonly used to check whether a script is
being executed directly as the main program or if it is being imported as a module.
Eg:
def main():

print("This is the main program.")


if __name__ == '__main__':
main()
30.Give example of function returning multiple values.
a function can return multiple values by using a tuple or any other iterable data structure.
Eg: def calculate_area_and_perimeter(width, height):

area = width * height


perimeter = 2 * (width + height)
return area, perimeter
area, perimeter = calculate_area_and_perimeter(10, 20)
print("The area is", area)

print("The perimeter is", perimeter)


31.What is keyword argument? Give example
Keyword arguments are values that are passed to a function by name. Keyword arguments
are often used to make code more readable and concise.
Eg: def greet(name, age):
print("Hello", name)
print("You are", age, "years old.")

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.

5. Explain the bitwise operators with examples.


Bitwise operators treat their operands as a sequence of bits (zeroes and ones) and
perform bit by bit operation.

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.

Eg: for num in range(10):

print(num) #0 to 9

eg: for num in range(0, 10, 2):

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.

Syntax:def function_name(parameter1, parameter2, ...):

# Code block

Eg: def greet(name):

print(f"Hello, {name}!")

def add_numbers(num1, num2):

return num1 + num2


Calling a function: To call a function in Python, you simply write the function name followed by
parentheses. If the function has parameters, you pass the appropriate values inside the parentheses.

Syntax: function_name(argument1, argument2, ...)

Eg: greet("Alice")

result = add_numbers(3, 5)

print(result)

output:Hello, Alice!

13.Explain *args and **kwargs with example

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.

Eg: def print_args(*args):

for arg in args:

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

for key, value in kwargs.items():

print("{}:{}".format(key,value))

print_kwargs(name="star", age=25, city="udupi")

# output name: star

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

def greet(name, age):

print(f"Hello {name}! You are {age} years old.")

if len(sys.argv) != 3:

print("Usage: python example.py <name> <age>")

else:

name = sys.argv[1]

age = sys.argv[2]

greet(name, age)

python example.py Alice 25

output: Hello Alice! You are 25 years old.

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

try:

number = int(input("Enter a number: "))

print("The number entered is:", number)

except ValueError:

print("Error: Invalid input. Please enter a valid number.")

output: Enter a number: ABC

Error: Invalid input. Please enter a valid number.

17.Write a program to check for ZeroDivisionError Exception

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

Enter another number: 0


Error: Division by zero is not allowed.

Exception handling completed.

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.

Eg:refer 2mark 30th

You might also like