[go: up one dir, main page]

0% found this document useful (0 votes)
29 views12 pages

DCA6109 – PYTHON PROGRAMMING

The document provides an internal assignment for a Master of Computer Applications (MCA) student, detailing Python programming concepts such as naming rules for identifiers, lambda functions, file handling modes, data structures, user-defined exceptions, and regular expressions for validating mobile numbers. It also discusses game development fundamentals, including game loops and event handling, as well as data preprocessing steps in data science. Each section includes examples and explanations to illustrate the concepts.

Uploaded by

rohit20021004
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)
29 views12 pages

DCA6109 – PYTHON PROGRAMMING

The document provides an internal assignment for a Master of Computer Applications (MCA) student, detailing Python programming concepts such as naming rules for identifiers, lambda functions, file handling modes, data structures, user-defined exceptions, and regular expressions for validating mobile numbers. It also discusses game development fundamentals, including game loops and event handling, as well as data preprocessing steps in data science. Each section includes examples and explanations to illustrate the concepts.

Uploaded by

rohit20021004
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/ 12

INTERNAL ASSIGNMENT

NAME VIVEK KUMAR


SESSION NOVEMBER 2024
ROLL NO 2414504937
PROGRAM MASTER OF COMPUTER APPLICATIONS (MCA)
SEMESTER I
COURSE CODE & NAME 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

Reasons for Using Lambda Functions:


a. Concise and efficient:
i. It alleviates the work of writing full function definitions.
ii. Ideal for short and simple operations when a full function is not needed.
b. Used with Higher-Order Functions:
i. Used commonly with the map(), filter(), and sorted().
ii. An example with map():
c. No Need to Define Separate Functions:
i. Very good for small operations that can only be used once.
d. Sorting with Custom Keys:
i. Lambda functions most frequently serve as the key function in sorted().
ii. Exmaple:
students = [("Alice", 25), ("Bob", 20), ("Charlie", 22)]
students.sort(key=lambda x: x[1])
print(students) # Output: [('Bob', 20), ('Charlie', 22), ('Alice', 25)]

e. One-Liner Functions for Functional Programming:


i. Helps to keep code more readable and compact.

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!")

b) String Functions in Python


Python provides various built-in functions to manipulate and check string properties. Six common
ones are:

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:

i. Read Mode ('r'):


o Opens the file for reading only.
o If the file does not exist, an error is raised.
o Example:

Example:
with open("example.txt", "r") as file:
content = file.read()
print(content)

ii. Write Mode ('w'):


o Opens the file for writing. If the file exists, it is overwritten. If it doesn’t exist,
a new file is created.
o Example :
with open("example.txt", "w") as file:
file.write("This is a new file.")

iii. Append Mode ('a'):


o Opens the file for writing, but does not overwrite existing content. Instead, data is
appended at the end.
o If the file doesn’t exist, it is created.
o Example:
with open("example.txt", "a") as file:
file.write("\nAppending new content.")

iv. Read and Write Mode ('r+'):


o Allows both reading and writing. The file must exist; otherwise, an error occurs.
o Example:
with open("example.txt", "r+") as file:
content = file.read()
file.write("\nAdding more data.")

v. Write and Read Mode ('w+'):


o Opens the file for both reading and writing. If the file exists, it is overwritten. If
not, a new file is created.
o Example:
with open("example.txt", "w+") as file:
file.write("New content.")
file.seek(0)
print(file.read())

vi. Append and Read Mode ('a+'):


o Similar to append mode but allows reading as well. The file pointer is at the end
when writing new data.
o Example:
with open("example.txt", "a+") as file:
file.write("\nAnother appended line.")
file.seek(0)
print(file.read())

vii. Binary Mode ('rb', 'wb', 'ab', 'rb+', 'wb+', 'ab+'):


o Used for working with binary files such as images or audio files.
o Example:
with open("image.png", "rb") as file:
data = file.read()

b) Differences Between List, Tuple, Set, and Dictionary


Python provides four main built-in data structures: list, tuple, set, and dictionary. Each of these
has unique properties and use cases.
Data Ordered? Mutable? Allows Indexed? Syntax
Structure Duplicates?
List Yes Yes Yes Yes []
Tuple Yes No Yes Yes ()
Set No Yes No No {}
Dictionary Yes Yes Keys: No, Values: Keys: No, Values: {key:
Yes Yes value}

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?

Custom exceptions can be easily created by following the steps below:


i. Define a new class exactly inheriting from the builtin Exception class in Python.
ii. Optionally, override the __init__ method to take custom error messages as well.
iii. Raise the exception at necessary places of code.

Example of User Defined Exception


A Python program has been shown below which defines a custom exception called
AgeTooSmallError. This exception checks if a user’s age is greater than 18, if not, raises the custom
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.

(b) Regular Expression for Validating Indian Mobile Numbers


Regular expressions (regex) in Python help match specific patterns in text. To validate an Indian
mobile number, we need to follow a specific pattern. Indian mobile numbers:
1. Begin with +91- (optional country code).
2. Contain exactly 10 digits.
3. The first digit should be between 6 and 9.
Regular Expression for Indian Mobile Number
A valid Indian mobile number can be matched using the following regex pattern:

^\+91-[6-9]\d{9}$

Breaking Down the Pattern:


o ^ → Ensures the match starts from the beginning of the string.
o \+91- → Matches the country code +91- exactly.
o [6-9] → The first digit must be between 6 and 9.
o \d{9} → Matches exactly 9 more digits (since total digits should be 10).
o $ → Ensures the match ends here.

Python Program for Validation:

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.

for event in pygame.event.get():


if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
print("Move forward")

b.) Data Preprocessing Steps in Detail


Consideration in how data are prepared and what sorts of data are prepared is a big part of what
data science and machine learning are concerned with. Data preprocessing usually involves
cleaning or transforming raw data into a form amenable to analysis-a series of steps which include:
i. Data Collection
Before the analysis can be done, the relevant data should be collected from a variety of sources;
usually databases are employed, but some also come from sensors or are scraped from the web.
There may be some inconsistencies in the raw data that may be vectors for missing values or
irrelevant details.
ii. Imputation of Missing Data
Missing data will often result in incorrect predictions or biases. Commonly, missing values can be
dealt with through one of several different methods:
o Removal-Dropping records such that too many missing values have been introduced into
the column.
o Imputation-Filling in the blank field with the mean, median, or mode of the particular
column.
Illustration in Python using pandas:
import pandas as pd
df = pd.read_csv("data.csv")
df.fillna(df.mean(), inplace=True)

iii. Data Cleaning


Data cleanup involves the correction of inconsistent data, duplicate removal, and resolution of
errors occurring through human error and misspellings. This further ensures uniformity and
trustworthiness.
df.drop_duplicates(inplace=True)

iv. Data Transformation


This process refers to converting data to a function not yet identified. It includes for instance,
scaling numerical ranges to make them common, like from 0 to 1, and also encoding categorical
values to numerical ones in order to apply an algorithm in machine learning.
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
df[['age', 'salary']] = scaler.fit_transform(df[['age', 'salary']]) # Scaling numerical data.
v. Feature Selection
By selecting relevant features, the efficiency and accuracy of a model is improved; correlation
analysis or dimensionality reduction-PCA techniques are some of the methods that can cure
redundancy and irrelevance.
from sklearn.feature_selection import SelectKBest, f_classif
selector = SelectKBest(score_func=f_classif, k=5)
df_selected = selector.fit_transform(df.iloc[:, :-1], df.iloc[:, -1]) # Selecting top 5 features.
vi. Splitting Data
In order to train and evaluate a model, the data should be divided into training and testing sets.
This ensures that the model will generalize to new data.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(df.iloc[:, :-1], df.iloc[:, -1], test_size=0.2,
random_state=42).

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.

v. Use of Naming Conventions


o For function and variable names, snake_case must be used.
o UpperCamelCase must be used for class names.
o Constants must be written in ALL_CAPS.

MAX_VALUE = 1000 # Constant


def calculate_sum():
pass # Function name written in snake_case.

Vi. Whitespace Usage


o Avoid unnecessary spaces within parentheses, brackets, or following a comma.

# Correct
x = [1, 2, 3]
y = (a+b)*c.

# Incorrect
x=[1, 2, 3].

vii. Comments and docstrings


o Use comments to describe why a thing is done, never what it is.
o Docstrings should be used for functions and classes.

def greet(name):
"""Returns a greeting message."""
return "Hey " + str(name) + " !"

You might also like