0% found this document useful (0 votes)
0 views

Python Assignment 2

The document explains geometry management methods in Tkinter, including pack(), grid(), and place(), with examples for each method. It also describes Django's MVT architecture, detailing the Model, View, and Template components. Additionally, it covers multithreading concepts, NumPy operations, and Pandas data structures, providing examples for each topic.

Uploaded by

aryanrasam01
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Python Assignment 2

The document explains geometry management methods in Tkinter, including pack(), grid(), and place(), with examples for each method. It also describes Django's MVT architecture, detailing the Model, View, and Template components. Additionally, it covers multithreading concepts, NumPy operations, and Pandas data structures, providing examples for each topic.

Uploaded by

aryanrasam01
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

1.​ Explain the geometry methods provided by Tkinter with example.

Ans:
Tkinter provides several geometry management methods to organize widgets within a
window or frame. The three main geometry managers are:
1.​ pack()
2.​ grid()
3.​ place()
Each has its own strengths and use cases. Let's explore each with examples.

1. pack() Method

The pack() method organizes widgets in blocks before placing them in the parent
widget.
Example:
import tkinter as tk

root = tk.Tk()
root.title("Pack Example")

# Create widgets
label1 = tk.Label(root, text="Top", bg="red", fg="white")
label2 = tk.Label(root, text="Bottom", bg="green", fg="white")
label3 = tk.Label(root, text="Left", bg="blue", fg="white")
label4 = tk.Label(root, text="Right", bg="yellow", fg="black")

# Pack widgets
label1.pack(side="top", fill="x", padx=10, pady=5)
label2.pack(side="bottom", fill="x", padx=10, pady=5)
label3.pack(side="left", fill="y", padx=5, pady=10)
label4.pack(side="right", fill="y", padx=5, pady=10)

root.mainloop()

Common pack() options:

●​ side: "top", "bottom", "left", or "right" (default is "top")


●​ fill: "x", "y", "both", or "none" (to expand widget)
●​ expand: True/False (to use extra space)
●​ padx, pady: External padding
●​ ipadx, ipady: Internal padding
2. grid() Method

The grid() method organizes widgets in a table-like structure with rows and columns.

Example:

import tkinter as tk

root = tk.Tk()
root.title("Grid Example")

# Create widgets
label1 = tk.Label(root, text="Row 0, Column 0", bg="red", fg="white")
label2 = tk.Label(root, text="Row 0, Column 1", bg="green", fg="white")
label3 = tk.Label(root, text="Row 1, Column 0", bg="blue", fg="white")
label4 = tk.Label(root, text="Row 1, Column 1", bg="yellow", fg="black")

# Place widgets using grid


label1.grid(row=0, column=0, padx=5, pady=5)
label2.grid(row=0, column=1, padx=5, pady=5)
label3.grid(row=1, column=0, padx=5, pady=5)
label4.grid(row=1, column=1, padx=5, pady=5)

# Configure column and row weights


root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=1)
root.rowconfigure(0, weight=1)
root.rowconfigure(1, weight=1)

root.mainloop()

Common grid() options:

●​ row, column: Position in grid


●​ rowspan, columnspan: How many rows/columns widget occupies
●​ sticky: "n", "s", "e", "w", or combinations (like "nsew") to stick to sides
●​ padx, pady: Padding
●​ ipadx, ipady: Internal padding
3. place() Method

The place() method places widgets at absolute or relative positions.

Example:

import tkinter as tk

root = tk.Tk()
root.title("Place Example")
root.geometry("300x200")

# Absolute positioning
label1 = tk.Label(root, text="Absolute: 50, 50", bg="red", fg="white")
label1.place(x=50, y=50)

# Relative positioning
label2 = tk.Label(root, text="Relative: 0.5, 0.5", bg="green", fg="white")
label2.place(relx=0.5, rely=0.5, anchor="center")

# Mixed positioning with size


label3 = tk.Label(root, text="Mixed", bg="blue", fg="white")
label3.place(relx=0.2, rely=0.8, width=100, height=30)

root.mainloop()

Common place() options:

●​ x, y: Absolute coordinates
●​ relx, rely: Relative coordinates (0.0 to 1.0)
●​ anchor: Position reference point ("n", "s", "e", "w", "center", etc.)
●​ width, height: Absolute size
●​ relwidth, relheight: Relative size (0.0 to 1.0)

2. Explain Django’s architecture.


Ans:
Django follows the Model-View-Template (MVT) architecture, a variation of the classic
Model-View-Controller (MVC) pattern. It separates concerns for better maintainability
and scalability.
1. Model (Data Layer)

●​ Represents the database structure (tables, fields, relationships).


●​ Uses Django’s ORM (Object-Relational Mapper) to interact with the database
without writing raw SQL.
●​ Defined in models.py.
●​ Example:
from django.db import models

class Blog(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()

2. View (Business Logic Layer)

●​ Handles HTTP requests, processes data, and returns responses.


●​ Connects Models (database) and Templates (UI).
●​ Defined in views.py.
●​ Example:
from django.shortcuts import render
from .models import Blog

def blog_list(request):
blogs = Blog.objects.all()
return render(request, 'blog/list.html', {'blogs': blogs})

3. Template (Presentation Layer)

●​ HTML files with Django’s template language for dynamic content.


●​ Renders data from Views.
●​ Stored in the templates/ directory.
●​ Example (list.html):
<h1>Blog Posts</h1>
<ul>
{% for blog in blogs %}
<li>{{ blog.title }}</li>
{% endfor %}
</ul>
3. Could you provide an example of a real-world situation where
multithreading would be Beneficial?
Ans:

Scenario:
Imagine a restaurant (web server) where:
●​ Each customer (client) places an order (HTTP request).
●​ The chef (CPU) prepares meals (processes requests).
Without Multithreading (Single-Threaded):
●​ The chef takes one order at a time → Other customers wait idle → Slow service.
With Multithreading:
●​ The chef delegates tasks to multiple assistants (threads).
●​ While one assistant cooks, another can take new orders → Faster service.

4. How we can get current thread name and how to change default
thread name in multithreading.
Ans :

1. Getting the Current Thread Name


Use threading.current_thread().name:
import threading

def task():
print(f"Current thread name: {threading.current_thread().name}")

thread = threading.Thread(target=task)
thread.start()
thread.join()

Output :
Current thread name: Thread-1 # Default naming (Thread-1, Thread-2, etc.)

2. Changing the Default Thread Name


Set a custom name using the name parameter when creating the thread:
import threading

def task():
print(f"Thread name: {threading.current_thread().name}")
# Assign a custom name
thread = threading.Thread(target=task, name="Worker-Thread")
thread.start()
thread.join()

Output :
Thread name: Worker-Thread # Custom name instead of Thread-1

3. Renaming a Thread After Creation


Modify thread.name dynamically:
import threading

def task():
threading.current_thread().name = "Renamed-Thread"
print(f"Updated thread name: {threading.current_thread().name}")

thread = threading.Thread(target=task)
thread.start()
thread.join()

Output:
Updated thread name: Renamed-Thread

5. What is NumPy? Explain NumPy basic operations with example?


Ans:
NumPy (Numerical Python) is a powerful library for numerical computing in Python. It
provides:
●​ Multidimensional arrays (ndarrays) for fast mathematical operations.
●​ Mathematical functions (linear algebra, statistics, Fourier transforms).
●​ Efficiency (written in C, optimized for performance).

Basic NumPy Operations with Examples

1. Creating Arrays
import numpy as np

# From a list
arr1 = np.array([1, 2, 3]) # 1D array
arr2 = np.array([[1, 2], [3, 4]]) # 2D array

# Special arrays
zeros = np.zeros((2, 3)) # 2x3 array of 0s
ones = np.ones((3, 2)) # 3x2 array of 1s
range_arr = np.arange(0, 10, 2) # Array [0, 2, 4, 6, 8]

2. Array Operations (Element-wise)


a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

print(a + b) # [5, 7, 9] (Addition)


print(a * 2) # [2, 4, 6] (Scalar multiplication)
print(np.sum(a)) # 6 (Sum of all elements)

3. Reshaping Arrays
arr = np.arange(6) # [0, 1, 2, 3, 4, 5]
reshaped = arr.reshape((2, 3)) # Converts to 2x3 matrix

4. Indexing & Slicing


arr = np.array([[1, 2, 3], [4, 5, 6]])

print(arr[1, 2]) # 6 (Row 1, Column 2)


print(arr[:, 1:3]) # Slices all rows, columns 1-2 → [[2, 3], [5, 6]]

5. Statistical Operations
data = np.array([1, 2, 3, 4, 5])

print(np.mean(data)) # 3.0 (Average)


print(np.max(data)) # 5 (Maximum value)
print(np.std(data)) # 1.414 (Standard deviation)

6. Matrix Multiplication
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])

print(np.dot(A, B)) # [[19, 22], [43, 50]]


6. What are Pandas? Explain different types of data structure in
pandas?
Ans:
Pandas is a powerful open-source Python library for data manipulation and analysis. It
provides easy-to-use data structures and functions for working with structured (tabular,
time-series, and matrix) data. It is built on top of NumPy and is widely used in data
science, machine learning, and financial analysis.

Key Data Structures in Pandas

Pandas primarily provides two data structures:


1.​ Series (1-dimensional)
2.​ DataFrame (2-dimensional, most commonly used)

1. Series (1D Data Structure)

●​ Similar to a NumPy array, but with index labels.


●​ Can hold any data type (int, float, string, Python objects, etc.).
●​ Used for single-column data.

Example: Creating a Series


import pandas as pd

# Create a Series from a list


data = [10, 20, 30, 40]
series = pd.Series(data, index=['a', 'b', 'c', 'd'])

print(series)

Output:

a 10
b 20
c 30
d 40
dtype: int64

Key Features of Series:


●​ Indexing & Slicing: series['a'] → 10
●​ Mathematical Operations: series * 2 → Multiplies each element by 2.
●​ Missing Data Handling: pd.Series([1, None, 3]) → Automatically handles NaN.

2. DataFrame (2D Data Structure)

●​ Similar to a spreadsheet or SQL table.


●​ Consists of rows and columns (like an Excel sheet).
●​ Each column is a Pandas Series.

Example: Creating a DataFrame

data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'London', 'Tokyo']
}

df = pd.DataFrame(data)

print(df)

Output :
Name Age City
0 Alice 25 New York
1 Bob 30 London
2 Charlie 35 Tokyo

Key Features of DataFrames:


●​ Column Selection: df['Name'] → Returns a Series.
●​ Row Selection: df.loc[0] → Returns the first row.
●​ Filtering: df[df['Age'] > 30] → Filters rows where Age > 30.
●​ Aggregation: df.mean(), df.sum(), df.describe() → Statistical summaries.

You might also like