DCA6109 – PYTHON PROGRAMMING
DCA6109 – PYTHON PROGRAMMING
1. Answer
a) Rules of naming Python identifiers while creating Python programs: Identifiers are names for
variables, functions, or classes. To make an identifier effective for Python interpretation, they must
follow particular rules.
Naming Rules for Identifiers:
1. Cannot be Python Keywords:
• Keywords, as the word implies, are those words which cannot be used as identifiers in
Python.
• Some examples of keywords include if, else, def, class, return, lambda, and so on.
2. Can contain letters, digits and underscores (_):
• Identifiers can contain lowercase letters (a-z), uppercase letters (A-Z), digits (0-9), and
underscores (_).
• Identifiers should usually not begin with a digit.
Examples:
my_var = 10 # valid
data_1 = 20 # valid
1name = 30 # invalid (cannot start with a digit)
3. Case Sensitivity: Identifiers are case-sensitive, which means name, Name and NAME are
different.
4. It is suggested that they are meaningful: Descriptive names lead an easy read to the code.
5. Underscore usage for Special Cases:
• Creating a leading underscore (_var) conception indicates that this variable would normally
be for internal use.
• Standard name mangling occurs when double underscores are in the beginning of a name.
6. No Special Characters Except _:
• Symbols like @, #, $, %, ! and so on are out.
When these rules are followed, identifiers are valid, readable, and maintainable.
b) Scalar functions are anonymous single-line functions that have the lambda keyword in
Python. They do not have a name and are written in a single line unlike normal functions.
Syntax of Lambda Function:
lambda arguments: expression
Example:
square = lambda x: x * x
print(square(5)) # Output: 25
Lambda is not intended for complicated logic; it is better avoided as normal functions offer more
readability.
2. Answer
a) Else statements can be used with the loops for and while in Python. An else block is
executed normally after the loop finishes and does not exit via a break statement. This is
useful in search operations that are only confined to certain conditions within loops.
1. Using else with for Loop
The else block in a for loop executes when all iterations are completed and no break has
been encountered.
Example:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 10:
print("Number found!") break
else:
print("Number not found!")
i. upper()
Converts all uppercase letters in a string to uppercase.
Example:
text = "hello world"
print(text.upper()) # Output: HELLO WORLD
ii. lower()
Converts all uppercase letters in a string to lowercase.
Example:
text = "Python Programming"
print(text.lower()) # Output: python programming
iii. isdigit()
Returns True if all characters in the string are digits(0-9) or otherwise returns False.
Example:
num = "12345"
print(num.isdigit()) # Output: True
num = "123a"
print(num.isdigit()) # Output: False
iv. isalpha()
Returns True if all characters in the string are alphabets (a-z, A-Z), otherwise False.
Example:
word = "Python"
print(word.isalpha()) # Output: True
word = "Python3"
print(word.isalpha()) # Output: False
v. split()
Splits a string into a list of words using spaces or a specified delimiter.
Example:
sentence="Learn Python Programming"
words = sentence.split()
print(words) # Output: ['Learn', 'Python', 'Programming']
data = "apple,banana,grape"
fruits = data.split(",")
print(fruits) # Output: ['apple', 'banana', 'grape']
vi. join()
Joins elements of an iterable, such as a list, into a single string using a specified separator.
Example:
words = ["Python", "is", "fun"]
sentence = " ".join(words)
print(sentence) # Output: Python is fun
fruits = ["apple", "banana", "grape"]
result = ", ".join(fruits)
print(result) # Output: apple, banana, grape
3. Answer
a) Various Modes for Reading and Writing Data into a File in Python
In Python, files are handled using different modes depending on whether to read, write ormodify
its contents. The built-in open() function is used to open a file from within Python. Its parameter
mode indicates in what manner the file should be accessed. The modes include:
Example:
with open("example.txt", "r") as file:
content = file.read()
print(content)
i. List
A list is an ordered collection of elements that are mutable, meaning we can modify, add,
or remove items. Lists allow duplicate values and support indexing and slicing.
Example:
my_list = [10, 20, 30, 40]
my_list.append(50) # Adds 50 to the end
my_list[2] = 100 # Modifies the value at index 2
print(my_list) # Output: [10, 20, 100, 40, 50]
ii. Tuple
A tuple is similar to a list but immutable, meaning its contents cannot be changed after
creation. Tuples are used for fixed data collections where modification is not needed.
Example:
my_tuple = (10, 20, 30)
# my_tuple[1] = 50 # This will raise an error
print(my_tuple) # Output: (10, 20, 30)
iii. Set
A set is an unordered collection of unique elements. It does not support duplicate values,
indexing, or slicing, and is useful when working with distinct items.
Example:
my_set = {1, 2, 3, 3, 4}
my_set.add(5)
print(my_set) # Output: {1, 2, 3, 4, 5}
iv. Dictionary
A dictionary is a collection of key-value pairs. Keys must be unique, while values can be
duplicated. Dictionaries allow efficient lookups and modifications.
Example:
my_dict = {"name": "Alice", "age": 25}
my_dict["city"] = "New York"
print(my_dict) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
4. Answer
(a) Creating User-Defined Exceptions in Python
Exceptions are those runtime errors in Python which intentionally break the normal flow of a
program. While Python provides some built-in exceptions like ValueError, TypeError, and
IndexError, sometimes it becomes vital for a programmer to create user-defined exceptions to trap
application-related errors. Such exceptions are called user-defined exceptions.
How is it Created User-Defined Exception?
class AgeTooSmallError(Exception):
"""Custom Exception for Age Validation"""
def __init__(self, message="Age must be at least 18."):
self.message = message
super().__init__(self.message)
def check_age(age):
if age < 18:
raise AgeTooSmallError()
else:
print("Age is valid!")
# Example Usage
try:
user_age = int(input("Enter your age: "))
check_age(user_age)
except AgeTooSmallError as e:
print(f"Error: {e}")
except ValueError:
print("Invalid input! Please enter a number.")
Explanation:
o The AgeTooSmallError class extends Exception and takes a default error message.
o The check_age() function raises this exception if the age is below 18.
o In the try block, user input is taken and checked using check_age().
o If an exception occurs, it is caught in the except block and an appropriate error message is
displayed.
This is how user-defined exceptions help in better error handling in Python programs.
^\+91-[6-9]\d{9}$
import re
def validate_mobile_number(number):
pattern = r"^\+91-[6-9]\d{9}$"
if re.match(pattern, number):
return "Valid Indian mobile number."
else:
return "Invalid mobile number!"
# Example
Usage user_input = input("Enter mobile number (+91-XXXXXXXXXX): ")
print(validate_mobile_number(user_input))
5. Answer
a) Significance of Game Loop and Event Handling in Game Development
Game loop and event handling are a few of the key tenets in the development of games for the
reasons they enable a game to offer yield performance, acting with the user on the happiest of
occasions.
Game Loops
This core mechanism that makes it possible for a game to run loops while continuously updating
the state of the game and flashing new frames in front of the user's eyes. A game loop generally
runs in three general phases, which are:
1) Handling Input - The game handles user inputs such as keyboard presses, mouse clicks, or
controller inputs.
2) Updating Game Status - The logic processes in the game such as moving characters, collision
checks, or score updates.
3) Rendering - The game updates the screen based on the updated game state.
Goodly written game loops tend to keep the frame rate constant and, hence, are generally smooth.
Normally, in a game library in Python, such as Pygame, the loop generally runs with while True
or while running and executes updates continually until the player quits or exits the game.
import pygame
pygame.init()
screen = pygame.display.set_mode((500, 500))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
Event Handling Events in the game include user interactions, which are quite varied: clicking on
a button, pressing keys, or moving a joystick. Event handling represents the capturing of these
interactions along with the triggering of the appropriate responses. In Pygame, this reduction of
event handling retrieves all events with pygame.event.get(), where developers impose conditions
using if to handle them.
For instance, if a player presses the "W" button to move forward, the event handler detects the key
press and moves the player accordingly.
6. Answer
PEP 8 Guidelines of Formatting Python code
PEP 8 (Python Enhancement Proposal 8) is essentially a coding convention which give a great
extent of guidelines about readable and consistent Python code. These standards help developers
to keep uniformity and hence enhances collaboration. Some highlighted PEP 8 guidelines are:
i. Indentation
Give 4 spaces to each indent in indented code.
Avoid using tabs; mixing tabs with spaces can make error. In a tab-only environments, four spaces
are equivalent to a tab space.
def example_function():
print("Hello, world!") # Correct: 4 spaces before print().
ii. Maximum Line Length
Lines should always contain 79 characters.
In case a statement or function is lengthy, it should be broken into lines and properly indented.
data = {
"name": "Alice",
"age": 25,
"city": "New York"
}
iii. Blank Lines
Put in double blank lines before such constructs as new class or function definition.
Use one blank line to separate different parts of logic inside a function.
class Person:
def __init__(self, name):
self.name = name
IV. Imports
o Always place modules at the start of the file.
o Use separate lines for different modules.
import os
import sys.
# Correct
x = [1, 2, 3]
y = (a+b)*c.
# Incorrect
x=[1, 2, 3].
def greet(name):
"""Returns a greeting message."""
return "Hey " + str(name) + " !"