Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
3 views16 pages

Python 2

Uploaded by

Grunesh Karande
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views16 pages

Python 2

Uploaded by

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

📘 Section B: Python 5-Mark Questions

1)Explain the main features of Python and how they contribute to its
popularity in different domains with examples.

1. Simple & Readable Syntax- Lowers the learning curve, improves


collaboration, and reduces bugs.
2. Interpreted Language- Faster prototyping, easier debugging.
3. Dynamically Typed- Speeds up development, especially for small
teams.
4. Cross-Platform Compatibility- Saves time in deployment and testing.
5. Large Standard Library- Reduces dependency on external packages.
6. Extensive Third-Party Ecosystem- Enables specialized work without
reinventing the wheel.
7. Object-Oriented & Multi-Paradigm- Flexibility for different project
needs.
8. Open Source & Free- Encourages community growth and innovation.
9. Strong Community Support- Easier troubleshooting and learning.
10. GUI Programming Support -Enables desktop app development.

Popularity Across Domains

1. Data Science & Machine Learning


- Why Python wins: Libraries like NumPy, Pandas, scikit-learn,
TensorFlow, and PyTorch make it a one-stop shop for analytics and AI.
- Example: Netflix uses Python for recommendation algorithms and
data analysis.

2. Web Development
- Why Python wins: Frameworks like Django and Flask allow rapid,
secure, and scalable web app development.
- Example: Instagram’s backend is powered by Django.

3. Automation & Scripting


- Why Python wins: Simple syntax + cross-platform compatibility make
it perfect for automating repetitive tasks.
- Example: IT teams use Python scripts to auto-generate reports or
manage servers.
4. Scientific Computing
- Why Python wins: Integration with SciPy, Matplotlib, and Jupyter
notebooks for research workflows.
- Example: NASA uses Python for space mission data analysis.

5. Game Development
- Why Python wins: Libraries like Pygame make prototyping easy.
- Example: Indie developers use Python to quickly test game
mechanics.

6. IoT (Internet of Things)


- Why Python wins: Lightweight and runs on microcontrollers via
MicroPython.
- Example: Raspberry Pi projects for home automation.

2)Discuss at least four real-world applications of Python, mentioning key


frameworks/libraries.

Web Development:

Clean syntax, rapid development, and powerful frameworks.

Key Frameworks/Libraries:

- Django – Full-stack framework with built-in authentication, ORM, and admin


panel.

- Flask – Lightweight, flexible microframework for smaller or highly


customized apps.

- FastAPI – High-performance API framework for modern web services.

Example:

- Pinterest and Dropbox also rely on Python for backend services.

2️⃣ Data Science & Analytics

Why Python works here: Rich ecosystem for data manipulation, analysis, and
visualization.

Key Frameworks/Libraries:
- Pandas – Data manipulation and analysis.

- NumPy – Numerical computing.

- Matplotlib / Seaborn – Data visualization.

Example:

- YouTube applies Python for video recommendation algorithms.

---

3️⃣ Artificial Intelligence & Machine Learning

Why Python works here: Simple syntax + powerful ML/AI libraries = faster
experimentation and deployment.

Key Frameworks/Libraries:

- TensorFlow – Deep learning framework by Google.

- PyTorch – Flexible deep learning library by Meta.

- scikit-learn – Machine learning for classification, regression, clustering, etc.

Example:

- Google applies TensorFlow for image recognition and NLP tasks.

4️⃣ Automation & Scripting ⚙️

Why Python works here: Easy to write, cross-platform, and great for
repetitive task automation.

Key Frameworks/Libraries:

- Selenium – Automates web browsers for testing or scraping.

- BeautifulSoup – Parses HTML/XML for web scraping.

- PyAutoGUI – Automates mouse and keyboard actions.

Example:

- Spotify uses Python automation for backend processes and playlist


curation.
3) IDLE, Jupyter Notebook, and VS Code for Python development with
examples.

IDLE (Integrated Development and Learning Environment)

- Comes bundled with Python installation — no extra setup needed.

- Lightweight, simple, and great for beginners.

- Has an interactive shell for running Python code line-by-line.

Best for:

- Learning Python basics.

- Quick testing of small code snippets.

Example:

In IDLE’s interactive shell

>>> name = “Grunesh”

>>> print(f”Hello, {name}!”)

Hello, Grunesh!

2. Jupyter Notebook

What it is:

- A web-based interactive environment for combining code, text, and


visualizations.

- Popular in data science, machine learning, and research.

- Supports Markdown for documentation alongside executable code cells.

Best for:

- Data analysis and visualization.


- Step-by-step tutorials or reports.

- Prototyping ML models.

Example:

In a Jupyter Notebook cell

Import numpy as np

Import matplotlib.pyplot as plt

X = np.linspace(0, 10, 100)

Y = np.sin(x)

Plt.plot(x, y, label=’sin(x)’)

Plt.xlabel(‘x’)

Plt.ylabel(‘sin(x)’)

Plt.title(‘Sine Wave’)

Plt.legend()

Plt.show()

3. Visual Studio Code (VS Code)

What it is:

- A full-featured code editor with extensions for Python, Git integration,


debugging, and more.

- Highly customizable with themes, plugins, and settings.

- Supports Jupyter Notebooks inside VS Code for a hybrid workflow.

Best for:

- Large-scale application development.

- Working with multiple files and frameworks.

- Debugging complex projects.


Example:

- Or, open a .ipynb notebook directly in VS Code to run data analysis without
leaving the editor.

4)Explain Python data types with examples and discuss pros & cons of
dynamic typing.

Numeric

int - Whole numbers (positive, negative, zero) eg. age = 25

float- Decimal numbers or scientific notation eg. pi = 3.14

complex -Numbers with real & imaginary parts eg. z = 2 + 3j

Text

str - Sequence of Unicode characters eg name = "Grunesh"

Boolean

-bool | Logical values True or False eg. is_active = True

None Type

NoneType | Represents “no value” eg. result = None

Sequence

- list - Ordered, mutable collection eg. fruits = ["apple", "banana"]

tuple -Ordered, immutable collection eg.b coords = (10.5, 20.3)

Types –

set- Unordered, mutable, unique elements eg. colors = {"red", "green"}

Mapping

dict - Key-value pairs | student = {"name": "Asha", "age": 21}

Advantages of Dynamic Typing

1. Flexibility & Speed – No need to declare types; great for rapid prototyping.
2. Less Boilerplate – Cleaner, shorter code.

3. Handles Unknown Data Easily – Useful when working with JSON, APIs, or
user input.

4. Great for Scripting – Perfect for automation and quick experiments.

Disadvantages of Dynamic Typing

1. Runtime Errors – Type mismatches are caught only when the code runs,
not at compile time.

2. Performance Overhead – Type checks happen at runtime, which can slow


execution.

3. Less Predictable – Variables can change type unexpectedly, making


debugging harder.

4. Maintainability Issues – Large projects may become error-prone without


type hints.

5)Explain Python operators with examples and discuss operator precedence.


6)Write a program to find the largest of three numbers and explain it.

# Program to find the largest of three numbers

# Input from the user

Num1 = float(input(“Enter first number: “))

Num2 = float(input(“Enter second number: “))

Num3 = float(input(“Enter third number: “))

# Compare the numbers

If (num1 >= num2) and (num1 >= num3):

Largest = num1

Elif (num2 >= num1) and (num2 >= num3):

Largest = num2

Else:

Largest = num3

# Display the result


Print(“The largest number is:”, largest)

1. User Input

- We use input() to get three numbers from the user.

- float() is used so the program works for both integers and decimal
numbers.

2. Comparison Logic

- First if condition: Checks if num1 is greater than or equal to both num2


and num3.

- elif condition: If the first condition is false, it checks if num2 is greater


than or equal to both num1 and num3.

- else block: If neither of the above is true, num3 must be the largest.

3. Output

- The variable largest stores the biggest number, which is then printed.

7)Differentiate between for and while loops with examples and scenarios.

For loop

A for loop is used when you already know how many times you want to
repeat something, or when you want to go through each item in a sequence
like a list, string, or range.

It automatically moves to the next item until the sequence is finished.

Example:

Print numbers from 1 to 5

For num in range(1, 6):

Print(num)

Scenario:

- Sending an email to each student in a list.


- Processing each line in a file.

- Running a loop exactly 10 times to simulate dice rolls.

While loop

A while loop is used when you don’t know in advance how many times you’ll
need to repeat something.

It keeps running as long as a condition is true. You must make sure


something inside the loop changes the condition, or it will run forever.

Example:

Keep asking until the user enters the correct password

Password = “”

While password != “python123”:

Password = input(“Enter password: “)

Print(“Access granted!”).

Scenario:

- Waiting for a sensor reading to reach a certain value.

- Running a game loop until the player quits.

- Continuously reading data from a live feed until a stop signal is received.

8) break, continue, and pass in loops with a suitable program.

Break

- Purpose: Immediately exits the loop, regardless of the loop condition or


remaining iterations.

- When to use: When you’ve found what you’re looking for and don’t need to
continue looping.
2 continue
2️⃣

- Purpose: Skips the rest of the current iteration and moves to the next
iteration of the loop.

- When to use: When you want to ignore certain cases but keep looping.

3 pass
3️⃣

- Purpose: A placeholder statement that does nothing — used when a


statement is syntactically required but you don’t want to execute any code
yet.

- When to use: When you’re writing code structure but haven’t implemented
logic yet.

🖥 Example Program

# Demonstrating break, continue, and pass

Numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

For num in numbers:

If num == 3:

Print(“Encountered 3 → using pass (do nothing)”)

Pass # Placeholder, does nothing

Elif num == 5:

Print(“Encountered 5 → using continue (skip this iteration)”)

Continue # Skip printing 5

Elif num == 8:

Print(“Encountered 8 → using break (exit loop)”)


Break # Exit the loop completely

Print(“Processing number:”, num).

Print(“Loop ended.”)

9)Explain scope & lifetime of variables in Python with examples and discuss
the LEGB rule.

1. Scope – where a variable can be accessed.

2. Lifetime – how long a variable exists in memory.

3. LEGB Rule – the order Python follows to find a variable’s value.

1 Scope in Python
1️⃣

Scope defines the region of the program where a variable is visible and can
be used.

- Local Scope – Variables created inside a function. Accessible only within


that function.

- Enclosing Scope – Variables in the outer function of a nested function.


Accessible to the inner function.

- Global Scope – Variables created outside any function. Accessible anywhere


in the file.

- Built-in Scope – Names pre-defined by Python (e.g., len, print).

Example:
X = “global variable” # Global scope

Def outer():

Y = “enclosing variable” # Enclosing scope

Def inner():

Z = “local variable” # Local scope

Print(z) # Access local

Print(y) # Access enclosing

Print(x) # Access global

Inner()

Outer()

2️⃣Lifetime of Variables

Lifetime refers to how long a variable stays in memory.

- Local variables: Created when the function starts, destroyed when the
function ends.

- Global variables: Exist for the entire program runtime.

- Enclosing variables: Exist as long as the outer function is active.

- Built-in names: Always available while Python is running.

Example:

Def demo():

A = 10 # Local variable

Print(a) # Exists only while demo() runs

Demo()

Print(a) # ❌ Error: a is not defined

3️⃣The LEGB Rule

When Python sees a variable name, it searches in this order:


1. L – Local: Inside the current function.

2. E – Enclosing: In the local scope of any enclosing (outer) functions.

3. G – Global: At the top level of the script/module.

4. B – Built-in: Python’s built-in names.

Example:

X = “global”

Def outer():

X = “enclosing”

Def inner():

X = “local”

Print(x) # Local wins

Inner()

Outer()

10)Write a program to read space-separated marks, calculate average, and


print ‘Pass’/’Fail’.

# Program to read space-separated marks, calculate average, and print


Pass/Fail

# Read marks from the user as space-separated values

marks = list(map(float, input("Enter marks separated by spaces: ").split()))

# Calculate average

average = sum(marks) / len(marks)

# Decide pass or fail (assuming pass mark is 40)

if average >= 40:

print(f"Average: {average:.2f} → Pass")


else:

print(f"Average: {average:.2f} → Fail")

1. Input Handling

- input() reads the entire line of marks as a string.

- .split() breaks it into a list of strings.

- map(float, ...) converts each string to a number.

- list(...) stores them in a list called marks.

2. Average Calculation

- sum(marks) adds all marks.

- len(marks) gives the number of subjects.

- Division gives the average.

3. Pass/Fail Decision

- If average >= 40, print Pass.

- Otherwise, print Fail.

- 2f formats the average to 2 decimal places.

You might also like