B1_0801IT231121_LAB1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Shivam Jhawar

0801IT231121

LAB ASSIGNMENT -1

No. Question
1 What is Python, and what are its key features?
Ans Python is a high-level, interpreted programming language known for its
readability, simplicity, and versatility. It was created by Guido van Rossum and
was first released in 1991. Python is widely used in various fields such as web
development, data analysis, machine learning, automation, and scientific
computing, among others.

Key Features of Python:

● Readability: Python's syntax is clean and concise, resembling natural


language, making it easy to learn and understand.
● Interpreted: Python code is executed line by line, simplifying
debugging and testing.
● Dynamically Typed: You don't need to explicitly declare variable types,
which can streamline development.
● Large Standard Library: Python comes with a vast collection of
built-in modules and functions, covering various tasks like file I/O,
networking, and data manipulation.
● Cross-Platform Compatibility: Python code can run on different
operating systems without modification
● Extensible: Python can be extended with C/C++ code for
performance-critical tasks.
\
● Object-Oriented: Python supports object-oriented programming
principles, allowing you to model real-world entities and create reusable
cod.
Shivam Jhawar

0801IT231121

2 What is the difference between an interpreted and compiled


language, and where does Python fit?
Ans Compiled Languages

Compilation: The entire source code is translated into machine code (a sequence
of instructions the computer's CPU can directly understand) before
execution.This process is performed by a compiler.

Execution: The generated machine code is then executed directly by the CPU.

Examples: C, C++, C#, Java (bytecode is compiled to machine code at runtime)

Pros:Generally faster execution due to direct CPU interaction.

Often produce more efficient and optimized code.

Cons:Slower development cycle due to the need for compilation after each code
change.

Less portable as the compiled code may be specific to a particular architecture.

Interpreted Languages

Interpretation: The source code is executed line by line by an interpreter, which


translates each line into machine code and executes it immediately.

Examples: Python, JavaScript, Ruby, PHP

Pros:Faster development cycle as changes can be tested immediately without


recompilation.

More portable as the interpreter handles the translation to machine code.

Cons:Generally slower execution compared to compiled languages due to the


overhead of interpretation.
Shivam Jhawar

0801IT231121

Python's Place

Python is primarily an interpreted language.

However, some Python implementations (like PyPy) use a technique called


Just-In-Time (JIT) compilation, where parts of the code are dynamically
compiled to machine code during execution for performance optimization.

3 What is PEP 8, and why is it important?

Ans PEP 8 is a style guide for Python code. It provides a set of recommendations for
writing clean, readable, and consistent Python code.
Key aspects of PEP 8:
Indentation: Use 4 spaces for indentation, not tabs.
Line Length: Limit all lines to a maximum of 79 characters.
Blank Lines: Use blank lines to separate functions and classes, and to group
related blocks of code within a function.
Naming Conventions: Use lowercase with underscores for variable and function
names (e.g., my_variable, my_function). Use CamelCase for class names (e.g.,
MyClass).
Comments: Use dorings to document functions and classes. Use inline
comments sparingly to explain complex logic.

Importance of PEP cst8:

Readability: Consistent code style makes it easier for others (and your future
self) to read and understand your code.
Maintainability: Following a common style guide makes it easier to maintain
and modify code over time.
Collaboration: When working on projects with others, adhering to PEP 8
ensures that everyone is writing code in a consistent manner, which improves
team productivity.
Shivam Jhawar

0801IT231121

Professionalism: Following industry-standard style guides demonstrates


professionalism and attention to detail.
4 What are Python's key applications or use cases?
Ans Python finds widespread use across numerous domains:
Web Development:Building websites and web applications.
Data Science: Analyzing data, building machine learning models.
Scientific Computing: Performing complex calculations.
Automation: Automating tasks, scripting.
AI: Developing AI applications.
Game Development: Creating game logic and AI.
Education: Teaching programming.
GUI Applications: Building desktop applications.
5 What are Python's core data types?
Ans Python offers several core data types:
Python offers several core data types:
Numbers:
Integers (int):Whole numbers (e.g., 10, -5, 0)
Floating-point numbers (float): Numbers with decimal points (e.g., 3.14, -2.5)
Complex numbers (complex): Numbers with both real and imaginary parts (e.g.,
2+3j)

Strings (str): Sequences of characters enclosed in single ('...') or double ("...")


quotes (e.g., "Hello", 'Python')
Booleans (bool): Represent truth values: True or False
Sequences:
Lists: Ordered, mutable collections of items (e.g., [1, 2, 3], ["apple", "banana"])
Tuples: Ordered, immutable collections of items (e.g., (1, 2, 3), ("apple",
"banana"))
Mappings:
Shivam Jhawar

0801IT231121

Dictionaries (dict): Unordered collections of key-value pairs (e.g., {"name":


"Alice", "age": 30})
Sets: Unordered collections of unique items (e.g., {1, 2, 3}, {"apple",
"banana"}).
6 What is the Python interpreter, and how does it work?
Ans The Python interpreter is a program that reads and executes Python code. Here's
a breakdown of its key functions:
Reads the code: The interpreter takes your Python source code (written in a .py
file) as input.

Parses the code: It analyzes the code to check for syntax errors and to
understand the structure of the program. This involves breaking down the code
into smaller, more manageable units.

Translates to bytecode: The interpreter translates the Python code into an


intermediate representation called bytecode. Bytecode is a set of low-level
instructions that are specific to the Python Virtual Machine (PVM).

Executes the bytecode: The PVM executes the bytecode instructions. This is
where the actual work of the program happens.

Manages memory: The interpreter also manages the memory used by the
program, allocating and deallocating memory as needed.
7 What is the significance of indentation in Python?
Ans Indentation is crucial in Python. It's not just for readability; it defines the
structure and execution flow of the code.

Blocks of Code:Python uses indentation to group statements together.


Code blocks within functions, loops, and conditional statements are defined by
their indentation level.
Shivam Jhawar

0801IT231121

Consequences of Incorrect Indentation:

Syntax Errors: Incorrect indentation will lead to syntax errors, preventing the
code from running.

Logical Errors: Even if the code runs, incorrect indentation can cause
unexpected behavior, leading to incorrect results.

Consistency:Maintaining consistent indentation (usually 4 spaces) throughout


your code is essential for readability and maintainability.
8 What are the main differences between Python 2 and Python 3?
Ans Print Statement:
Python 2: print "Hello, world!"
Python 3: print("Hello, world!") (print is a function)
Division:
Python 2: 7 / 2 results in 3 (integer division)
Python 3: 7 / 2 results in 3.5 (floating-point division)
String Handling:
Python 2: Strings are ASCII by default.
Python 3: Strings are Unicode by default.
xrange vs. range:
Python 2: xrange() generates an iterator.
Python 3: range() generates an iterator (xrange() was removed).
Exception Handling:
Python 2: except Exception, e:
Python 3: except Exception as e:
Input Function:
Python 2: raw_input() for getting user input as a string.
Python 3: input() gets user input as a string.
Library Support:
Shivam Jhawar

0801IT231121

Many Python 2 libraries are not compatible with Python 3.

Key Points:
Python 3 is the present and future of Python.
Python 2 is no longer officially supported.
It's generally recommended to learn and use Python 3 for new project
9 What is the purpose of Python's `pip` tool?
Ans Python's pip is a crucial command-line tool that acts as the package installer for
the Python ecosystem. It simplifies the process of acquiring and managing
third-party libraries, which are collections of pre-written code that extend
Python's functionality. With pip, developers can easily install packages from the
Python Package Index (PyPI) and other repositories, ensuring access to a vast
array of tools for various domains like data science, machine learning, web
development, and more. Furthermore, pip enables the uninstallation of packages
when they are no longer needed, updates installed packages to the latest
versions, lists currently installed packages, and effectively manages
dependencies between packages, streamlining the development process and
ensuring a smooth and efficient project workflow.

10 What is a Python virtual environment, and why is it used?


Ans A Python virtual environment is an isolated space where you can work on a
specific Python project, independent of other projects or your system-wide
Python installation. It creates a self-contained environment with its own Python
interpreter and a dedicated set of installed packages.
Key Benefits of Using Virtual Environments:
Project Isolation: Each project gets its own unique set of dependencies,
preventing conflicts between different projects that might require different
versions of the same package.
Shivam Jhawar

0801IT231121

System Integrity: Changes made within a virtual environment won't affect your
system-wide Python installation, ensuring stability and preventing accidental
modifications.
Reproducibility: Virtual environments make it easy to recreate the exact
environment for a specific project, ensuring consistent behavior across different
machines.
Dependency Management: Managing dependencies becomes more
straightforward, as you can easily install, update, and uninstall packages within
the isolated environment.
11 What are Python's advantages compared to other programming
languages?
Ans Python boasts several advantages over other programming languages:

Readability: Python's syntax is renowned for its clarity and simplicity,


resembling natural language. This readability enhances code maintainability and
collaboration among developers.
Versatility: Python is a general-purpose language, adaptable to a wide range of
applications, including web development, data science, machine learning,
scripting, and automation.
Large and Active Community: A vast and supportive community provides
extensive resources, libraries, and frameworks, accelerating development and
problem-solving.
Cross-Platform Compatibility: Python code can run seamlessly on various
operating systems, promoting portability and flexibility.
Beginner-Friendly: Python's beginner-friendly nature makes it an excellent
choice for learning programming concepts. Its straightforward syntax and
emphasis on readability facilitate a smooth learning curve.
Extensive Libraries: The Python Package Index (PyPI) hosts a vast repository
of third-party libraries, offering pre-built solutions for a wide array of tasks,
saving developers time and effort.
Shivam Jhawar

0801IT231121

12 What are Python's limitations or drawbacks?


Ans Python, while powerful, has some limitations:
Speed: Being an interpreted language, Python generally executes slower than
compiled languages like C++ or Java. This can be a concern for
performance-critical applications.
Memory Consumption: Python's dynamic typing and flexibility can lead to
higher memory consumption compared to some other languages.
Global Interpreter Lock (GIL): The GIL in CPython (the most common
Python implementation) limits the utilization of multiple CPU cores for
CPU-bound tasks, potentially hindering performance in multi-threaded
applications.
Mobile Development: While Python can be used for mobile development with
frameworks like Kivy, it's not as dominant in this domain as languages like Java
(for Android) or Swift (for iOS).
13 What is a Python module, and how is it different from a Python
package?
Ans In Python, both modules and packages are used to organize and structure code,
but they serve different purposes:

Module: A module is essentially a single Python file (with the .py extension)
containing Python code. This code can include functions, classes, variables, and
more. Modules help break down large programs into smaller, more manageable
units, improving code organization and reusability.
Package: A package is a collection of related modules organized within a
directory hierarchy. To signify a directory as a package, it must contain a special
file named __init__.py (which can be empty). Packages allow for hierarchical
structuring of modules, creating a more organized and modular namespace,
especially for larger projects.
Shivam Jhawar

0801IT231121

14 What is the difference between mutable and immutable objects in


Python?
Ans Immutable Objects:
Cannot be changed after creation.
When you try to modify an immutable object, a new object is created with the
modified value.
Examples:
Numbers: Integers (int), Floats (float), Complex numbers (complex)
Strings (str)
Tuples (tuple)

Mutable Objects:
Can be changed after creation.
Modifications are made in-place, altering the original object.
Examples:
Lists (list)
Dictionaries (dict)
Sets (set)
15 What are keywords in Python? Name a few examples.
Ans In Python, keywords are reserved words with specific meanings and purposes.
They cannot be used as variable names, function names, or any other identifiers.
Here are a few examples:

● if: Used for conditional execution of code.


● else: Used with if to specify code to be executed if the condition is
false.
● for: Used for loop iteration.
● while: Used for loop iteration that continues as long as a condition is
true.
Shivam Jhawar

0801IT231121

● def: Used to define a function.


● return: Used to return a value from a function.
● class: Used to define a class.
● import: Used to import modules or packages.
● try: Used for exception handling.
● except: Used with try to handle specific exceptions.

16 What is the role of the `__init__.py` file in Python packages?


Ans The __init__.py file plays a crucial role in defining Python packages. Here's its
significance:
Package Declaration:
The presence of __init__.py (even if it's empty) within a directory signals to
Python that this directory should be treated as a package.

Controlling Imports:
The __init__.py file can be used to control which modules or subpackages are
imported when you use the from ... import * syntax.You can explicitly list the
names of modules or subpackages that should be imported by default in the
__init__.py file.

Namespace Management:
It helps to manage the namespace of the package, defining which names are
accessible when importing from the package.

# In my_package/__init__.py
from .module1 import function1
from .module2 import class1
17 Explain the concept of Python's dynamic typing.
Shivam Jhawar

0801IT231121

Ans In Python, dynamic typing refers to the ability of variables to hold values of
different data types throughout the program's execution. This means you don't
need to explicitly declare the data type of a variable before assigning a value to
it.

Key Characteristics:
No explicit type declarations: You can directly assign values to variables without
specifying their type.
Type inference: The Python interpreter automatically determines the data type of
a variable based on the assigned value.
Flexibility: Allows for more flexible code and rapid prototyping.
18 What are Python's control flow statements? Name them.
Ans Control flow statements in Python are used to alter the normal sequential
execution of code. They allow you to control which parts of the code are
executed and in what order. Here are some of the main control flow statements
in Python:

if, elif, else: These statements are used to conditionally execute blocks of code
based on whether a certain condition is true or false.

for loop: This statement is used to iterate over a sequence (like a list, tuple, or
string) or any other iterable object.

while loop: This statement is used to repeatedly execute a block of code as long
as a given condition is true.

break: This statement is used to immediately exit from a loop, regardless of


whether the loop's condition is still true.
continue: This statement is used to skip the current iteration of a loop and
proceed to the next iteration.
Shivam Jhawar

0801IT231121

try, except, and finally: These statements are used for exception handling,
allowing you to gracefully handle errors that might occur during the execution
of your code.
19 what is the Global Interpreter Lock (GIL) in Python?
Ans The Global Interpreter Lock (GIL) is a mutex (or lock) used in CPython, the
default implementation of Python, to synchronize access to Python objects. It
ensures that only one thread executes Python bytecode at a time, even on
multi-core systems. This simplifies memory management in CPython but limits
the ability of Python programs to achieve true parallelism in multi-threaded
code.
20 How does Python handle memory management?
Ans
Python handles memory management automatically through a combination of
mechanisms that manage the allocation and deallocation of memory for Python
objects. This is primarily achieved using a private heap and a garbage collection
system. Here's an overview of how Python handles memory management:

1. Private Heap:

● All Python objects and data structures are stored in a private heap,
which is managed by the Python memory manager.
● Programmers do not have direct access to this heap; instead, Python
provides constructs like variables, lists, and dictionaries to interact with
objects in memory.

2. Memory Allocation:

Python uses different layers of memory allocation:

● Object-Specific Allocators: Memory for specific objects (e.g., integers,


strings) is allocated using specialized object allocators.
Shivam Jhawar

0801IT231121

● Dynamic Allocation with PyMalloc: For general-purpose allocations,


Python uses a built-in allocator called PyMalloc, optimized for Python
objects.

3. Reference Counting:
Python uses reference counting as the primary mechanism for memory
management:

● Each object in memory has a reference count, which tracks the number
of references to that object.
● When an object's reference count drops to zero (i.e., no references to it
exist), the memory is deallocated immediately.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy