0% found this document useful (0 votes)
6 views30 pages

Python Programming Answers t

The document outlines key concepts in Python programming, including the program development cycle, decision structures, operators, repetition structures, functions, file handling, exceptions, and string methods. It provides examples and syntax for various programming constructs such as loops, conditionals, and file operations. Additionally, it discusses the differences between definite and indefinite iteration and includes a sample program for checking palindromes.

Uploaded by

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

Python Programming Answers t

The document outlines key concepts in Python programming, including the program development cycle, decision structures, operators, repetition structures, functions, file handling, exceptions, and string methods. It provides examples and syntax for various programming constructs such as loops, conditionals, and file operations. Additionally, it discusses the differences between definite and indefinite iteration and includes a sample program for checking palindromes.

Uploaded by

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

PYTHON PROGRAMMING ANSWERS

UNIT -1
1.Explain the program development cycle in Python with a
suitable example.
The Program Development Cycle in Python refers to the systematic process of writing,
testing, and maintaining a program. This process ensures that the software developed is
correct, efficient, and meets user requirements. It consists of several key steps:

🔁 Steps in the Program Development Cycle

1. Problem Definition
2. Designing the Solution
3. Writing the Code (Implementation)
4. Testing and Debugging
5. Documentation
6. Maintenance

1. Problem Definition

Understand the problem clearly:

The program should accept a non-negative integer and return its factorial.

🧠 2. Designing the Solution

Use a recursive or iterative approach to compute factorial:

 Factorial of 0 is 1.
 Factorial of n (n!) = n × (n-1) × ... × 1

Algorithm (Iterative):

 Input a number n
 Initialize fact = 1
 Loop from 1 to n and multiply fact with loop variable
 Output fact

3. Writing the Code (Implementation)


python
# Program to calculate factorial of a number
def factorial(n):
fact = 1
for i in range(1, n + 1):
fact *= i
return fact

# Input from user


num = int(input("Enter a non-negative integer: "))

if num < 0:
print("Factorial is not defined for negative numbers.")
else:
print(f"The factorial of {num} is {factorial(num)}")

🧠 4. Testing and Debugging

Test with multiple values:

 Input: 0 → Output: 1 ✅
 Input: 5 → Output: 120 ✅
 Input: -3 → Output: Error Message ✅

Fix bugs (if any) like incorrect loop bounds or condition checks.

📚 5. Documentation

Add comments and describe how the code works:

 Use # comments in Python.


 Prepare a README or user guide if needed.

🔧 6. Maintenance

After deployment:

 Modify to add recursion.


 Handle very large numbers.
 Improve user interface.

2.Discuss various decision structures in Python with syntax and


examples
In Python, decision structures (also called conditional statements) allow a program to make
choices and execute certain blocks of code based on specific conditions.

✅ Types of Decision Structures in Python

1. Simple if statement
2. if-else statement
3. if-elif-else ladder
4. Nested if statements
5. Ternary (Conditional) operator

1. 🔹 Simple if Statement

Syntax:

python
CopyEdit
if condition:
# block of code

Example:

python
CopyEdit
age = 20
if age >= 18:
print("You are eligible to vote.")

2. 🔹 if-else Statement

Used when you want to execute one block if the condition is True, and another if it’s False.

Syntax:

python
CopyEdit
if condition:
# block if true
else:
# block if false

Example:

python
CopyEdit
marks = 45
if marks >= 50:
print("Pass")
else:
print("Fail")

3. 🔹 if-elif-else Ladder

Used to check multiple conditions one by one.

Syntax:

python
if condition1:
# block1
elif condition2:
# block2
...
else:
# default block

Example:

python
num = 0

if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")

4. 🔹 Nested if Statements

An if statement inside another if block. Used for checking multiple levels of conditions.

Syntax:

python
if condition1:
if condition2:
# block

Example:

python
age = 25
citizen = True

if age >= 18:


if citizen:
print("Eligible to vote")
else:
print("Not a citizen")
else:
print("Underage")

5. 🔹 Ternary Operator (Conditional Expression)

Short form of if-else in one line.

Syntax:

python
value_if_true if condition else value_if_false

Example:

python
CopyEdit
num = 7
result = "Even" if num % 2 == 0 else "Odd"
print(result)

3.Write a Python program to calculate the running total


# Initialize total to 0

running_total = 0

# Ask the user how many numbers they want to add


n = int(input("How many numbers do you want to add? "))

# Loop to take n numbers and compute running total


for i in range(n):
num = float(input(f"Enter number {i+1}: "))
running_total += num
print(f"Running total after {i+1} numbers: {running_total}")

# Final total
print(f"\nFinal Total: {running_total}")
4.Explain different types of operators in Python with examples.
In Python, operators are special symbols used to perform operations on variables and values.

1. Arithmetic Operators

Used to perform basic mathematical operations.

Operator Description Example Output

+ Addition 10 + 5 15

- Subtraction 10 - 5 5

* Multiplication 10 * 5 50

/ Division 10 / 5 2.0

// Floor Division 10 // 3 3

% Modulus (remainder) 10 % 3 1

** Exponentiation 2 ** 3 8

✅ 2. Comparison (Relational) Operators

Used to compare two values; result is always True or False.

Operator Description Example Output

== Equal to 5 == 5 True

!= Not equal to 5 != 3 True

> Greater than 7 > 3 True

< Less than 2 < 4 True

>= Greater than or equal 5 >= 5 True

<= Less than or equal 6 <= 7 True

✅ 3. Logical Operators

Used to combine conditional statements.


Operator Description Example Output

and True if both are True True and False False

or True if at least one is True True or False True

not Reverses the result not True False

✅ 4. Assignment Operators

Used to assign values to variables.

Operator Example Equivalent To

= a = 10 Assigns 10 to a

+= a += 5 a = a + 5

-= a -= 3 a = a - 3

*= a *= 2 a = a * 2

/= a /= 4 a = a / 4

//= a //= 2 a = a // 2

%= a %= 3 a = a % 3

**= a **= 2 a = a ** 2

✅ 5. Bitwise Operators

Operate on bits (binary values).

Operator Description Example (a=5, b=3) Binary Operation Output

& AND a & b→5 & 3 0101 & 0011 = 0001 1

` ` OR `a b→5

^ XOR a ^ b→5 ^ 3 0101 ^ 0011 = 0110 6

~ NOT ~a → ~5 ~0101 = -(0101 + 1) -6

<< Left Shift a << 1 → 5 << 1 0101 → 1010 10

>> Right Shift a >> 1 → 5 >> 1 0101 → 0010 2


✅ 6. Membership Operators

Used to test if a value is present in a sequence.

Operator Description Example Output

in True if value exists 'a' in 'apple' True

not in True if value not exists 'x' not in 'apple' True

✅ 7. Identity Operators

Check whether two variables refer to the same object (not just same value).

Operator Description Example Output

is True if same object a is b True/False

is not True if not same object a is not b True/False

5.Describe repetition structures in Python with examples


In Python, repetition structures (also known as loops) are used to execute a block of code
multiple times. Python provides two main types of repetition structures:

1. for Loop

The for loop is used for iterating over a sequence (like a list, tuple, dictionary, string, or
range).

Syntax:
python
for variable in sequence:
# code block
Example:
python
CopyEdit
for i in range(5):
print("Hello", i)

Output:

Hello 0
Hello 1
Hello 2
Hello 3
Hello 4

2. while Loop

The while loop keeps executing as long as a condition is True.

Syntax:
python
while condition:
# code block
Example:
python
CopyEdit
count = 0
while count < 5:
print("Count is", count)
count += 1

Output:

Count is 0
Count is 1
Count is 2
Count is 3
Count is 4

UNIT-2
1.Explain the concept of functions in Python. How are arguments passed to functions?
1. Functions in Python

A function in Python is a reusable block of code that performs a specific task. Functions help
make programs modular, readable, and easier to maintain.

Types of Functions

 Built-in functions: Already provided by Python (e.g., print(), len(), type())


 User-defined functions: Created by users using the def keyword.

Syntax:
def function_name(parameters):
# code block
return result

2. How Arguments Are Passed to Functions


In Python, arguments are passed by object reference (also known as pass-by-assignment).
Here's how it works:

Mutable vs Immutable Objects

 Immutable objects (e.g., int, str, tuple): The function gets a copy of the reference;
changes do not affect the original.
 Mutable objects (e.g., list, dict): The function can modify the original object.

3. Types of Arguments in Functions

Python supports several types of function arguments:

 Positional arguments
 Keyword arguments
 Default arguments
 Variable-length arguments (*args, **kwargs)

2.Discuss file handling in Python with examples


File Handling in Python

File handling in Python allows you to create, read, write, and delete files. It uses built-in
functions and methods to perform these operations efficiently and safely.

Basic File Handling Modes


Mode Description

'r' Read (default). File must exist.

'w' Write. Creates a new file or overwrites.

'a' Append. Creates file if not exists.

'x' Create. Fails if file already exists.

'b' Binary mode

't' Text mode (default)

You can combine them, e.g., 'rb', 'wt'.

Common File Operations

1. Opening a File
python
file = open("example.txt", "r") # Opens file for reading

2. Reading from a File


python
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

3. Writing to a File
python
CopyEdit
file = open("example.txt", "w")
file.write("Hello, world!\n")
file.write("This is a second line.")
file.close()

3.Explain exceptions and exception handling in Python


with examples
Exceptions and Exception Handling in Python

In Python, exceptions are errors that occur during the execution of a program. When an error
occurs, Python stops the program and displays an error message unless the error is properly
handled using exception handling techniques.

What Is an Exception?

An exception is an event that disrupts the normal flow of the program.

Exception Handling Syntax


python
try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
else:
# Runs if no exception occurs
finally:
# Always runs, even if an exception occurs

✅ Example 1: Handling Division by Zero


python
try:
a = 10
b = 0
result = a / b
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
else:
print("Division successful:", result)
finally:
print("Execution completed.")

4.Write a Python program to read data from a file and


display it
# File: read_file.py

# Ask user to enter the file name


file_name = input("Enter the file name: ")

try:
# Open the file in read mode
with open(file_name, 'r') as file:
# Read the content
content = file.read()

# Display the content


print("\n--- File Content ---")
print(content)

except FileNotFoundError:
print("Error: File not found. Please check the
file name.")
except Exception as e:
print("An error occurred:", e)

6.Differentiate between definite and indefinite iteration


with examples
Difference Between Definite and Indefinite Iteration in Python

In Python, iteration refers to the process of executing a block of code repeatedly. There are
two main types of iteration:

🧠 1. Definite Iteration

Definition:
Definite iteration is when you know in advance how many times a loop will run.
✅ Typically implemented using a for loop.

🔹 Example:
python
# Print numbers from 1 to 5
for i in range(1, 6):
print(i)

🧠 2. Indefinite Iteration

Definition:
Indefinite iteration is used when the number of repetitions is not known in advance.
✅ Implemented using a while loop.

🔹 Example:
python
# Keep asking until user enters 'yes'
response = ""
while response.lower() != "yes":
response = input("Do you want to exit? (yes to stop): ")

UNIT-3
1.Explain string methods in Python with
suitable examples

String Methods in Python (with Examples)

In Python, strings are sequences of characters. Python provides many built-in string
methods that help perform common tasks like searching, replacing, formatting, checking
content, and more.

🔧 Commonly Used String Methods

✅ 1. lower() & upper()

Converts the string to lowercase or uppercase.

python
text = "Hello World"
print(text.lower()) # hello world
print(text.upper()) # HELLO WORLD
✅ 2. strip()

Removes whitespace (or specified characters) from the beginning and end.

python
msg = " Welcome! "
print(msg.strip()) # "Welcome!"

✅ 3. replace(old, new)

Replaces part of the string.

python
text = "I like Python"
print(text.replace("Python", "Java")) # I like Java

✅ 4. split(separator)

Splits a string into a list.

python
line = "apple,banana,grape"
print(line.split(",")) # ['apple', 'banana', 'grape']

✅ 5. join(list)

Joins elements of a list into a single string.

python
words = ["Python", "is", "fun"]
print(" ".join(words)) # Python is fun

✅ 6. find(substring)

Returns the index of the first occurrence of a substring; returns -1 if not found.

python
s = "hello world"
print(s.find("world")) # 6
print(s.find("Python")) # -1

✅ 7. startswith() / endswith()

Checks if the string starts or ends with a given substring.

python
s = "data.csv"
print(s.endswith(".csv")) # True
print(s.startswith("data")) # True

✅ 8. isdigit() / isalpha() / isalnum()

Checks the type of characters in the string.

python
print("123".isdigit()) # True
print("abc".isalpha()) # True
print("abc123".isalnum()) # True

✅ 9. count(substring)

Counts how many times a substring appears.

python
sentence = "banana"
print(sentence.count("a")) # 3

✅ 10. capitalize() / title()

 capitalize(): Capitalizes first letter of the string.


 title(): Capitalizes first letter of each word.

python
text = "python programming"
print(text.capitalize()) # Python programming
print(text.title()) # Python Programmings

2.Write a Python program to check whether a string is a


palindrome
def palindrome(s):
s=s.replace(“ “,””).lower()
n=len(s)
for i in range(n//2):
if s[i]!=s[n-1-i]:
return False
return True
print(palindrome(“madam”))
print(palindrome(“python”))
print(palindrome(“radar”))

3.Explain the concept of lists, tuples, and dictionaries in


Python with examples
1. List in Python

✅ Definition:

A list is an ordered, mutable (changeable) collection of items. Lists can contain elements of
different data types.

🔹 Syntax:
python
my_list = [10, 20, 30, "hello", True]

🔹 Common Operations:
python
# Accessing elements
print(my_list[0]) # 10

# Modifying elements
my_list[1] = 25

# Adding elements
my_list.append(40)

# Removing elements
my_list.remove("hello")

# Iterating through a list


for item in my_list:
print(item)
2. Tuple in Python

✅ Definition:

A tuple is an ordered, immutable (unchangeable) collection. It is like a list, but you cannot
modify its elements once defined.

🔹 Syntax:
python
my_tuple = (1, 2, 3, "apple", False)
🔹 Common Operations:
python
print(my_tuple[0]) # 1

# Iterating
for item in my_tuple:
print(item)

# Tuple unpacking
a, b, c, d, e = my_tuple
print(d)
3. Dictionary in Python

✅ Definition:

A dictionary is an unordered collection of key-value pairs. Each key must be unique and
immutable, but values can be of any type.

🔹 Syntax:
python
my_dict = {
"name": "Alice",
"age": 25,
"city": "New York"
}

🔹 Common Operations:
python
# Accessing values
print(my_dict["name"]) # Alice

# Modifying values
my_dict["age"] = 26

# Adding new key-value pair


my_dict["country"] = "USA"

# Removing key
del my_dict["city"]

# Iterating through dictionary


for key, value in my_dict.items():
print(key, ":", value)

4.Write a Python program to search an element in a list.


def search_element(lst, target):
"""
Linear‑search the target in lst.
Returns the index if found, else -1.
"""
for index, item in enumerate(lst):
if item == target:
return index
return -1

raw = input("Enter list elements separated by spaces:


")
user_list = raw.split()

element = input("Enter the element to search for: ")

position = search_element(user_list, element)

if position != -1:
print(f"Element '{element}' found at index
{position}.")
else:
print(f"Element '{element}' not found in the
list.")

5.Explain recursion in Python with suitable examples.


Recursion in Python

Recursion is a programming technique where a function calls itself to solve a smaller version
of the problem until it reaches a base case (a stopping condition).

Syntax:

def recursive_function(parameters):

if base_condition:
return result
else:
return recursive_function(smaller_problem)

Factorial:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

print(factorial(5)) # Output: 120

Fibonacci:
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)

for i in range(6):
print(fibonacci(i), end=" ") # Output: 0 1 1 2 3 5

Sum natural:
def sum_natural(n):
if n == 1:
return 1
else:
return n + sum_natural(n - 1)

print(sum_natural(5)) # Output: 15 (5+4+3+2+1)

UNIT-4
1.Explain object-oriented programming principles with
examples
OOPs (Object-Oriented Programming System) is a programming paradigm that organizes
software design around objects rather than functions and logic. An object is a real-world
entity that has state (attributes) and behavior (methods).

🧠 Four Main Concepts of OOP

1. Encapsulation
Definition: Wrapping data (variables) and code (methods) together into a single unit (class).

 Purpose: To hide internal details and protect object integrity.


 Example:

python

class Car:
def __init__(self):
self.__speed = 0 # Private variable

def set_speed(self, speed):


self.__speed = speed

def get_speed(self):
return self.__speed

2. Abstraction

Definition: Hiding complex implementation details and showing only essential features.

 Purpose: To simplify the interface for the user.


 Example:

python

from abc import ABC, abstractmethod

class Animal(ABC):
@abstractmethod
def sound(self):
pass

class Dog(Animal):
def sound(self):
return "Bark"

3. Inheritance

Definition: One class (child) inherits the properties and behaviors of another class (parent).

 Purpose: Code reusability and hierarchical classification.


 Example:

python
CopyEdit
class Animal:
def speak(self):
print("Animal speaks")

class Dog(Animal):
def bark(self):
print("Dog barks")
4. Polymorphism

Definition: One interface, many implementations. The same method behaves differently
based on the object.

 Purpose: Flexibility and scalability.


 Types:
o Compile-time (method overloading — not directly supported in Python)
o Runtime (method overriding)
 Example:

python
CopyEdit
class Animal:
def sound(self):
print("Some sound")

class Cat(Animal):
def sound(self):
print("Meow")

class Dog(Animal):
def sound(self):
print("Bark")

for animal in [Cat(), Dog()]:


animal.sound() # Output: Meow, Bark

2.Describe how classes and objects are created in Python.


Classes and Objects in Python

In Python, classes and objects are fundamental to object-oriented programming (OOP).


They allow you to model real-world things using code by bundling data and behavior
together.

🧠 What is a Class?

A class is like a blueprint or template for creating objects.


It defines:

 Attributes (variables)
 Methods (functions that belong to the class)

✅ Creating a Class:
python
class Person:
def __init__(self, name, age): # Constructor method
self.name = name # Instance variable
self.age = age

def greet(self): # Method


print(f"Hello, my name is {self.name} and I am {self.age} years
old.")

🧠 What is an Object?

An object is an instance of a class — a real, usable version of the blueprint.

✅ Creating an Object:
python
# Create an object of the Person class
p1 = Person("Alice", 25)

# Accessing attributes and methods


print(p1.name) # Output: Alice
print(p1.age) # Output: 25
p1.greet() # Output: Hello, my name is Alice and I am 25 years
old.
3.Explain inheritance and polymorphism in Python with
suitable examples.
1. Inheritance

Definition:
Inheritance allows a class (child class) to acquire the properties and methods of another class
(parent class).

This helps in code reuse and building hierarchies.

✅ Example: Inheritance
python
# Parent class
class Animal:
def speak(self):
print("This animal makes a sound.")

# Child class
class Dog(Animal):
def bark(self):
print("The dog barks.")

# Create object of Dog


d = Dog()
d.speak() # Inherited from Animal
d.bark() # Defined in Dog

✅ Types of Inheritance in Python:

 Single Inheritance (one parent → one child)


 Multiple Inheritance (multiple parents → one child)
 Multilevel Inheritance (grandparent → parent → child)
 Hierarchical Inheritance (one parent → many children)

🌀 2. Polymorphism

Definition:
Polymorphism means “many forms.” It allows different classes to have methods with the
same name but different behaviors.

✅ Example: Polymorphism via Method Overriding


python
class Animal:
def speak(self):
print("Animal speaks")

class Cat(Animal):
def speak(self):
print("Meow")

class Dog(Animal):
def speak(self):
print("Woof")

# Polymorphism in action
def make_sound(animal):
animal.speak()

a = Animal()
c = Cat()
d = Dog()

make_sound(a) # Animal speaks


make_sound(c) # Meow
make_sound(d) # Woof
4.Write a Python program to implement multiple
inheritance.
# Parent Class 1
class Father:
def skills(self):
print("Father: Gardening, Programming")

# Parent Class 2
class Mother:
def skills(self):
print("Mother: Cooking, Painting")

# Child Class inherits from both Father and Mother


class Child(Father, Mother):
def skills(self):
print("Child: Sports")
# Call skills of Father and Mother using class name
Father.skills(self)
Mother.skills(self)

# Create object of Child class


c = Child()
c.skills()

5.Differentiate between procedural and object-oriented


programming
OOP (Object-Oriented POP (Procedure-Oriented
Feature
Programming) Programming)
Approach Based on objects and classes Based on functions and procedures
Focuses on data and how to Focuses on functions and the sequence
Focus
protect it of tasks
Encapsulation: Data is hidden Data is global or shared and less
Data Handling
and protected protected
Program is divided into objects Program is divided into functions
Modularity
(modules) (steps)
OOP (Object-Oriented POP (Procedure-Oriented
Feature
Programming) Programming)
Code Limited code reusability;
Achieved using Inheritance
Reusability copying/modifying functions
High – Uses encapsulation and
Security Low – Data is accessible globally
access control
Java, Python (OOP), C++, C#, C, Pascal, Fortran, COBOL
Examples
Ruby

UNIT-5
1.Explain the features of tkinter and how GUI programs
are created.
Tkinter is Python’s standard library for creating Graphical User Interfaces (GUIs)
What is Tkinter?

Tkinter is a built-in Python module that provides tools to create windows, buttons, labels,
input fields, menus, and more — all with event handling.

python
import tkinter as tk
How GUI Programs are Created Using Tkinter

✅ Basic Steps:

1. Import Tkinter module


2. Create a main window
3. Add widgets (buttons, labels, etc.)
4. Set layout using pack/grid/place
5. Run the GUI with the main loop

import tkinter as tk

from tkinter import messagebox

def show_selection():

selected = choice.get()

messagebox.showinfo("Selected Option", f"You selected: {selected}")

# Create main window


root = tk.Tk()

root.title("Radio Button Example")

root.geometry("300x200")

# Label

tk.Label(root, text="Choose your favorite color:", font=("Arial", 12)).pack(pady=10)

# StringVar to hold the value of selected radio button

choice = tk.StringVar()

choice.set("Red") # Default value

# Radio Buttons

tk.Radiobutton(root, text="Red", variable=choice, value="Red").pack()

tk.Radiobutton(root, text="Blue", variable=choice, value="Blue").pack()

tk.Radiobutton(root, text="Green", variable=choice, value="Green").pack()

# Submit Button

tk.Button(root, text="Submit", command=show_selection).pack(pady=10)

# Run the GUI

root.mainloop()

2.Write a Python program to design a login window using


tkinter.
import tkinter as tk
from tkinter import messagebox

# Predefined username and password (you can customize this)


USERNAME = "admin"
PASSWORD = "1234"

# Function to validate login


def login():
user = username_entry.get()
pwd = password_entry.get()
if user == USERNAME and pwd == PASSWORD:
messagebox.showinfo("Login Success", "Welcome, Admin!")
else:
messagebox.showerror("Login Failed", "Invalid username or password.")

# Create main window


root = tk.Tk()
root.title("Login Window")
root.geometry("300x200")
root.resizable(False, False)

# Username label and entry


tk.Label(root, text="Username:").pack(pady=5)
username_entry = tk.Entry(root)
username_entry.pack()

# Password label and entry


tk.Label(root, text="Password:").pack(pady=5)
password_entry = tk.Entry(root, show="*")
password_entry.pack()

# Login button
tk.Button(root, text="Login", command=login).pack(pady=15)

# Run the GUI loop


root.mainloop()

3.Explain various widgets in tkinter with examples.


Widgets are the building blocks of GUI applications in Tkinter. Each widget serves a specific purpose
like displaying text, taking input, or creating buttons and menus.

1. Label
python
ssstk.Label(root, text="Welcome to Tkinter").pack()

✅ 2. Entry (Single-line Input)


python
entry = tk.Entry(root)
entry.pack()

✅ 3. Button
python
def say_hello():
print("Hello!")
tk.Button(root, text="Click Me", command=say_hello).pack()

✅ 4. Checkbutton
python
var = tk.IntVar()
tk.Checkbutton(root, text="Accept Terms", variable=var).pack()

✅ 5. Radiobutton
python
gender = tk.StringVar()
tk.Radiobutton(root, text="Male", variable=gender, value="Male").pack()
tk.Radiobutton(root, text="Female", variable=gender, value="Female").pack()

✅ 6. Listbox
python
listbox = tk.Listbox(root)
listbox.insert(1, "Python")
listbox.insert(2, "Java")
listbox.pack()

✅ 7. Text (Multi-line Input)


python
text = tk.Text(root, height=5, width=30)
text.pack()

✅ 8. Frame (for grouping widgets)


python
frame = tk.Frame(root)
frame.pack()
tk.Label(frame, text="Inside Frame").pack()

✅ 9. Canvas (Drawing)
python
canvas = tk.Canvas(root, width=100, height=100)
canvas.create_oval(10, 10, 90, 90, fill="blue")
canvas.pack()

✅ 10. Menu
python
menu = tk.Menu(root)
root.config(menu=menu)
file_menu = tk.Menu(menu)
menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="Open")
file_menu.add_command(label="Exit", command=root.quit)
4.Explain turtle graphics and write a program to draw a
star.
Turtle Graphics in Python

Turtle is a built-in Python module used for drawing shapes, patterns, and designs using a
virtual pen (turtle) that moves on the screen.

It's great for learning programming and geometry through visuals.

import turtle

# Set up the screen


screen = turtle.Screen()
screen.bgcolor("white")

# Create turtle
star = turtle.Turtle()
star.color("blue")
star.pensize(2)
star.speed(3)

# Draw a 5-pointed star


for i in range(5):
star.forward(100)
star.right(144)

# Hide turtle and display window


star.hideturtle()
screen.mainloop()
5. Discuss the concept of image processing with simple
examples in Python.

Image Processing in Python

Image Processing is the technique of performing operations on an image to:

 Enhance it
 Extract useful information
 Convert or manipulate its structure (size, color, format, etc.)

1.Using Pillow (PIL) — Simple & Beginner-Friendly

🔹 Installation:
bash
pip install Pillow

🔹 Example: Open and Show an Image


python
from PIL import Image

# Open an image
img = Image.open("example.jpg")

# Show the image


img.show()
2. Using OpenCV (Advanced)

🔹 Installation:
bash
pip install opencv-python

🔹 Example: Read and Display Image


python
import cv2

# Read the image


img = cv2.imread("example.jpg")

# Show image in a window


cv2.imshow("My Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

You might also like