exame book
exame book
Python is an interpreted scripting language that is known for its power, interactivity, and object-oriented
nature. It utilizes English keywords extensively and has a simpler syntax compared too many other
programming languages.
Python is designed to be highly readable and compatible with different platforms such as Mac, Windows,
Linux, Raspberry Pi, etc.
An interpreted programming language refers to any language that executes its instructions sequentially, one line
at a time. In the case of Python, programs are executed directly from the source code without the need for any
intermediate compilation process.
This code can be of different types like classes, functions, or variables. This saves the programmer’s time by
providing predefined functionalities when needed. It is a file with “.py” extension containing an executable code.
Number
String
Tuple
A Python namespace ensures that the names assigned to objects within a program are unique and can be
used without conflict. In Python, namespaces are implemented as dictionaries where the object’s name
serves as the key and the object itself serves as the value.
In Python, a scope defines the region of code where an object remains valid and accessible. Every object
in Python operates within its designated scope
In Python classes, the reserved method init serves a similar purpose as constructors in object-oriented
programming (OOP) terminology. When a new object is created, the init method is automatically called,
initializing the object and allocating memory for it. This method can also be utilized to set initial values
for variables.
Below is an example:
class Human:
def __init__(self, age):
self.age = age
def say(self):
print('Hello, my age is', self.age)
h = Human(22)
h.say()
Output:
Hello, my age is 22
A local variable is a variable that is defined within a specific function and is only accessible within that
function. It cannot be accessed by other functions within the program.
A global variable is a variable that is declared outside of any function, allowing it to be accessed by all
functions .
Example:-
def func_multiply():
m=g*l
return m
func_multiply()
Output: 20
Python offers a valuable feature that allows for the conversion of data types as needed. This process is referred to
as type conversion in Python.
Implicit Type Conversion: This type of conversion is automatically performed by the Python interpreter without
requiring any user intervention.
Explicit Type Conversion: This type of conversion involves the user explicitly changing the data type to the
desired type.
Python supports various data types, including dictionaries. A dictionary in Python is a collection of elements
that are stored as key-value pairs. It is an unordered data structure, and the indexing is done based on the keys
assigned to each element.
example: we have a dictionary named ‘dict’ with two keys, ‘Country’ and ‘Capital’, which have corresponding
values ‘India’ and ‘New Delhi’, respectively.
Syntax:
dict={‘Country’:’India’,’Capital’:’New Delhi’, }
Yes,
Python is a case sensitive language. In Python, it is important to note that “Function” and “function” are distinct
entities, similar to how SQL and Pascal handle them differently.
18. Is indentation required in Python?
It is a method used by programming languages to determine the scope and extent of code blocks. In Python,
indentation serves this purpose.
The mandatory requirement of indentation in Python not only enforces consistent code formatting but also
enhances code readability, which is likely the reason behind its inclusion.
The following statements assist in altering the course of execution from the regular flow, which categorizes them
as loop control statements.
Python break: This statement aids in discontinuing the loop or the statement and transferring control to the
subsequent statement.
Python continue: This statement enforces the execution of the subsequent iteration when a particular
condition is met, instead of terminating it.
Python pass: This statement allows the syntactical writing of code while intending to bypass its execution.
It is also recognized as a null operation, as no action is taken when the pass statement is executed.
21. What are negative indexes and why are they used?
To retrieve an item from a sequential collection, we can simply utilize its index, which represents the
position of that specific item. Conventionally, the index commences at 0, implying that the initial element
has an index of 0, the second element has an index of 1, and so forth.
When employing reverse indexing, we access elements from the opposite end of the sequence. In this
case, the indexing initiates from the last element, denoted by the index number ‘-1’. The second-to-last
element is assigned an index of ‘-2’, and so forth. These negative indexes employed in reverse indexing
are specifically referred to as negative indexes.
Both append() and extend() methods are methods used to add elements at the end of a list.
The primary differentiation between the append() and extend() methods in Python is that append() is used
to add a single element to the end of a list. In contrast, open () is used to append multiple aspects, such as
another list or an iterable, to the end of a list.
A lambda function is an anonymous function (a function that does not have a name) in Python. To define
anonymous functions, we use the ‘lambda’ keyword instead of the ‘def’ keyword, hence the name
‘lambda function’. Lambda functions can have any number of arguments but only one statement.
For example:
l = lambda x,y : x*y
print(a(5, 6))
Output:30
Syntax:
List_name[start:stop]
Syntax:
Class A:
def func(self):
print("Hi")
25. Why would you use NumPy arrays instead of lists in Python?
NumPy arrays provide users with three main advantages as shown below:
NumPy arrays consume a lot less memory, thereby making the code more efficient.
NumPy arrays execute faster and do not add heavy processing to the runtime.
NumPy has a highly readable syntax, making it easy and convenient for programmers.
27. How will you remove the last object from a list in Python?
my_list = [1, 2, 3, 4, 5]
my_list.pop()
Here, −1 represents the last element of the list. Hence, the pop() function removes the last object (obj) from the
list.
Syntax:
x , y=10,20
count = x if x<y else y
Output:
3.6
1.1 # element popped at 3 rd index
array('d', [ 2.4, 6.8, 7.7, 1.2])
Output:- 1 2 5 7 8
Command:
f= open(“hello.txt”, “wt”)
len() is an inbuilt function used to calculate the length of sequences like list, python string, and array.
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length)
Python iterators are objects that allow you to access elements of a collection one at a time. They use the __iter__()
and __next__() methods to retrieve the next element until there are no more. Iterators are commonly used in for
loops and can be created for custom objects. They promote efficient memory usage and enable lazy evaluation of
elements. In summary, iterators provide a convenient way to iterate over data structures in a controlled and
efficient manner.
No. Python is a dynamically typed language, i.e., the Python Interpreter automatically identifies the data type of a
variable based on the type of value assigned.
Python comprehensions are like decorators that help to build altered and filtered lists, dictionaries, or sets from a
given list, dictionary, or a set. Comprehension is a powerful feature in Python that offers a convenient way to
create lists, dictionaries, and sets with concise expressions. It eliminates the need for explicit loops, which can
help reduce code size and save time during development.
For example:
my_list = [2, 3, 5, 7, 11]
squared_list = [x**2 for x in my_list] # list comprehension
To remove duplicate elements from the list we use the set() function.
43.Write a Python program to count the total number of lines in a text file?
Refer the code below to count the total number of lines in a text file-
def file_count(fname):
with open(fname) as f:
for i, _ in enumerate(f):
pass
return i + 1
Python does follow an object-oriented programming paradigm and has all the basic OOPs concepts such as
inheritance, polymorphism, and more, with the exception of access specifiers. Python doesn’t support strong
encapsulation (adding a private keyword before data members). Although, it has a convention that can be used for
data hiding, i.e., prefixing a data member with two underscores.