Skip to main content
  1. Resources/
  2. Study Materials/
  3. Information Technology Engineering/
  4. IT Semester 2/

Advanced Python Programming (4321602) - Summer 2024 Solution

17 mins· ·
Study-Material Solutions Python 4321602 2024 Summer
Milav Dabgar
Author
Milav Dabgar
Experienced lecturer in the electrical and electronic manufacturing industry. Skilled in Embedded Systems, Image Processing, Data Science, MATLAB, Python, STM32. Strong education professional with a Master’s degree in Communication Systems Engineering from L.D. College of Engineering - Ahmedabad.
Table of Contents

Question 1(a) [3 marks]
#

Give the difference between Tuple and List in python.

Answer:

FeatureTupleList
MutabilityImmutable (cannot be changed)Mutable (can be changed)
SyntaxCreated using ()Created using []
PerformanceFasterSlower
MethodsLimited methods (count, index)Many methods (append, remove, etc.)
  • Memory efficient: Tuples use less memory than lists
  • Use case: Tuples for fixed data, lists for dynamic data

Mnemonic: “Tuples are Tight, Lists are Loose”


Question 1(b) [4 marks]
#

Define Set and how is it created in python?

Answer:

Set is an unordered collection of unique elements in Python.

Creating Sets:

# Empty set
my_set = set()

# Set with elements
fruits = {"apple", "banana", "orange"}

# From list
numbers = set([1, 2, 3, 4])
  • Unique elements: No duplicates allowed
  • Unordered: Elements have no specific order
  • Operations: Union, intersection, difference supported

Mnemonic: “Sets are Special - Unique and Unordered”


Question 1(c) [7 marks]
#

What is Dictionary in Python? Write a program to concatenate two dictionary into new one.

Answer:

Dictionary is an ordered collection of key-value pairs in Python.

Program:

# Two dictionaries
dict1 = {1: 10, 2: 20}
dict2 = {3: 30, 4: 40}

# Method 1: Using update()
result1 = dict1.copy()
result1.update(dict2)

# Method 2: Using ** operator
result2 = {**dict1, **dict2}

print("Result:", result2)
# Output: {1: 10, 2: 20, 3: 30, 4: 40}
  • Key-value pairs: Each element has a key and value
  • Mutable: Can be modified after creation
  • Fast access: O(1) average time complexity

Mnemonic: “Dictionaries are Dynamic Key-Value stores”


Question 1(c) OR [7 marks]
#

What is a list in python? Write a program that finds maximum and minimum numbers from a list.

Answer:

List is an ordered, mutable collection of elements in Python.

Program:

# Input list
numbers = [45, 12, 78, 23, 56, 89, 34]

# Find maximum and minimum
maximum = max(numbers)
minimum = min(numbers)

print(f"Maximum: {maximum}")
print(f"Minimum: {minimum}")

# Manual method
max_val = numbers[0]
min_val = numbers[0]
for num in numbers:
    if num > max_val:
        max_val = num
    if num < min_val:
        min_val = num
  • Ordered: Elements maintain insertion order
  • Indexing: Accessed using index [0, 1, 2…]
  • Built-in functions: min(), max(), len() available

Mnemonic: “Lists are Linear and Indexed”


Question 2(a) [3 marks]
#

Explain Nested Tuple with example.

Answer:

Nested Tuple is a tuple containing other tuples as elements.

Example:

# Nested tuple
student_data = (
    ("John", 85, "A"),
    ("Alice", 92, "A+"),
    ("Bob", 78, "B")
)

# Accessing elements
print(student_data[0][1])  # Output: 85
print(student_data[1][0])  # Output: Alice
  • Multi-dimensional: Tuples within tuples
  • Indexing: Use multiple indices [i][j]
  • Immutable: Cannot change nested elements

Mnemonic: “Nested means Tuples inside Tuples”


Question 2(b) [4 marks]
#

What is random module? Explain with example.

Answer:

Random module generates random numbers and performs random operations.

Example:

import random

# Random integer
num = random.randint(1, 10)
print(f"Random number: {num}")

# Random choice from list
colors = ["red", "blue", "green"]
choice = random.choice(colors)
print(f"Random color: {choice}")

# Random float
decimal = random.random()
print(f"Random decimal: {decimal}")
  • Import required: import random
  • Various functions: randint(), choice(), random()
  • Useful for: Games, simulations, testing

Mnemonic: “Random makes things Unpredictable”


Question 2(c) [7 marks]
#

Explain different ways of importing package. Give one example of it.

Answer:

Import Methods:

MethodSyntaxUsage
Normal importimport packagepackage.function()
From importfrom package import functionfunction()
Import allfrom package import *function()
Alias importimport package as aliasalias.function()

Example:

# Normal import
import math
result1 = math.sqrt(16)

# From import
from math import sqrt
result2 = sqrt(16)

# Import with alias
import math as m
result3 = m.sqrt(16)

# Import all (not recommended)
from math import *
result4 = sqrt(16)
  • Namespace: Normal import keeps separate namespace
  • Direct access: From import allows direct function call
  • Alias: Shorter names for convenience

Mnemonic: “Import methods: Normal, From, All, Alias”


Question 2(a) OR [3 marks]
#

Write down the properties of dictionary in python.

Answer:

Dictionary Properties:

PropertyDescription
OrderedMaintains insertion order (Python 3.7+)
MutableCan be modified after creation
Key-uniqueNo duplicate keys allowed
HeterogeneousKeys and values can be different types
  • Fast access: O(1) average lookup time
  • Dynamic size: Can grow or shrink
  • Key restrictions: Keys must be immutable

Mnemonic: “Dictionaries are Ordered, Mutable, Unique, Heterogeneous”


Question 2(b) OR [4 marks]
#

What is the dir() function in python. Explain with example.

Answer:

dir() function returns all attributes and methods of an object.

Example:

# List all attributes of string
text = "hello"
attributes = dir(text)
print(attributes[:5])  # First 5 attributes

# Check available methods
print("upper" in dir(text))  # True

# For modules
import math
math_methods = dir(math)
print("sqrt" in math_methods)  # True

# For custom objects
class MyClass:
    def my_method(self):
        pass

obj = MyClass()
print(dir(obj))
  • Introspection: Examines object properties
  • Debugging: Helps find available methods
  • All objects: Works with any Python object

Mnemonic: “dir() shows Directory of object attributes”


Question 2(c) OR [7 marks]
#

Write a program to define module to find sum of two numbers. Import module to another program.

Answer:

Module file (calculator.py):

# calculator.py
def add_numbers(a, b):
    """Function to add two numbers"""
    return a + b

def multiply_numbers(a, b):
    """Function to multiply two numbers"""
    return a * b

def get_sum(num1, num2):
    """Alternative sum function"""
    result = num1 + num2
    return result

Main program:

# main.py
import calculator

# Using the module
result1 = calculator.add_numbers(10, 20)
print(f"Sum: {result1}")

# From import
from calculator import get_sum
result2 = get_sum(15, 25)
print(f"Sum using from import: {result2}")
  • Module creation: Save functions in .py file
  • Import: Use import statement to access
  • Code reusability: Use same module in multiple programs

Mnemonic: “Modules make code Reusable and Organized”


Question 3(a) [3 marks]
#

What is Runtime error and Logical error. Explain with example.

Answer:

Error TypeDefinitionExample
Runtime ErrorOccurs during program executionDivision by zero, file not found
Logical ErrorProgram runs but gives wrong outputWrong formula, incorrect condition

Examples:

# Runtime Error
x = 10
y = 0
result = x / y  # ZeroDivisionError

# Logical Error
def calculate_area(radius):
    return 3.14 * radius  # Should be radius * radius
  • Runtime: Crashes program execution
  • Logical: Program continues but wrong result

Mnemonic: “Runtime Crashes, Logical Confuses”


Question 3(b) [4 marks]
#

Write points on Except and explaining it.

Answer:

Except clause handles specific exceptions in try-except block.

Key Points:

FeatureDescription
Syntaxexcept ExceptionType:
MultipleCan have multiple except blocks
Genericexcept: catches all exceptions
Variableexcept Exception as e: stores error
try:
    number = int(input("Enter number: "))
    result = 10 / number
except ValueError:
    print("Invalid input")
except ZeroDivisionError:
    print("Cannot divide by zero")
except Exception as e:
    print(f"Error: {e}")
  • Specific handling: Different exceptions handled differently
  • Error recovery: Program continues after handling

Mnemonic: “Except Catches and Handles errors”


Question 3(c) [7 marks]
#

Write a program to catch Divide by zero Exception. Also use finally block.

Answer:

def safe_division():
    try:
        # Get input from user
        numerator = float(input("Enter numerator: "))
        denominator = float(input("Enter denominator: "))
        
        # Perform division
        result = numerator / denominator
        print(f"Result: {numerator} / {denominator} = {result}")
        
    except ZeroDivisionError:
        print("Error: Cannot divide by zero!")
        print("Please enter a non-zero denominator")
        
    except ValueError:
        print("Error: Please enter valid numbers only")
        
    except Exception as e:
        print(f"Unexpected error occurred: {e}")
        
    finally:
        print("Division operation completed")
        print("Thank you for using the calculator")

# Call the function
safe_division()
  • Try block: Contains risky code
  • Except: Handles ZeroDivisionError specifically
  • Finally: Always executes regardless of exception

Mnemonic: “Try risky code, Except handles errors, Finally always runs”


Question 3(a) OR [3 marks]
#

What are the built-in exceptions and gives its types.

Answer:

Built-in Exception Types:

TypeDescriptionExample
ValueErrorInvalid value for operationint(“abc”)
TypeErrorWrong data type“5” + 5
IndexErrorIndex out of rangelist[10] for 5-element list
KeyErrorKey not found in dictionarydict[“missing_key”]
FileNotFoundErrorFile doesn’t existopen(“missing.txt”)
# Examples
try:
    int("hello")  # ValueError
    "5" + 5       # TypeError
    [1,2,3][5]    # IndexError
except (ValueError, TypeError, IndexError) as e:
    print(f"Error: {type(e).__name__}")

Mnemonic: “Value, Type, Index, Key, File - common error types”


Question 3(b) OR [4 marks]
#

Explain Syntax error and how do we identify it? Give an example.

Answer:

Syntax Error occurs when Python cannot parse the code due to incorrect syntax.

Identification:

MethodDescription
Python interpreterShows error message with line number
IDE highlightingCode editors highlight syntax errors
Error messagePoints to exact location of error

Examples:

# Missing colon
if x > 5
    print("Greater")  # SyntaxError

# Unmatched parentheses
print("Hello"  # SyntaxError

# Incorrect indentation
def my_function():
print("Hello")  # IndentationError

# Invalid variable name
2variable = 10  # SyntaxError
  • Detection: Before program execution
  • Error message: Shows line and character position
  • Common causes: Missing colons, brackets, wrong indentation

Mnemonic: “Syntax errors Stop code from Starting”


Question 3(c) OR [7 marks]
#

What is Exception handling in python? Explain with proper example.

Answer:

Exception Handling is a mechanism to handle runtime errors gracefully without crashing the program.

Structure:

try:
    # Risky code
    pass
except SpecificException:
    # Handle specific error
    pass
except Exception as e:
    # Handle any other error
    pass
else:
    # Runs if no exception
    pass
finally:
    # Always runs
    pass

Complete Example:

def file_processor():
    filename = None
    try:
        filename = input("Enter filename: ")
        with open(filename, 'r') as file:
            content = file.read()
            numbers = [int(x) for x in content.split()]
            average = sum(numbers) / len(numbers)
            print(f"Average: {average}")
            
    except FileNotFoundError:
        print(f"Error: File '{filename}' not found")
        
    except ValueError:
        print("Error: File contains non-numeric data")
        
    except ZeroDivisionError:
        print("Error: No numbers found in file")
        
    except Exception as e:
        print(f"Unexpected error: {e}")
        
    else:
        print("File processed successfully")
        
    finally:
        print("File processing operation completed")

# Run the function
file_processor()
  • Graceful handling: Program continues after error
  • Multiple exceptions: Different error types handled separately
  • Else clause: Runs only if no exception occurs
  • Finally clause: Always executes for cleanup

Mnemonic: “Try-Except-Else-Finally: Complete error handling”


Question 4(a) [3 marks]
#

What kind of different operations we can perform in a file?

Answer:

File Operations:

OperationDescriptionMethod
ReadRead file contentread(), readline(), readlines()
WriteWrite data to filewrite(), writelines()
AppendAdd data to endopen with ‘a’ mode
CreateCreate new fileopen with ‘w’ or ‘x’ mode
DeleteRemove fileos.remove()
SeekMove file pointerseek()
# Example operations
with open('file.txt', 'w') as f:
    f.write("Hello")  # Write
    
with open('file.txt', 'r') as f:
    content = f.read()  # Read

Mnemonic: “Read, Write, Append, Create, Delete, Seek”


Question 4(b) [4 marks]
#

Give list of file modes. Write Description of any four mode.

Answer:

File Modes:

ModeDescriptionPurpose
‘r’Read mode (default)Read existing file
‘w’Write modeCreate new or overwrite existing
‘a’Append modeAdd to end of existing file
‘x’Exclusive creationCreate new file, fail if exists
‘b’Binary modeHandle binary files
’t’Text mode (default)Handle text files
’+’Read and writeBoth operations allowed

Four Mode Descriptions:

  1. ‘r’ (Read): Opens file for reading only, file pointer at beginning
  2. ‘w’ (Write): Opens for writing, truncates file or creates new one
  3. ‘a’ (Append): Opens for writing, file pointer at end of file
  4. ‘r+’ (Read/Write): Opens for both reading and writing

Mnemonic: “Read, Write, Append, eXclusive - main file modes”


Question 4(c) [7 marks]
#

Write a program to sort all the words in a file and put it in list.

Answer:

def sort_words_from_file():
    try:
        # Input filename
        filename = input("Enter filename: ")
        
        # Read file content
        with open(filename, 'r') as file:
            content = file.read()
        
        # Split into words and clean them
        words = content.lower().split()
        
        # Remove punctuation and empty strings
        import string
        clean_words = []
        for word in words:
            clean_word = word.translate(str.maketrans('', '', string.punctuation))
            if clean_word:  # Add only non-empty words
                clean_words.append(clean_word)
        
        # Sort the words
        sorted_words = sorted(clean_words)
        
        # Display results
        print("Sorted words:")
        print(sorted_words)
        
        # Save to new file
        with open('sorted_words.txt', 'w') as output_file:
            for word in sorted_words:
                output_file.write(word + '\n')
        
        print(f"Total words: {len(sorted_words)}")
        print("Sorted words saved to 'sorted_words.txt'")
        
    except FileNotFoundError:
        print("Error: File not found")
    except Exception as e:
        print(f"Error: {e}")

# Run the program
sort_words_from_file()
  • File reading: Read entire file content
  • Word processing: Split, clean, and sort words
  • List creation: Store sorted words in list

Mnemonic: “Read, Split, Clean, Sort, Save”


Question 4(a) OR [3 marks]
#

What is file handling? List files handling operation and explain it.

Answer:

File Handling is the process of working with files to store and retrieve data permanently.

File Handling Operations:

OperationFunctionDescription
Openopen()Opens file in specified mode
Readread(), readline()Reads data from file
Writewrite(), writelines()Writes data to file
Closeclose()Closes file and frees resources
Seekseek()Moves file pointer position
Telltell()Returns current file pointer position
# Basic file operations
file = open('data.txt', 'w')  # Open
file.write('Hello World')     # Write
file.close()                  # Close

file = open('data.txt', 'r')  # Open for reading
content = file.read()         # Read
file.close()                  # Close

Mnemonic: “Open, Read, Write, Close - basic file cycle”


Question 4(b) OR [4 marks]
#

Explain load() method with example.

Answer:

load() method is used to deserialize data from a file (usually with pickle module).

Pickle load() Example:

import pickle

# First, save some data
data_to_save = {
    'name': 'John',
    'age': 25,
    'scores': [85, 92, 78]
}

# Save data to file
with open('data.pkl', 'wb') as file:
    pickle.dump(data_to_save, file)

# Load data from file
with open('data.pkl', 'rb') as file:
    loaded_data = pickle.load(file)

print("Loaded data:", loaded_data)
print("Name:", loaded_data['name'])
print("Scores:", loaded_data['scores'])

JSON load() Example:

import json

# Load JSON data
with open('config.json', 'r') as file:
    config = json.load(file)
    
print("Configuration:", config)
  • Deserialization: Converts file data back to Python objects
  • Binary mode: Use ‘rb’ mode for pickle files
  • Error handling: Handle FileNotFoundError

Mnemonic: “load() brings file data back to Python objects”


Question 4(c) OR [7 marks]
#

Write a program that inputs a text file. The program should print all of the unique words in the file in alphabetical order.

Answer:

def find_unique_words():
    try:
        # Get filename from user
        filename = input("Enter text filename: ")
        
        # Read file content
        with open(filename, 'r', encoding='utf-8') as file:
            content = file.read().lower()
        
        # Clean and extract words
        import re
        import string
        
        # Remove punctuation and split into words
        words = re.findall(r'\b[a-zA-Z]+\b', content.lower())
        
        # Create set to get unique words
        unique_words = set(words)
        
        # Convert to sorted list
        sorted_unique_words = sorted(list(unique_words))
        
        # Display results
        print("\nUnique words in alphabetical order:")
        print("-" * 40)
        
        for i, word in enumerate(sorted_unique_words, 1):
            print(f"{i:3d}. {word}")
        
        print(f"\nTotal unique words: {len(sorted_unique_words)}")
        
        # Save results to file
        with open('unique_words_output.txt', 'w') as output_file:
            output_file.write("Unique Words in Alphabetical Order\n")
            output_file.write("=" * 40 + "\n\n")
            for word in sorted_unique_words:
                output_file.write(word + '\n')
        
        print("Results saved to 'unique_words_output.txt'")
        
    except FileNotFoundError:
        print(f"Error: File '{filename}' not found")
    except PermissionError:
        print("Error: Permission denied to read file")
    except Exception as e:
        print(f"Unexpected error: {e}")

# Example usage
def create_sample_file():
    sample_text = """
    Python is a powerful programming language.
    Python is easy to learn and Python is versatile.
    Programming with Python is fun and programming is rewarding.
    """
    
    with open('sample.txt', 'w') as f:
        f.write(sample_text)
    print("Sample file 'sample.txt' created")

# Create sample and run program
create_sample_file()
find_unique_words()
  • Regular expressions: Extract only alphabetic words
  • Set data structure: Automatically removes duplicates
  • Sorted function: Arranges words alphabetically
  • File output: Saves results for future reference

Mnemonic: “Read, Extract, Unique, Sort, Display”


Question 5(a) [3 marks]
#

Explain the use of the following turtle function with an appropriate example. (a) turn() (b) move().

Answer:

Note: Standard turtle module uses left(), right() instead of turn(), and forward(), backward() instead of move().

Turtle Movement Functions:

FunctionPurposeExample
left(angle)Turn left by degreesturtle.left(90)
right(angle)Turn right by degreesturtle.right(45)
forward(distance)Move forwardturtle.forward(100)
backward(distance)Move backwardturtle.backward(50)
import turtle

# Create turtle
t = turtle.Turtle()

# Turn functions
t.left(90)    # Turn left 90 degrees
t.right(45)   # Turn right 45 degrees

# Move functions
t.forward(100)  # Move forward 100 units
t.backward(50)  # Move backward 50 units

# Keep window open
turtle.done()

Mnemonic: “Turn changes direction, Move changes position”


Question 5(b) [4 marks]
#

Explain the various inbuilt methods to change the direction of the turtle.

Answer:

Direction Control Methods:

MethodDescriptionExample
left(angle)Turn counterclockwiseturtle.left(90)
right(angle)Turn clockwiseturtle.right(45)
setheading(angle)Set absolute directionturtle.setheading(0)
towards(x, y)Point towards coordinatesturtle.setheading(turtle.towards(100, 100))
import turtle

t = turtle.Turtle()

# Relative turning
t.left(90)        # Turn left 90°
t.right(45)       # Turn right 45°

# Absolute direction
t.setheading(0)   # Point East (0°)
t.setheading(90)  # Point North (90°)

# Point towards specific point
angle = t.towards(100, 100)
t.setheading(angle)
  • Relative: left() and right() change current direction
  • Absolute: setheading() sets exact direction
  • Coordinate-based: towards() calculates direction to point

Mnemonic: “Left-Right relative, Heading absolute, Towards calculates”


Question 5(c) [7 marks]
#

Write a program to draw square, rectangle and circle using turtle.

Answer:

import turtle

def draw_shapes():
    # Create turtle and screen
    screen = turtle.Screen()
    screen.title("Drawing Shapes with Turtle")
    screen.bgcolor("white")
    screen.setup(800, 600)
    
    # Create turtle
    pen = turtle.Turtle()
    pen.speed(3)
    pen.color("blue")
    
    # Draw Square
    pen.penup()
    pen.goto(-200, 100)
    pen.pendown()
    pen.write("Square", font=("Arial", 12, "bold"))
    pen.goto(-200, 50)
    
    for i in range(4):
        pen.forward(80)
        pen.right(90)
    
    # Draw Rectangle
    pen.penup()
    pen.goto(0, 100)
    pen.pendown()
    pen.color("red")
    pen.write("Rectangle", font=("Arial", 12, "bold"))
    pen.goto(0, 50)
    
    for i in range(2):
        pen.forward(120)  # Length
        pen.right(90)
        pen.forward(60)   # Width
        pen.right(90)
    
    # Draw Circle
    pen.penup()
    pen.goto(200, 100)
    pen.pendown()
    pen.color("green")
    pen.write("Circle", font=("Arial", 12, "bold"))
    pen.goto(200, 50)
    
    pen.circle(40)  # Radius = 40
    
    # Hide turtle and keep window open
    pen.hideturtle()
    screen.exitonclick()

# Alternative function for each shape
def draw_square(turtle_obj, size):
    """Draw a square with given size"""
    for _ in range(4):
        turtle_obj.forward(size)
        turtle_obj.right(90)

def draw_rectangle(turtle_obj, width, height):
    """Draw a rectangle with given dimensions"""
    for _ in range(2):
        turtle_obj.forward(width)
        turtle_obj.right(90)
        turtle_obj.forward(height)
        turtle_obj.right(90)

def draw_circle(turtle_obj, radius):
    """Draw a circle with given radius"""
    turtle_obj.circle(radius)

# Run the main program
draw_shapes()
  • Square: 4 equal sides with 90° turns
  • Rectangle: 2 pairs of equal sides
  • Circle: Built-in circle() method with radius

Mnemonic: “Square: 4 equal sides, Rectangle: 2 pairs, Circle: radius method”


Question 5(a) OR [3 marks]
#

What are the various types of pen command in turtle? Explain them all.

Answer:

Pen Control Commands:

CommandPurposeExample
penup()Lift pen (no drawing)turtle.penup()
pendown()Put pen down (start drawing)turtle.pendown()
pensize(width)Set pen thicknessturtle.pensize(5)
pencolor(color)Set pen colorturtle.pencolor(“red”)
fillcolor(color)Set fill colorturtle.fillcolor(“blue”)
begin_fill()Start filling shapeturtle.begin_fill()
end_fill()End filling shapeturtle.end_fill()
import turtle

t = turtle.Turtle()

# Pen control
t.penup()           # Lift pen
t.goto(50, 50)      # Move without drawing
t.pendown()         # Put pen down
t.pensize(3)        # Set thickness
t.pencolor("red")   # Set color

Mnemonic: “Up-Down controls drawing, Size-Color controls appearance”


Question 5(b) OR [4 marks]
#

Draw circle and star shapes using turtle and fill them with red color.

Answer:

import turtle

def draw_filled_shapes():
    # Setup screen
    screen = turtle.Screen()
    screen.bgcolor("white")
    screen.title("Filled Circle and Star")
    
    # Create turtle
    artist = turtle.Turtle()
    artist.speed(5)
    
    # Draw filled circle
    artist.penup()
    artist.goto(-150, 0)
    artist.pendown()
    
    # Set colors for circle
    artist.color("red", "red")  # pen color, fill color
    artist.begin_fill()
    artist.circle(50)
    artist.end_fill()
    
    # Draw filled star
    artist.penup()
    artist.goto(100, 0)
    artist.pendown()
    
    # Set colors for star
    artist.color("red", "red")
    artist.begin_fill()
    
    # Draw 5-pointed star
    for i in range(5):
        artist.forward(100)
        artist.right(144)
    
    artist.end_fill()
    
    # Add labels
    artist.penup()
    artist.goto(-180, -80)
    artist.color("black")
    artist.write("Filled Circle", font=("Arial", 12, "bold"))
    
    artist.goto(70, -80)
    artist.write("Filled Star", font=("Arial", 12, "bold"))
    
    # Hide turtle
    artist.hideturtle()
    screen.exitonclick()

# Run the program
draw_filled_shapes()

Key Points:

  • begin_fill(): Start filling the shape
  • end_fill(): Complete the fill
  • color(): Set both pen and fill colors
  • Star angle: 144° for 5-pointed star

Mnemonic: “Begin fill, Draw shape, End fill = Filled shape”


Question 5(c) OR [7 marks]
#

Write a program to draw Indian Flag using turtle.

Answer:

import turtle

def draw_indian_flag():
    # Create screen
    screen = turtle.Screen()
    screen.bgcolor("white")
    screen.title("Indian Flag")
    screen.setup(800, 600)
    
    # Create turtle
    flag = turtle.Turtle()
    flag.speed(5)
    flag.pensize(2)
    
    # Flag dimensions
    flag_width = 300
    flag_height = 200
    
    # Starting position
    start_x = -150
    start_y = 100
    
    # Draw flag pole
    flag.penup()
    flag.goto(start_x - 20, start_y + 50)
    flag.pendown()
    flag.color("brown")
    flag.pensize(8)
    flag.setheading(270)  # Point downward
    flag.forward(400)
    
    # Reset pen
    flag.pensize(2)
    flag.color("black")
    
    # Draw saffron rectangle (top)
    flag.penup()
    flag.goto(start_x, start_y)
    flag.pendown()
    flag.color("orange", "orange")
    flag.begin_fill()
    flag.setheading(0)
    
    for _ in range(2):
        flag.forward(flag_width)
        flag.right(90)
        flag.forward(flag_height // 3)
        flag.right(90)
    flag.end_fill()
    
    # Draw white rectangle (middle)
    flag.penup()
    flag.goto(start_x, start_y - flag_height // 3)
    flag.pendown()
    flag.color("black", "white")
    flag.begin_fill()
    
    for _ in range(2):
        flag.forward(flag_width)
        flag.right(90)
        flag.forward(flag_height // 3)
        flag.right(90)
    flag.end_fill()
    
    # Draw green rectangle (bottom)
    flag.penup()
    flag.goto(start_x, start_y - 2 * flag_height // 3)
    flag.pendown()
    flag.color("green", "green")
    flag.begin_fill()
    
    for _ in range(2):
        flag.forward(flag_width)
        flag.right(90)
        flag.forward(flag_height // 3)
        flag.right(90)
    flag.end_fill()
    
    # Draw Ashoka Chakra (wheel)
    chakra_center_x = start_x + flag_width // 2
    chakra_center_y = start_y - flag_height // 2
    
    flag.penup()
    flag.goto(chakra_center_x, chakra_center_y - 30)
    flag.pendown()
    flag.color("navy blue")
    flag.pensize(3)
    
    # Draw outer circle
    flag.circle(30)
    
    # Draw spokes
    flag.penup()
    flag.goto(chakra_center_x, chakra_center_y)
    flag.pendown()
    
    for i in range(24):  # 24 spokes in Ashoka Chakra
        flag.setheading(i * 15)  # 360/24 = 15 degrees
        flag.forward(30)
        flag.backward(30)
    
    # Draw inner circle
    flag.penup()
    flag.goto(chakra_center_x, chakra_center_y - 5)
    flag.pendown()
    flag.circle(5)
    
    # Add title
    flag.penup()
    flag.goto(-100, 200)
    flag.color("black")
    flag.write("INDIAN FLAG", font=("Arial", 16, "bold"))
    
    # Hide turtle
    flag.hideturtle()
    screen.exitonclick()

# Run the program
draw_indian_flag()

Flag Components:

  • Saffron: Courage and sacrifice (top)
  • White: Truth and peace (middle)
  • Green: Faith and chivalry (bottom)
  • Ashoka Chakra: 24-spoke wheel in navy blue

Mnemonic: “Saffron-White-Green stripes with 24-spoke Chakra”

Related

Python Programming (1323203) - Summer 2024 Solution
18 mins
Study-Material Solutions Python 1323203 2024 Summer
Python Programming (4311601) - Summer 2024 Solution
Study-Material Solutions Python 4311601 2024 Summer
Data Structure with Python (4331601) - Summer 2024 Solution
Study-Material Solutions Data-Structure Python 4331601 2024 Summer
OOPS & Python Programming (4351108) - Summer 2024 Solution
Study-Material Solutions Python Oops 4351108 2024 Summer
Advanced Python Programming (4321602) - Summer 2023 Solution
36 mins
Study-Material Solutions Python 4321602 2023 Summer
Consumer Electronics & Maintenance (4341107) - Summer 2024 Solution
15 mins
Study-Material Solutions Consumer-Electronics 4341107 2024 Summer