0% found this document useful (0 votes)
176 views30 pages

Ques Python

Here are the key differences between object-oriented programming (OOP) and procedural programming: 1. Encapsulation: - OOP supports encapsulation which binds together the data and functions that manipulate the data, and keeps both safe from outside interference and misuse. - Procedural programming does not have the concept of encapsulation. Data and functions are independent. 2. Data abstraction: - OOP supports data abstraction which allows defining the data in terms of its essential characteristics without regard to implementation details. - Procedural programming does not support data abstraction. 3. Inheritance: - OOP supports inheritance which allows properties to be inherited from a parent class to a child class. -

Uploaded by

rs7586792
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
176 views30 pages

Ques Python

Here are the key differences between object-oriented programming (OOP) and procedural programming: 1. Encapsulation: - OOP supports encapsulation which binds together the data and functions that manipulate the data, and keeps both safe from outside interference and misuse. - Procedural programming does not have the concept of encapsulation. Data and functions are independent. 2. Data abstraction: - OOP supports data abstraction which allows defining the data in terms of its essential characteristics without regard to implementation details. - Procedural programming does not support data abstraction. 3. Inheritance: - OOP supports inheritance which allows properties to be inherited from a parent class to a child class. -

Uploaded by

rs7586792
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 30

Q.

1 Python is which type language


a) Object Oriented b) Procedure oriented
c) Schema Oriented d) None of the above
Ans: a
Q.2 How to create a variable in Python with value 34?
a) int a=34 b) a =34
c) integer a = 34 d) None
Ans: b
Q.3 How to add a multi-line comment in Python
a) /*This is comment b) !! This is comment
c) // This is comment d) '''This is comment'''
Ans: d
Q.4 How to access a value in tuple?
a) mytuple =() b) mytuple =(0)
c) mytuple = 0 d) mytuple =
Ans: b
Q.5 How to access a value in List?
a) Mylist (1) b) mylist [1]
c) mylist {1} d) None of the above
Ans: b
Q.6 Name of the operators which operate on bits
a) Bitwise Operators b) Exponentiation Operator
c) Identity Operator d) Membership Operators
Ans: a
Q.7 Name the thing which is not a core data type
a) List b) Tuples
c) Dictionary d) class
Ans: d
Q.8 The extension of a Python module is______
a) .py b) .mod
c) .pyy d) None of the above
Ans a
Q.9 How to align a string centrally in Python?
a) align () method b) center () method
c) fill () method d) None of the above
Ans: b
Q.10 The developer of Python is________
a) Denis Ritchie b) Guido Van Rossum
c) Peter Norton d) John Backus
Ans: b
Q.11 The extension of a Python Script File is
a) .py b) .pyy c) .pie d) none these
Ans: a
Q.12 The following is an example of an invalid variable?
a) xyz_1 b) 1st c) foo d) _qwe
Ans: d
Q.13 A variable in Python with value 42.6
a) int a = 42.6 b) a = 42.6 c) integer a = 42.6 d) None
Ans: b
Q.14 How to add a single-line comment in Python?
a) /*This is comment*/ b) !! This is comment
c) // This is comment d) # This is comment
Ans: d
Q.15 How to correctly create a function in python?
a) demoFunction() b) def demoFunction()
c) function demoFunction() d) void demoFunction()
Ans: b
Q.16 How to access a value in Tuple?
a) mytuple (1) b) mytuple [1]
c) mytuple {1} d) None of the above
Ans:a
Q.17 Name the operator used in Python to raise numbers
to the power?
a) Bitwise Operators b) Exponentiation Operator
c) Identify Operator d) Membership Operators
Ans: b
Q.18 Name the statement which is used to import all the
functionally of one module into another.
a) import b) asset c) try d) Exception
Ans: a
Q.19 Name the thing which represents a key-value pair
in Python?
a) Tuples b) Lists c) Dictionary d) all of the above
Ans:c
Q.20 Name the thing which does not allow duplicate values
a) Set b) lists c) Tuples d) None of the above
Ans: a
Q.21 The words having a special meaning in Python are
known as_________
Ans: keyword
Q.22 Python is a case sensitive language. (True/False)
Ans: True
Q.23 The function which converts all characters of a
string to lowercase is________
Ans: tolower()
Q.24 List allows duplicate values. (True/False)
Ans: true
Q.25 The Data type which is used to implement the keyvalue pair in Python.
Ans: dictionary
Q.26 The keyword which is used to define a function.
Ans: def
Q.27 The module that contains trigonometric and logarithmetic functions is
Ans: math module
Q.28 Name the error that occurs when a number is divided by zero.
Ans: ArithmeticError
Q.29 OOPS stands for___________
Ans:Object oriented programming system
Q.30 Name the operator that is used to compare two operands and check them for equality?
Ans: equal operator(==)
Q.31 What is a compiler?
Ans: A compiler is a program that translates a programming language's source code into machine code.
Q.32 What are environment variables?
An environment variable is a dynamic-named value that can affect the way running processes will behave on a
computer
Q.33 What is the Sys Module?
The sys module in Python provides various functions and variables that are used to manipulate different parts of the
Python runtime environment
Q.34 Indentation is compulsory in Python. (T/F)
Ans: True
Q.35 Can we make multiple comments
Ans: Yes
Q.36 What is the extension of a Python program file?
Ans: .py
Q.37 Give an example of an arithmetic exception.
Ans: division by zero
Q.38 == is ________ operator
Ans: equal operator
Q.39% method is used for ________.
Ans:Modulus: returns the remainder when the first operand is divided by the second
Q.40Python Language was developed by...............
Ans:Guido van Rossum
Q.41 Give the purpose of input function
Ans: Python input() function is used to take user input.
Q.42 The return keyword is used in Python for..............
Ans:The return keyword is to exit a function and return a value.
Q43 Python Tuples are faster than lists?(True/False)
Ans:True
Q.44 The elements of a list can be accessed by using which operator.
Ans Index operator[]
Q.45 The variables declared outside of a function have scope.
Ans: Global scope
Q.46 Name the module in Python which supports regular expression?
Ans:"re" module
Q.47 Write the character which is used for searching from the end.
Ans: $
Q.48Write the statement for opening a file c:/scores.txt for reading?
Ans:fileptr=open(“c:/scores.txt”,’”r”)
Long Answer type questions

Q Explain the various types of parameters passing in


Python.

Types of arguments
There may be several types of arguments which can be passed at the time of function call.
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments

Required Arguments
As far as the required arguments are concerned, these are the arguments which are required to be passed at the
time of function calling with the exact match of their positions in the function call and function definition. Consider
the following example.

Example 1

1. def func(name):
2. message = "Hi "+name
3. return message
4. name = input("Enter the name:")
5. print(func(name))

Output:

Enter the name: John


Hi John

Keyword arguments(**kwargs)
Python allows us to call the function with the keyword arguments. This kind of function call will enable us to pass the
arguments in the random order.

The name of the arguments is treated as the keywords and matched in the function calling and definition. If the
same match is found, the values of the arguments are copied in the function definition.

Consider the following example.

Example 1

1. #function func is called with the name and message as the keyword arguments
2. def func(name,message):
3. print("printing the message with",name,"and ",message)
4.
5. #name and message is copied with the values John and hello respectively
6. func(name = "John",message="hello")

Output:

printing the message with John and hello

Default Arguments
Python allows us to initialize the arguments at the function definition. If the value of any of the arguments is not
provided at the time of function call, then that argument can be initialized with the value given in the definition even
if the argument is not specified at the function call.

Example 1

1. def printme(name,age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john")

Output:

My name is John and age is 22

Variable-length Arguments (*args)


In large projects, sometimes we may not know the number of arguments to be passed in advance. In such cases,
Python provides us the flexibility to offer the comma-separated values which are internally treated as tuples at the
function call. By using the variable-length arguments, we can pass any number of arguments.

However, at the function definition, we define the variable-length argument using the *args (star) as *<variable -
name >.

Consider the following example.

Example

1. def printme(*names):
2. print("type of passed argument is ",type(names))
3. print("printing the passed arguments...")
4. for name in names:
5. print(name)
6. printme("john","David","smith","nick")

Output:

type of passed argument is <class 'tuple'>


printing the passed arguments...
john
David
smith
nick

In the above code, we passed *names as variable-length argument. We called the function and passed values
which are treated as tuple internally. The tuple is an iterable sequence the same as the list. To print the given
values, we iterated *arg names using for loop.

Q. What do you mean by scope of variable.Explain.


The scopes of the variables depend upon the location where the variable is being declared. The variable declared in
one part of the program may not be accessible to the other parts.

In python, the variables are defined with the two types of scopes.

1. Global variables
2. Local variables

The variable defined outside any function is known to have a global scope, whereas the variable defined inside a
function is known to have a local scope.

Consider the following example.

Example 1 Local Variable


1. def print_message():
2. message = "hello !! I am going to print a message." # the variable message is local to the function itself
3. print(message)
4. print_message()
5. print(message) # this will cause an error since a local variable cannot be accessible here.

Output:

hello !! I am going to print a message.


File "/root/PycharmProjects/PythonTest/Test1.py", line 5, in
print(message)
NameError: name 'message' is not defined

Example 2 Global Variable

1. def calculate(*args):
2. sum=0
3. for arg in args:
4. sum = sum +arg
5. print("The sum is",sum)
6. sum=0
7. calculate(10,20,30) #60 will be printed as the sum
8. print("Value of sum outside the function:",sum) # 0 will be printed Output:

Output:

The sum is 60
Value of sum outside the function: 0

Q Difference between Object-oriented vs Procedure-


oriented Programming languages

Index Object-oriented Programming Procedural Programming

1. Object-oriented programming is the Procedural programming uses a


problem-solving approach and used list of instructions to do
where computation is done by using computation step by step.
objects.

2. It makes the development and In procedural programming, It is


maintenance easier. not easy to maintain the codes
when the project becomes
lengthy.

3. It simulates the real world entity. So real- It doesn't simulate the real
world problems can be easily solved world. It works on step by step
through oops. instructions divided into small
parts called functions.

4. It provides data hiding. So it is more Procedural language doesn't


secure than procedural languages. You provide any proper way for data
cannot access private data from binding, so it is less secure.
anywhere.

5. Example of object-oriented programming Example of procedural


languages is C++, Java, .Net, Python, languages are: C, Fortran,
C#, etc. Pascal, VB etc.

Q Describe inheritance and explain the various typesof


python inheritance with the help of suitable example.
In inheritance, the child class acquires the properties and can access all the data members and
functions defined in the parent class. A child class can also provide its specific implementation to
the functions of the parent class.

Single inheritance

Example 1

1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. d = Dog()
9. d.bark()
10. d.speak()

Output:

dog barking
Animal Speaking

Python Multi-Level inheritance


Multi-Level inheritance is possible in python like other object-oriented languages. Multi-level
inheritance is archived when a derived class inherits another derived class. There is no limit on the
number of levels up to which, the multi-level inheritance is archived in python.

Example
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #The child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. #The child class Dogchild inherits another child class Dog
9. class DogChild(Dog):
10. def eat(self):
11. print("Eating bread...")
12. d = DogChild()
13. d.bark()
14. d.speak()
15. d.eat()
Output:

dog barking
Animal Speaking
Eating bread...

Python Multiple inheritance


Python provides us the flexibility to inherit multiple base classes in the child class.

Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(d.Summation(10,20))
12. print(d.Multiplication(10,20))
13. print(d.Divide(10,20))

Output:

30
200
0.5

Q Define class and object and describe how they are


implemented in Python.

Object
The object is an entity that has state and behavior. It may be any real-world object like the
mouse, keyboard, chair, table, pen, etc.Everything in Python is an object, and almost everything
has attributes and methods.

Class
The class can be defined as a collection of objects. It is a logical entity that has some specific
attributes and methods. For example: if you have an employee class then it should contain an
attribute and method, i.e. an email id, name, age, salary, etc.

Creating classes in python


In python, a class can be created by using the keyword class followed by the class name. The
syntax to create a class is given below.

Syntax

1. class ClassName:
2. #statement_suite

Consider the following example to create a class Employee which contains two fields as Employee
id, and name.The class also contains a function display() which is used to display the information
of the Employee.

Example

1. class Employee:
2. id = 10;
3. name = "ayush"
4. def display (self):
5. print(self.id,self.name)

Here, the self is used as a reference variable which refers to the current class object. It is always
the first argument in the function definition. However, using self is optional in the function call.

Creating an instance of the class


A class needs to be instantiated if we want to use the class attributes in another class or method.
A class can be instantiated by calling the class using the class name.

The syntax to create the instance of the class is given below.

1. <object-name> = <class-name>(<arguments>)

The following example creates the instance of the class Employee defined in the above example.

Example

1. class Employee:
2. id = 10;
3. name = "John"
4. def display (self):
5. print("ID: %d \nName: %s"%(self.id,self.name))
6. emp = Employee()
7. emp.display()

Output:

ID: 10
Name: ayush
Q What is a file? Explain methods to open, close,read and
write files in Python.

Opening a file
Python provides the open() function which accepts two arguments, file name and access mode in
which the file is accessed. The function returns a file object which can be used to perform various
operations like reading, writing, etc.

The files can be accessed using various modes like read, write, or append. The following are the
details about the access mode to open a file.

Example

1. #opens the file file.txt in read mode


2. fileptr = open("file.txt","r")
3.
4. if fileptr:
5. print("file is opened successfully")

Output:

<class '_io.TextIOWrapper'>
file is opened successfully

The close() method


Once all the operations are done on the file, we must close it through our python script using the close()
method. Any unwritten information gets destroyed once the close() method is called on a file object.

The syntax to use the close() method is given below.

fileobject.close()

Consider the following example.

Example

1. # opens the file file.txt in read mode


2. fileptr = open("file.txt","r")
3.
4. if fileptr:
5. print("file is opened successfully")
6.
7. #closes the opened file
8. fileptr.close()

Reading the file


To read a file using the python script, the python provides us the read() method. The read() method
reads a string from the file. It can read the data in the text as well as binary format.

Here, the count is the number of bytes to be read from the file starting from the beginning of the file. If
the count is not specified, then it may read the content of the file until the end.

Consider the following example.

Example

1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file.txt","r");
3.
4. #stores all the data of the file into the variable content
5. content = fileptr.read(9);
6.
7. # prints the type of the data stored in the file
8. print(type(content))
9.
10. #prints the content of the file
11. print(content)
12.
13. #closes the opened file
14. fileptr.close()

Output:

<class 'str'>
Hi, I am

Writing the file


To write some text to a file, we need to open the file using the open method with one of the following
access modes.

a: It will append the existing file. The file pointer is at the end of the file. It creates a new file if no file
exists.

w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.
Consider the following example.

Example 1

1. #open the file.txt in append mode. Creates a new file if no such file exists.
2. fileptr = open("file.txt","a");
3.
4. #appending the content to the file
5. fileptr.write("Python is the modern day language. It makes things so simple.")
6.
7.
8. #closing the opened file
9. fileptr.close();

Now, we can see that the content of the file is modified.

File.txt:

1. Hi, I am the file and being used as


2. an example to read a
3. file in python.
4. Python is the modern day language. It makes things so simple.

Q What are various types of operators used in Python?

1. Arithmetic operators: Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication and division.
OPERATOR DESCRIPTION SYNTAX

+ Addition: adds two operands x+y

- Subtraction: subtracts two operands x-y

* Multiplication: multiplies two operands x*y

/ Division (float): divides the first operand by the second x/y

// Division (floor): divides the first operand by the second x // y

Modulus: returns the remainder when first operand is divided by

% the second x%y

# Examples of Arithmetic Operator


a=9
b=4
# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a - b
# Multiplication of number
mul = a * b
# Division(float) of number
div1 = a / b
# Division(floor) of number
div2 = a // b
# Modulo of both number
mod = a % b

# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
Output:
13
5
36
2.25
2
1

2. Relational Operators: Relational operators compares the values. It either True or False according
to the condition.
OPERATOR DESCRIPTION SYNTAX

> Greater than: True if left operand is greater than the right x>y

< Less than: True if left operand is less than the right x<y

== Equal to: True if both operands are equal x == y

!= Not equal to - True if operands are not equal x != y

Greater than or equal to: True if left operand is greater than or equal

>= to the right x >= y


Less than or equal to: True if left operand is less than or equal to the

<= right x <= y

Examples of Relational Operators


a = 13
b = 33

print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Output:
False
True
False
True
False
True

3. Logical operators: Logical operators perform Logical AND, Logical OR and Logical
NOToperations.

OPERATOR DESCRIPTION SYNTAX

And Logical AND: True if both the operands are true x and y

Or Logical OR: True if either of the operands is true x or y

Not Logical NOT: True if operand is false not x

# Examples of Logical Operator


a = True
b = False

print(a and b)
print(a or b)
print(not a)
Output:
False
True
False

4. Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation.

OPERATOR DESCRIPTION SYNTAX

& Bitwise AND x&y

| Bitwise OR x|y

~ Bitwise NOT ~x

^ Bitwise XOR x^y

>> Bitwise right shift x>>

<< Bitwise left shift


>>x
Examples of Bitwise operators
a = 10
b=4

# Print bitwise AND operation


print(a & b)

# Print bitwise OR operation


print(a | b)

# Print bitwise NOT operation

print(~a)

# print bitwise XOR operation

print(a ^ b)

# print bitwise right shift operation

print(a >> 2)

# print bitwise left shift operation


print(a << 2)
Output:
0
14
-11
14
2
40

Short Answer type questions

Q What is function and its advantages.

A function can be defined as the organized block of reusable code, which can be called whenever required.

The Function helps to programmer to break the program into the smaller part. It organizes the code very effectively
and avoids the repetition of the code. As the program grows, function makes the program more organized.

There are mainly two types of functions.

o User-define functions - The user-defined functions are those define by the user to perform the specific
task.
o Built-in functions - The built-in functions are those functions that are pre-defined in Python.

In this tutorial, we will discuss the user define functions.

Advantage of Functions in Python


There are the following advantages of Python functions.

o Using functions, we can avoid rewriting the same logic/code again and again in a program.
o We can call Python functions multiple times in a program and anywhere in a program.
o We can track a large Python program easily when it is divided into multiple functions.
o Reusability is the main achievement of Python functions.

Q Explain the lambda function with the help of a suitable


example
Python Lambda function is known as the anonymous function that is defined without a name. These functions are
declared by using the lambda keyword. However, Lambda functions can accept any number of arguments, but they
can return only one value in the form of expression.

The syntax to define an anonymous function is given below.


Syntax

1. lambda arguments: expression

It can accept any number of arguments and has only one expression. It is useful when the function objects are
required.

Consider the following example of the lambda function.

Example 1

1. x = lambda a:a+10
2. print(x)
3. print("sum = ",x(20))

Output:

<function <lambda> at 0x0000019E285D16A8>


sum = 30

In the above example, we have defined the lambda a: a+10 anonymous function where a is an argument
and a+10 is an expression. The given expression gets evaluated and returned the result.

Q Explain the constructor and its types in brief.


A constructor is a special type of method (function) which is used to initialize the instance
members of the class.

Constructors can be of two types.

1. Parameterized Constructor
2. Non-parameterized Constructor

Python Parameterized Constructor Example

1. class Student:
2. # Constructor - parameterized
3. def __init__(self, name):
4. print("This is parametrized constructor")
5. self.name = name
6. def show(self):
7. print("Hello",self.name)
8. student = Student("John")
9. student.show()

Output:

This is parametrized constructor


Hello John

Python Non-Parameterized Constructor Example


1. class Student:
2. # Constructor - non parameterized
3. def __init__(self):
4. print("This is non parametrized constructor")
5. def show(self,name):
6. print("Hello",name)
7. student = Student()
8. student.show("John")

Output:

This is non parametrized constructor


Hello John

Q What is a regular expression? Explain different functions that


can be used in regular expressions.

The regular expressions can be defined as the sequence of characters which are used to search for
a pattern in a string. The module re provides the support to use regex in the python program. The
re module throws an exception if there is some error while using the regular expression.

The re module must be imported to use the regex functionalities in python.

1. import re

Regex Functions
The following regex functions are used in the python.

SN Function Description

1 match This method matches the regex pattern in the string with the
optional flag. It returns true if a match is found in the string
otherwise it returns false.

2 search This method returns the match object if there is a match


found in the string.

3 findall It returns a list that contains all the matches of a pattern in


the string.

4 split Returns a list in which the string has been split in each
match.

5 sub Replace one or many matches in the string.


Q Explain split and substituting in Regular expression.

The split() Function


The split() function returns a list where the string has been split at each match:

Example
Split at each white-space character:

import re

str = "The rain in Spain"


x = re.split("\s", str)
print(x)

['The', 'rain', 'in', 'Spain']

The sub() Function


The sub() function replaces the matches with the text of your choice:

Example
Replace every white-space character with the number 9:

import re

str = "The rain in Spain"


x = re.sub("\s", "9", str)
print(x)

The9rain9in9Spain

You can control the number of replacements by specifying the count parameter:

Example
Replace the first 2 occurrences:

import re

str = "The rain in Spain"


x = re.sub("\s", "9", str, 2)
print(x)

The9rain9in Spain
Q Explain findall in Regular expression.

The findall() Function


The findall() function returns a list containing all matches.

Example
Print a list of all matches:

import re

str = "The rain in Spain"


x = re.findall("ai", str)
print(x)

['ai', 'ai']

The list contains the matches in the order they are found.

If no matches are found, an empty list is returned:

Example
Return an empty list if no match was found:

import re

str = "The rain in Spain"


x = re.findall("Portugal", str)
print(x)

[]
No match

Q Explain assert statement with an example


Python provides the assert statement to check if a given logical expression is true or false. If the condition
is True, the control simply moves to the next line of code. In case if it is False the program stops running and
returns AssertionError Exception.
Example 1
n=int(input("enter the no."))
assert n>=0
print(“The number is”,n)

Output :

enter the no.-5


Traceback (most recent call last):
File "C:/Users/Rajni Gupta/AppData/Local/Programs/Python/Python311/ss.py", line
2, in <module>
assert n>=0
AssertionError

Output :
enter the no.5
The number is 5

Q Appraise the use of try block and except block in Python with
syntax.
If the python program contains suspicious code that may throw the exception, we must place that code in the
try block. The try block must be followed with the except statement which contains a block of code that will
be executed if there is some exception in the try block.
We can also use the else statement with the try-except statement in which, we can place the code which will
be executed in the scenario if no exception occurs in the try block.

Example

1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b;
5. print("a/b = %d"%c)
6. except Exception:
7. print("can't divide by zero")
8. else:
9. print("Hi I am else block")

Output:

Enter a:10
Enter b:2
a/b = 5
Hi I am else block

Q What are quantifiers?


In regular expressions, quantifiers match the preceding characters or character sets a number of
times. The following table shows all the quantifiers and their meanings :
Quantifier Name Meaning

* Asterisk Match its preceding element zero or more times.

+ Plus Match its preceding element one or more times.

? Question Mark Match its preceding element zero or one time.

Q Explain the sys module


It provides functions and variables used to manipulate different parts of the Python runtime environment .

Sys.maxsize
It returns the largest integer a variable can take.

import sys
sys.maxsize

OUTPUT:

2147483647

Sys.path
This is an environment variable that is a search path for all Python modules
import sys
sys.path

OUTPUT:

['C:/Users/Rajni/AppData/Local/Programs/Python/Python38-32', 'C:\\Users\\Rajni\\AppData\\Local\\
Programs\\Python\\Python38-32\\lib\\site-packages']

Q Define the module and how it is imported into a Python file.


Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

Create a Module
To create a module just save the code you want in a file with the file extension .py:

Example

Save this code in a file named mymodule.py

def greeting(name):
print("Hello, " + name)

Use a Module
Now we can use the module we just created, by using the import statement:

Example
Import the module named mymodule, and call the greeting function:

import mymodule

mymodule.greeting("John")

OUTPUT:

Hello john

Q Explain the math module


The Math Module
Python has also a built-in module called math, which extends the list of mathematical functions.
To use it, you must import the math module:
import math

When you have imported the math module, you can start using methods and constants of the module.

The math.sqrt() method for example, returns the square root of a number :

import math

x = math.sqrt(64)

print(x)

Output: 4

The math.ceil() method rounds a number upwards to its nearest integer, and the math.floor() method
rounds a number downwards to its nearest integer, and returns the result:

import math

x = math.ceil(1.4)
y = math.floor(1.4)

print(x) # returns 2
print(y) # returns 1

Q Differentiate between List and Tuples

SN List Tuple
1 The literal syntax of list is shown by the []. The literal syntax of the tuple is
shown by the ().

2 The List is mutable. The tuple is immutable.

3 The List has the variable length. The tuple has the fixed length.

4 The list provides more functionality than The tuple provides less functionality
tuple. than the list.

5 The list Is used in the scenario in which we The tuple is used in the cases where
need to store the simple collections with no we need to store the read-only
constraints where the value of the items can collections i.e., the value of the
be changed. items can not be changed. It can be
used as the key inside the
dictionary.

Q Explain Dictionary and how it is created in Python


Dictionary is used to implement the key-value pair in python. The dictionary is the data type in
python which can simulate the real-life data arrangement where some specific value exists for
some particular key.

Creating the dictionary


The dictionary can be created by using multiple key-value pairs enclosed with the small brackets ()
and separated by the colon (:). The collections of the key-value pairs are enclosed within the curly
braces {}.

The syntax to define the dictionary is given below.

1. Dict = {"Name": "Ayush","Age": 22}

In the above dictionary Dict, The keys Name, and Age are the string that is an immutable object.

Let's see an example to create a dictionary and printing its content.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
Output

<class 'dict'>
printing Employee data ....
{'Age': 29, 'salary': 25000, 'Name': 'John', 'Company': 'GOOGLE'

Q What are the various types of loops in python?


Python has two primitive loop commands:

 while loops
 for loops

The while Loop


With the while loop we can execute a set of statements as long as a condition is true.

Example

Print i as long as I is less than 6:

i = 1
while i< 6:
print(i)
i += 1

The break Statement

With the break statement we can stop the loop even if the while condition is true:

Example

Exit the loop when iis 3:

i = 1
while i< 6:
print(i)
if i == 3:
break
i += 1

The continue Statement

With the continue statement we can stop the current iteration, and continue with the next:

Example

Continue to the next iteration if iis 3:

i = 0
while i< 6:
i += 1
if i == 3:
continue
print(i)
For Loop

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or
a string).

This is less like the for keyword in other programming languages, and works more like an iterator
method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

Example

Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

The for loop does not require an indexing variable to set beforehand .

Q Define variable and what are the rules for creating variables in
Python.

A variable in python gives data to the computer for processing. It is a reserved memory location to
store values.

A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).

Rules for Python variables:

 A variable name must start with a letter or the underscore character


 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and
_)
 Variable names are case-sensitive (age, Age and AGE are three different variables)

Q Difference Between C++ and Python

Parameters Python C++

C++ tends to have long lines of


Code Python has fewer lines of code
code

Variable Variables are declared by simply While declaring a variable it is


Declaration writing their name with their datatype necessary to mention its datatype
Parameters Python C++

Compilation Python is interpreted C++ is precompiled

It is slower since it uses an interpreter


It is faster once compiled as
Speed and also determines the data type at
compared to python
run time

Installation on
Difficult to install on Windows Easy to install on Windows
Windows

Nature It is dynamically typed. is statically typed

Python Functions do not have


In C++, the function can accept
restrictions on the type of the
Functions and return the type of value which
argument and the type of its return
is already defined
value

Scope of Variables are accessible even outside The scope of variables is limited
Variable the loop within the loops

Python programs are saved with C++ programs are saved with the
Extension
the .py extension .cpp extension

Application Web development, data analysis, Game development, embedded


Domain scientific computations, etc systems, etc

Q Explain any four keywords or reserved words of Python

Python keywords are special reserved words that have specific meanings and purposes and can’t be used for
anything but those specific purposes.

Some of the keywords are:

For, while, true , false, if , for, while

You might also like