Untitled Deck Flashcards

(72 cards)

1
Q

What is the difference between a module and a package in Python?

A
  • Module: a single .py file containing functions, variables, or classes
  • Package: a directory with an __init__.py file and multiple modules inside

Packages help organize code logically and make it reusable and easier to manage.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does the import statement do in Python?

A

It allows you to reuse code from other files or libraries

This promotes the use of existing solutions and helps build modular, scalable programs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the purpose of the __init__.py file in a package?

A

It initializes a package and/or its sub-packages

The file may be empty but must not be absent for the directory to be recognized as a package.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What does the dir() function do?

A

Shows a list of the entities contained inside an imported module

Example: dir(os) will list all attributes, functions, and classes defined in the os module.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the role of the sys.path variable?

A

Controls where Python looks for modules when using an import statement

It determines the search path Python follows to locate the files that define the modules you’re importing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

List the functions provided by the math module.

A
  • ceil()
  • floor()
  • trunc()
  • factorial()
  • hypot()
  • sqrt()

These functions perform various mathematical operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does the math.ceil(x) function do?

A

Rounds up to the nearest integer (toward +∞)

Example: math.ceil(3.1) returns 4.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does the random.random() function return?

A

A random float in the range (0.0, 1.0)

Example output: 0.5738…

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the purpose of the random.seed(x) function?

A

Initializes the random number generator for reproducibility

Always use seed() before random() if you want repeatable output.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What does the platform.platform() function return?

A

A single string describing the full platform

Example output: ‘Windows-10-10.0.19041-SP0’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the significance of the __name__ variable in Python?

A

Indicates if a file is run directly or imported as a module

If run directly, __name__ is set to __main__; if imported, it is set to the file’s name.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

True or false: The finally branch of the try statement is executed only if an exception occurs.

A

FALSE

The finally branch is always executed, regardless of whether an exception occurred.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are abstract expressions in the context of Python exceptions?

A

Base classes in the exception hierarchy not meant to be raised directly

They provide categorization or grouping of related errors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

List three examples of concrete built-in Python exceptions.

A
  • AssertionError
  • ImportError
  • IndexError

These represent actual error conditions that can occur.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What does the except (e1, e2) syntax do?

A

Catches multiple types of exceptions in one block

e1 and e2 must be exception types like ValueError or TypeError.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the purpose of the __pycache__ directory?

A

Stores semi-compiled .pyc files for imported modules

This improves performance by avoiding recompilation on subsequent imports.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is a namespace in Python?

A

A mapping between names and objects (like variables or functions)

Different types include local, global, nonlocal, and built-in namespaces.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Fill in the blank: A module is designed to couple together some related entities such as functions, variables, and _______.

A

constants

This helps in organizing code logically.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Name some concrete built-in Python exceptions.

A
  • AssertionError
  • ImportError
  • IndexError
  • KeyboardInterrupt
  • KeyError
  • MemoryError
  • OverflowError

These exceptions are part of Python’s built-in exception hierarchy.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is the purpose of the raise statement in Python?

A
  • Raise an exception on demand
  • Re-raises the current exception
  • Raises the exception stored in a variable

The raise statement can be used to trigger exceptions intentionally.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

True or false: Assertions are used for handling runtime errors.

A

FALSE

Assertions are primarily used for debugging and can be disabled when Python is run with the -O flag.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What are event classes in Python exceptions?

A
  • Represent errors and signals
  • Can be caught, raised, and defined
  • Allow precise error handling and flow control

Event classes include exceptions like KeyboardInterrupt and SystemExit.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What does the syntax except E as e: do?

A

Catches a specific exception and assigns it a name

This allows you to access the details of the exception after catching it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the args property in Python exceptions?

A

A tuple containing the arguments passed to the exception

You can access individual arguments using ex.args[index].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
How can you create a **custom exception** in Python?
Define a class that inherits from `Exception` ## Footnote You can add custom properties and methods to manage the exception's behavior.
26
What are the **encoding standards** mentioned for character representation?
* ASCII * UNICODE * UTF-8 ## Footnote These standards are commonly used in IT for encoding characters.
27
What is a **code point**?
A number corresponding to a particular character ## Footnote For example, *32* is the code point for a space in ASCII encoding.
28
What does **BOM** stand for in encoding?
Byte Order Mark ## Footnote It indicates the encoding used by a file's contents.
29
True or false: **Python strings** can be changed in-place.
FALSE ## Footnote Strings in Python are immutable, meaning they cannot be modified after creation.
30
What does the **ord()** function do?
Returns the ASCII/UNICODE code point value of a character ## Footnote For example, `ord('a')` returns 97.
31
What does the **chr()** function do?
Returns the character corresponding to a given code point ## Footnote For example, `chr(97)` returns 'a'.
32
What is the difference between **sort()** and **sorted()**?
* `sort()`: Sorts a list in place * `sorted()`: Returns a new sorted list ## Footnote `sort()` modifies the original list, while `sorted()` does not.
33
What does the method **.isalpha()** check?
Checks if the string consists only of letters ## Footnote Returns `True` if the string contains only alphabetic characters.
34
What does the method **.split(sep)** do?
Splits a string into a list using a separator ## Footnote For example, `'a-b-c'.split('-')` returns `['a', 'b', 'c']`.
35
What is the purpose of **encapsulation** in Object-Oriented Programming?
Hides the internal state of an object and requires all interaction to be performed through an object's methods ## Footnote This promotes modularity and protects object integrity.
36
What is a **subclass**?
A class that is derived from another class ## Footnote The class from which it is derived is called the superclass.
37
What is the role of a **superclass**?
The class from which subclasses are derived ## Footnote It can provide common properties and methods to its subclasses.
38
What is the significance of **two underscores (`__`)** at the start of a class component's name?
Indicates that the component is private ## Footnote This is part of Python's name mangling feature to prevent name clashes.
39
What is an **inheritance diagram**?
A diagram where superclasses are presented above their subclasses and relations are shown as arrows directed from the subclass toward its superclass ## Footnote It visually represents the hierarchical structure of classes.
40
What are the components of an object?
* Name * Properties * Methods ## Footnote Objects can have a set of properties and methods, which can be empty.
41
What happens if a class component has a name starting with two underscores (`__`)?
It becomes **private** and can only be accessed from within the class ## Footnote This is how Python implements the **encapsulation** concept.
42
What is a **constructor** in Python?
A method named `__init__` responsible for creating new objects ## Footnote It cannot return any value and cannot be invoked directly.
43
True or false: An **instance variable** exists independently of an object.
FALSE ## Footnote Instance variables depend on the creation of an object.
44
What is the purpose of the `__dict__` property?
It stores all instance variables in a dedicated dictionary for each object ## Footnote Class variables are not shown in an object's `__dict__`.
45
List the features of **private attributes** in instances vs. classes.
* Defined in `__init__()` or methods (instance) * Defined directly inside class body (class) * Uses `self` (instance) * Does not use `self` (class) ## Footnote Private attributes are accessed differently in instances and classes.
46
What is the **self** parameter used for in methods?
To obtain access to the object's instance and class variables ## Footnote It is always the first parameter in a method.
47
What does the `hasattr()` function do?
Checks if an object/class contains a specified property ## Footnote It returns True or False.
48
What does the `issubclass(Class_1, Class_2)` function determine?
If `Class_1` is a **subclass** of `Class_2` ## Footnote It helps in understanding class hierarchies.
49
What is **polymorphism** in Python?
The ability of a subclass to modify its superclass behavior ## Footnote It allows methods to behave differently based on the object.
50
What does the `is` operator check?
If two variables refer to **the same object** ## Footnote It helps in understanding object identity.
51
What is the purpose of the `__str__()` method?
To convert an object's contents into a readable string ## Footnote It can be overridden for custom string representation.
52
What is **multiple inheritance**?
A class inherits from two or more classes ## Footnote It can lead to complexity and ambiguity in the inheritance hierarchy.
53
What is the difference between **inheritance** and **composition**?
* Inheritance extends a class's capabilities * Composition projects a class as a container for other objects ## Footnote Both are ways to build class relationships.
54
What does the `super()` function do?
Returns a reference to the nearest **superclass** of the class ## Footnote It is useful for accessing inherited methods.
55
What is the **yield** statement used for?
To suspend function execution and return a value as part of a **generator** ## Footnote It can only be used inside functions.
56
What is a **class variable**?
A property that exists in exactly one copy and doesn't need an object to be accessible ## Footnote Class variables are stored in a class's `__dict__`.
57
The **yield** statement can be used only inside _______.
functions ## Footnote The yield statement suspends function execution and causes the function to return the yield's argument as a result.
58
A **lambda** function is a function without a _______.
name ## Footnote Lambda functions are also called anonymous functions.
59
The **map()** function applies a function to each element in an _______.
iterable ## Footnote It can be used with lists or tuples.
60
The **filter()** function returns a new iterable containing only the elements for which the function returns _______.
True ## Footnote The filter function is useful for extracting elements that meet certain criteria.
61
A **closure** allows the storing of values even when the context in which they were created _______.
does not exist anymore ## Footnote Closures are useful for maintaining state in nested functions.
62
In Python, there are three **predefined streams**: _______.
* sys.stdin * sys.stdout * sys.stderr ## Footnote These streams are automatically available for input, output, and error handling.
63
The **open()** function syntax is used to open a file: open(file_name, mode=open_mode, _______).
encoding=text_encoding ## Footnote This function creates a stream object associated with the specified file.
64
The **errno** variable contains a property named _______ when any file operation fails.
errno ## Footnote This property helps diagnose the problem with file operations.
65
To read a file’s contents, the following stream methods can be used: _______.
* read(number) * readline() * readlines(number) ## Footnote These methods allow for different ways to read data from a file.
66
A **bytearray** is a mutable sequence of _______.
bytes ## Footnote It is useful for buffering binary input/output.
67
In text mode, data type is _______ and requires encoding.
str ## Footnote Text mode is used for files that contain readable text.
68
In binary mode, data type is _______ and does not require encoding.
bytes ## Footnote Binary mode is used for files that contain raw data.
69
The **close()** method is used to _______ a file stream.
close ## Footnote It is important to close file streams to free up system resources.
70
The **read()** method reads the specified number of _______ from the file.
characters/bytes ## Footnote It can read the whole file at once if no number is specified.
71
The **write()** method writes a _______ to a text file.
string ## Footnote This method is used to add new content to a file.
72
The **chunk size** in the context of reading data from a file can be set to _______.
1024 ## Footnote This is a common size for reading data in chunks.