[go: up one dir, main page]

0% found this document useful (0 votes)
21 views22 pages

PYTHON 505

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 22

C20-CM-WD-505

BOARD DIPLOMA EXAMINATION, (C-20)


OCTOBER/NOVEMBER-2024
DCME-FIFTH SEMESTER EXAMINATION
PYTHON PROGRAMING

Time: 3 Hours] [Total Marks: 80


–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
PART-A 3×10=30

Instructions: (1) Answer all questions.


(2) Each question carries three marks.
(3) Answers should be brief and straight to the point and shall not exceed five simple
sentences.

1. Define variables.

A Python variable is a reserved memory location to store values. In other words, a variable in a python
program gives data to the computer for processing. Every value in Python has a datatype. Different data
types in Python are Numbers, List, Tuple, Strings, Dictionary, etc. Variables can be declared by any name
or even alphabets like a, aa, abc, etc

EX. Valid : age , _age , Age

Invalid : 1age

2. What is an operator?

Operators refer to special symbols that perform operations on values and variables.

Operators are used to perform operations on variables and values.


Example: print (10 + 5)

3. Define break and assert.

ASSERT: Assert statements are a convenient way to insert debugging assertions into a program.
# Initializing variables
x = 10
y = 20

# Asserting a boolean condition


assert x < y

# Printing the values of x and y


print("x =", x)
print("y =", y)

BREAK: It terminates the current loop and resumes execution at the next statement.

for i in range(10):
print(i)
if i == 2:
break
4. What is range?

Python range is a function that returns a sequence of numbers.

The range() function returns a sequence of numbers, starting from 0 by default, and

increments by 1 (by default), and stops before a specified number.

Syntax. range(start, stop, step)

Example:

x = range(3, 6)
for n in x:
print(n)

5. Define python package.

Python Packages are a way to organize and structure your Python code into reusable components.
Think of it like a folder that contains related Python files (modules) that work together to provide
certain functionality. Packages help keep your code organized, make it easier to manage and maintain,
and allow you to share your code with others. They’re like a toolbox where you can store and organize
your tools (functions and classes) for easy access and reuse in different projects.

6. What are different python array methods?

Array Methods

Python has a set of built-in methods that you can use on lists/arrays.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

7. Define cloning list.

Cloning Lists

If we want to modify a list and also keep a copy of the original, we need to be able to make a copy of the
list itself, not just the reference. This process is sometimes called cloning, to avoid the ambiguity of the
word copy.
Example

a = [81,82,83]

b = a[:] # make a clone using slice

print(a == b)

print(a is b)

b[0] = 5

print(a)

print(b)
8. What is mutability?

Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’ is the ability
of objects to change their values. These are often the objects that store a collection of data.

List of Mutable and Immutable objects

Objects of built-in type that are mutable are:

 Lists
 Sets
 Dictionaries
 User-Defined Classes (It purely depends upon the user to define the characteristics)

9. Define class.

A Class is like an object constructor, or a "blueprint" for creating objects.

A class is a code template for creating objects. Objects have member variables and have behaviour
associated with them. In python a class is created by the keyword class.

Example

class MyClass:
x=5

10. Define exceptional handling

Exception handling in Python is a process of resolving errors that occur in a program. This involves
catching exceptions, understanding what caused them, and then responding accordingly. Exceptions are
errors that occur at runtime when the program is being executed. They are usually caused by invalid user
input or code that is invalid in Python. Exception handling allows the program to continue to execute
even if an error occurs.

Syntax:

try:

# code that may cause an exception

except ExceptionType as e:

# code to handle the exception

else:

# code to execute if no exceptions were raised

finally:

# code that will always be executed, regardless of exceptions


PART-B 5×10=50

Instructions: (1) Answer all the questions


(2) Each question carries eight marks.
(3)Answers should be comprehensive and criterion for valuation is the content but not the
length of the answer.
11.(a) What is python IDLE? Explain how to use IDE for writing and executing the program.

Python IDLE (Integrated Development and Learning Environment) is an integrated development


environment for Python that comes bundled with the standard Python distribution.

 It serves as a convenient tool for writing, testing, and debugging Python code.
 Python IDLE provides a graphical user interface (GUI) that simplifies the coding process and helps
users manage their Python projects efficiently.
 Python's IDLE capability enables programmers to write and execute a single line of code, much as how
Shell writes and edits code.
 Getting Started with Python Programming for Windows Users

Installation of Python

Download the current production version of Python from the Python Download site.

Double click on the icon of the file that you just downloaded.

Accept the default options given to you until you get to the Finish button. Your installation is complete.

Setting up the Environment

Starting at My Computer go to the following directory C:\Python38-32. In that folder you should see all the
Python files.

Copies that address starting with C:\Python38-32 close that window.

Click on Start. Right Click on My Computer.

Click on Properties. Click on Advanced System Settings or Advanced.


Click on Environment Variables.

Under System Variables search for the variable Path.

Select Path by clicking on it. Click on Edit.

Scroll all the way to the right of the field called Variable value using the right arrow.

Add a semi-colon (;) to the end and paste the path (to the Python folder) that you previously copied. Click
OK.
Writing Your First Python Program

Create your own folder (ex: pythonscripts) in C: drive for storing all your Python programs.

Go to Start and choose notepad for writing python script.

Save your python script with any filename.py (Hi.py) in created folder (pythonscripts).

# File: Hi.py

print ("Hello World!")

Running Your First Program

Go to Start and click on Run.

Type cmd in the Open field and click OK.

A dark window will appear. Type cd C:\ and hit the key Enter.

If you type dir you will get a listing of all folders in your C: drive. You should see the folder pythonscripts
that you created.

Type cd pythonscripts and hit Enter. It should take you to the pythonscripts folder.

Type dir and you should see the file Hi.py.

To run the program, type python Hi.py and hit Enter.

You should see the line Hello World!

Congratulations, you have run your first Python program.


OR

IDLE stands for Integrated Development and Learning Environment, and it is the default
environment that comes with Python when you install it on your system. IDLE is a simple IDE
(Integrated Development Environment) that provides an interface for writing, editing, and running Python
code. It is particularly useful for beginners learning to program in Python.

IDLE has the following features:

1. Python Shell: It provides an interactive environment where you can type Python code and see
immediate results. This is a REPL (Read-Eval-Print Loop) that allows you to run Python
commands one at a time.
2. Editor: It also includes a text editor for writing longer Python programs, which can be saved as
.py files and executed later.
3. Debugger: IDLE provides a basic debugger that allows you to set breakpoints and step through
your code, making it easier to diagnose issues.
4. Syntax Highlighting: It highlights keywords, functions, and other Python syntax in different
colors to improve readability.

How to Use IDLE for Writing and Executing Python Programs

1. Opening IDLE

 On Windows: After installing Python, you can open IDLE by searching for "IDLE" in the Start
menu.
 On Mac/Linux: You can open IDLE from the terminal by typing idle or use the system’s
application launcher.

This will open the Python Shell, where you can type Python code directly.

2. Writing a Python Program in the Editor

 Once IDLE is open, click File > New File to open a blank editor window.
 In this editor, you can write a Python program.

Example program:

python
Copy code
def greet(name):
print(f"Hello, {name}!")

greet("Alice")

3. Saving the Program

 After writing your program, save it by clicking File > Save or using the shortcut Ctrl + S.
 Choose a location and name your file with a .py extension, for example greet.py.

4. Running the Program

 Once the program is saved, you can run it by selecting Run > Run Module from the menu or by
pressing F5.
 IDLE will execute the Python program, and the output will appear in the Python Shell window.

5. Using the Python Shell for Quick Testing

 The Python Shell is an interactive window that allows you to quickly type and execute Python
code one line at a time. It is useful for testing small snippets of code without creating a file.
 For example, you can type:

python
Copy code
>>> print("Hello, World!")
Hello, World!

 The output is immediately displayed after each command.

6. Debugging in IDLE

 IDLE includes a basic debugger that you can use to step through your program.
 To start the debugger, open the program in the editor and click Debug > Debugger.
 You can set breakpoints by clicking the margin next to a line number, and then running the
program. The program will pause at the breakpoint, allowing you to inspect variables and step
through the code.

Summary of Common Features in IDLE

 Interactive Shell: Quickly run small Python commands.


 Editor: Write full Python scripts, save, and edit them.
 Run Program: Use Run > Run Module or F5 to execute saved scripts.
 Debugger: Step through code and inspect values for debugging.
 Syntax Highlighting: Makes code easier to read by color-coding keywords.

PROCESS OF RUNNING SCRIPT

Click on Start button -> go to -> All Programs ->go to -> Python -> go to-> (Python GUI) .python shell will
be opened.
Goto File menu click on New File (CTRL+N) and write the code and save with extension. example (1.py).

1.py-C:\Users\hills\AppData\Local\Programs\Python Python38-32\1.py (3.8.3)

File Edit Format Run Options Window Help

print('hello world')

And run the program by pressing F5 (or) RunaRun Module. Out put can be observed after Run

Python 3.8.3 (taga/v3.8.3:6f8c832, May 13 2020, 22:20:19) (MSC v.1925 32 bit (li

tel)] on win32

Type "help", "copyright", "credits" or "license() for more information.

hello >>> |

RESTART: C:\Users\hills\AppData\Local\Programs\Python\Python38-3211-py

(OR)

(b) Explain declaration and initialization of variables

VARIABLES

In Programming languages, variables allow programs to store, load, and manipulate information which
can be referenced later on. They also provide a means to store data with a label, this label is usually a
descriptive name to give a developer an idea of the type of data stored.

Variable properties

There are 4 major properties associated with variables;

 A name
 A type
 A value
 Scope

The name of a variable should describe the information that is stored within the variable. The name is
very important because this is how we access the value stored in a location in memory.

The type refers to the kind of data being stored, in some programming languages the data type must be
defined before initializing the variable. This tells the compiler the kind of value to expect. Languages like
this are, C++, Java, etc.
In other languages, the data type of each variable doesn't need to be specified before initialization, for this
case, the data type is inferred based on the value passed. Example is Python;

All actions carried out within variables can be grouped into three major parts;

 Variable Declaration
 Initializing the Variable: Access(Read) and Assign(Write)

Variable Declaration

In declaring variables, this is basically where we announce the existence of the variable to the computer,
the declarations simply gives an identifier to a value stored in memory
The code below is a variable declaration example in type script

let age: number;

Here the identifier age refers to a number value stored at a certain location in memory, the general syntax
for declaring variables her is

let <name> : <type>;

for C++ the syntax for declaring variables is

<type> <name>:
example

int age;

This tells the processor to reserve a location in the computers memory, this location should be enough to
store any value of integer type.
After declaring the variable, whenever we refer to the variable name, the program knows the exact
location in memory it reserved.

There are specific rules to how we name variables;

 Variables can not contain spaces


 Variables can only contain letters, numbers and undrescores.
 Variables names must begin with a letter

Initializing a Variable

Initializing a variable refers to the process wherein a variable is assigned its' initial value before it is used
within the program.
Initializing a variable comes after declaring the variable. A variable can not be used without first
declaring it.
In some programming languages, the declaration and initialization process can be done in one line.

In python, if we say age = 50, the age variable is first declared and we don't need to specify the data type,
since we passed in an integer, python infers the data type automatically.

Assigning a value

Considering the example below

height = 20
height = height + 60

First the program, reserves a location in memory and assigns the label 'height' to it, it then stores the value
20 in that memory location.

For the second line, python first evaluates what's on the right hand side, then passes that value to the
memory location with the label 'height'.
On the right hand side, python is faced with a variable height, it goes to the location in memory with this
label and retrieves the value stored within that location.
The value stored here is 20, it then retrieves the stored value and evaluates 20 + 60 to 80, this is the new
value.
This value is then stored in a location in memory, then it's labelled 'height'.

So whenever we call the variable height, the program searches for the location in memory with the label
height, and returns the value within.

12.(a) Explain continue and Write a python program to skip multiple elements using continue
The Python continue statement is a control flow statement that is used to skip certain iterations of a loop
and continue with the next iteration. It is used in combination with an if statement to skip over certain
values or conditions that do not meet specific criteria.
The continue statement allows the program to skip over the rest of the code in the current iteration of the
loop and proceed with the next iteration. This can be useful in situations where you want to ignore certain
values or conditions in the loop and continue with the rest of the iterations.

Syntax of the Python continue statement

while test_expression:
# Some code
if condition:
continue
# Some more code
PROGRAM
x=0
while x < 10:
x += 1
if x == 5:
continue
print(x)
Output
1
2
3
4
6
7
8
9
10

(OR)

(b) Explain various loop statements.

Looping statements in Python

Looping simplifies complicated problems into smooth ones. It allows programmers to modify the flow of
the program so that rather than writing the same code again and again, programmers are able to repeat the
code a finite number of times.

In Python, there are three different types of loops: for loop, while loop, and nested loop. Here, we will
read about these different types of loops and how to use them.

For Loop

The for loop is used in cases where a programmer needs to execute a part of the code until the given
condition is satisfied. The for loop is also called a pre-tested loop. It is best to use a for loop if the number
of iterations is known in advance.

In Python, there is no C style for loop, i.e., for (i=0; i<n; i++).

Syntax:
for variable in sequence:
statement(s)

Input:
a=5
for i in range(0, a):
print(i)

Output:
0
1
2
3
4

The for loop runs till the value of i is less than a. As the value of a is 5, the loop ends.
While Loop

The while loop is to be used in situations where the number of iterations is unknown at first. The block of
statements is executed in the while loop until the condition specified in the while loop is satisfied. It is
also called a pre-tested loop.

In Python, the while loop executes the statement or group of statements repeatedly while the given
condition is True. And when the condition becomes false, the loop ends and moves to the next statement
after the loop.

Syntax:
while condition:
statement(s)

Input:
count = 0
while (count < 5):
count = count + 1
print("Flexiple")

Output:
Flexiple
Flexiple
Flexiple
Flexiple
Flexiple

The loop prints ‘Flexiple’ till the value of count becomes 5 and the condition is False.

Nested Looping statements in Python

The Python programming language allows programmers to use one looping statement inside another
looping statement.

Syntax:
#for loop statement
for variable in sequence:
for variable in sequence:
statement(s)
statement(s)

#while loop statement


while condition:
while condition:
statement(s)
statement(s)

Input:
for i in range(1, 7):
for j in range(i):
print(i, end=' ')
print()

Output:
1
22
333
4444
55555
666666

13.(a) Explain different types of arguments and write a python program by using variable lengthy
argument.

In Python, a function is defined with def. This is followed by the name of the function and a set of formal
parameters. The actual parameters, or arguments, are passed during a function call. We can define a
function with a variable number of arguments.

5 Arguments in Python

1. Default arguments
2. Keyword arguments
3. Positional arguments
4. Arbitrary positional arguments
5. Arbitrary keyword arguments

1. Default Arguments in Python

 Default arguments are values that are provided while defining functions.
 The assignment operator = is used to assign a default value to the argument.
 Default arguments become optional during the function calls.
 If we provide a value to the default arguments during function calls, it overrides the default value.
 The function can have any number of default arguments.
 Default arguments should follow non-default arguments.

In the below example, the default value is given to argument b and c.

def add(a,b=5,c=10):
return (a+b+c)
This function can be called in one of three ways:
Giving Only the Mandatory Argument

print(add(3))
#Output:18

Giving One of the Optional Arguments

3 is assigned to a, 4 is assigned to b.

print(add(3,4))
#Output:17

Giving All the Arguments

print(add(2,3,4))
#Output:9
Default values are evaluated only once at the point of the function definition in the defining scope. So, it
makes a difference when we pass mutable objects like a list or dictionary as default values.

2. Keyword Arguments in Python


Functions can also be called using keyword arguments of the form kwarg=value.

During a function call, values passed through arguments don’t need to be in the order of parameters in the
function definition. This can be achieved by keyword arguments. But all the keyword arguments should
match the parameters in the function definition.

def add(a,b=5,c=10):
return (a+b+c)
Calling the function add by giving keyword arguments

All parameters are given as keyword arguments, so there’s no need to maintain the same order.

print (add(b=10,c=15,a=20))
#Output:45
During a function call, only giving a mandatory argument as a keyword argument. Optional default
arguments are skipped.

print (add(a=10))
#Output:25

3. Positional Arguments in Python


During a function call, values passed through arguments should be in the order of parameters in the
function definition. This is called positional arguments.

Keyword arguments should follow positional arguments only.

def add(a,b,c):
return (a+b+c)
The above function can be called in two ways:
First, during the function call, all arguments are given as positional arguments. Values passed through
arguments are passed to parameters by their position. 10 is assigned to a, 20 is assigned to b and 30 is
assigned to c.

print (add(10,20,30))
#Output:60
The second way is by giving a mix of positional and keyword arguments. Keyword arguments should
always follow positional arguments.

print (add(10,c=30,b=20))
#Output:60

4. Arbitrary Positional Arguments in Python


Variable-length arguments are also known as arbitrary arguments. If we don’t know the number of
arguments needed for the function in advance, we can use arbitrary arguments. Arbitrary arguments come
in two types: arbitrary positional arguments and arbitrary keyword arguments.

For arbitrary positional argument, an asterisk (*) is placed before a parameter in function definition which
can hold non-keyword variable-length arguments. These arguments will be wrapped up in a tuple. Before
the variable number of arguments, zero or more normal arguments may occur.

def add(*b):
result=0
for i in b:
result=result+i
return result

print (add(1,2,3,4,5))
#Output:15
print (add(10,20))
#Output:30

5. Arbitrary Keyword Arguments in Python


For arbitrary keyword argument, a double asterisk (**) is placed before a parameter in a function which
can hold keyword variable-length arguments.

def fn(**a):
for i in a.items():
print (i)
fn(numbers=5,colors="blue",fruits="apple")
'''
Output:
('numbers', 5)
('colors', 'blue')
('fruits', 'apple')
'''
EX-2
def sum_all(*args):
result = 0
for num in args:
result += num
return result

print(sum_all(1, 2, 3, 4, 5))

(OR)
(b) Explain about different string modules.
The string module contains a number of functions to process standard Python strings

The string module is part of Python’s standard library and is specifically designed for common
string operations. It provides constants representing commonly used sets of characters
(like lowercase and uppercase letters, digits, and punctuation) as well as utility functions
like capwords() for manipulating strings.

The module is useful for:


 Validating characters in a string.
 Formatting output.
 Handling templates in text processing.
We can import the string module by:
import string
text = "Monty Python's Flying Circus"
print ("upper", "=>", string.upper(text))
print( "lower", "=>", string.lower(text))
print( "split", "=>", string.split(text))
print ("join", "=>", string.join(string.split(text), "+"))
print ("replace", "=>", string.replace(text, "Python", "Java"))
print ("find", "=>", string.find(text, "Python"), string.find(text, "Java"))
print ("count", "=>", string.count(text, "n")
OUTPUT
upper => MONTY PYTHON'S FLYING CIRCUS
lower => monty python's flying circus
split => ['Monty', "Python's", 'Flying', 'Circus']
join => Monty+Python's+Flying+Circus
replace => Monty Java's Flying Circus
find => 6 -1
count => 3

14.(a) Write a python program to declare and print a list of English alphabets.
# Python program to print a list of alphabets

# Importing the string module


import string

# Printing a list of lowercase alphabets


lower = list(string.ascii_lowercase)
print(lower)

# Printing a list of uppercase alphabets


upper = list(string.ascii_uppercase)
print(upper)

# Printing a list of both upper and lowercase alphabets


alphabets = list(string.ascii_letters)
print(alphabets)
Output:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

OR
1. # Python program to generate a list of alphabets using the chr and ord functions
2. list_ = []
3. for i in range(97, 123):
4. list_.append(chr(i))
5.
6. print(list_)
Output:

7. ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

(OR)
(b) Compare list, tuple, dictionary and set.

List Tuple Set Dictionary

A list is a non- A Tuple is a non-


The set data
homogeneous data homogeneous data A dictionary is also a
structure is non-
structure that stores structure that stores non-homogeneous
homogeneous but
the elements in elements in columns of a data structure that
stores the elements
columns of a single single row or multiple stores key-value pairs.
in a single row.
row or multiple rows. rows.

The list can be A tuple can be The set can be The dictionary can be
represented by [ ] represented by ( ) represented by { } represented by { }

The Set will not


The list allows Tuple allows duplicate The dictionary doesn’t
allow duplicate
duplicate elements elements allow duplicate keys.
elements

The list can be nested A tuple can be nested The set can be nested The dictionary can be
among all among all among all nested among all

Example: {1: “a”, 2:


Example: [1, 2, 3, 4, Example: {1, 2, 3, 4,
Example: (1, 2, 3, 4, 5) “b”, 3: “c”, 4: “d”, 5:
5] 5}
“e”}

A list can be created Tuple can be created A set can be created A dictionary can be
using using using created using
the list() function the tuple() function. the set() function the dict() function.

A set is mutable i.e


A list is mutable i.e A tuple is immutable i.e we can make any A dictionary is
we can make any we can not make any changes in the set, its mutable, its Keys are
changes in the list. changes in the tuple. elements are not not duplicated.
duplicated.
List Tuple Set Dictionary

Dictionary is ordered
List is ordered Tuple is ordered Set is unordered (Python 3.7 and
above)

Creating a set Creating an empty


Creating an empty list Creating an empty Tuple
a=set() dictionary
l=[] t=()
b=set(a) d={}

15.(a) Explain about object with a python program.


Objects are variables that contain data and functions that can be used to manipulate the data. The object's
data can vary in type (string, integer, etc.) depending on how it’s been defined. An object is like a mini-
program inside python, with its own set of rules and behaviors.
An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class
with actual values. Python is an object-oriented programming language that stresses objects i.e. it
mainly emphasizes functions. Python Objects are basically an encapsulation of data variables and
methods acting on that data into a single entity.
Syntax:
obj = MyClass()
print(obj.x)

class Person:

def __init__(self, name, age):


self.name = name
self.age = age

person1 = Person('Alex', 24)


print (person1.name)
print (person1.age)

Output
Alex
24
(OR)

(b) What is data hiding? Explain with an example.

Data hiding in Python is the method to prevent access to specific users in the application.

Data hiding in Python is done by using a double underscore before (prefix) the attribute name.
This makes the attribute private/ inaccessible and hides them from users. Python has nothing
secret in the real sense. Still, the names of private methods and attributes are internally mangled
and unmangled on the fly, making them inaccessible by their given names.

In Python, the process of encapsulation and data hiding works simultaneously. Data
encapsulation hides the private methods on the other hand data hiding hides only the data
components. The robustness of the data is also increased with data hiding. The private access
specifier is used to achieve data hiding. There are three types of access specifiers, private,
public, and protected.

Example:
class JustCounter:

__secretCount = 0

def count(self):

self.__secretCount += 1

print self.__secretCount

counter = JustCounter()

counter.count()

counter.count()

print counter.__secretCount
Output

Traceback (most recent call last):

Ex-2

class Solution:

__privateCounter = 0

def sum(self):

self.__privateCounter += 1

print(self.__privateCounter)

count = Solution()

count.sum()

count.sum()

# Here we have accessed the private data

# member through class name.


print(count._Solution__privateCounter)

Output:
1
2
2

Advantages of Data Hiding:


1. It helps to prevent damage or misuse of volatile data by hiding it from the public.
2. The class objects are disconnected from the irrelevant data.
3. It isolates objects as the basic concept of OOP.
4. It increases the security against hackers that are unable to access important data.
Disadvantages of Data Hiding:
1. It enables programmers to write lengthy code to hide important data from common clients.
2. The linkage between the visible and invisible data makes the objects work faster, but data hiding
prevents this linkage.

PART-C 10×1=10

Instructions: (1) Answer all questions.


(2) The question carries ten marks.
(3) Answers should be comprehensive and criterion for valuation is the content but not
the length of the answer.

16. 16. Write a python program that accepts a string and calculate the number of digits and
letters.

Sample data: Python 3.2

Expected output:

Letters 6

Digits 2

# Prompt the user to input a string and store it in the variable 's'

s = input("Input a string")

# Initialize variables 'd' (for counting digits) and 'l' (for counting letters) with values 0

d=l=0

# Iterate through each character 'c' in the input string 's'


for c in s:

# Check if the current character 'c' is a digit

if c.isdigit():

# If 'c' is a digit, increment the count of digits ('d')

d=d+1

# Check if the current character 'c' is an alphabet letter

elif c.isalpha():

# If 'c' is an alphabet letter, increment the count of letters ('l')

l=l+1

else:

# If 'c' is neither a digit nor an alphabet letter, do nothing ('pass')

pass

# Print the total count of letters ('l') and digits ('d') in the input string 's'

print("Letters", l)

print("Digits", d)

OUTPUT:

Input a string python 3.2

Letters 6

Digits 2

You might also like