PYTHON 505
PYTHON 505
PYTHON 505
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
Invalid : 1age
2. What is an operator?
Operators refer to special symbols that perform operations on values and variables.
ASSERT: Assert statements are a convenient way to insert debugging assertions into a program.
# Initializing variables
x = 10
y = 20
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?
The range() function returns a sequence of numbers, starting from 0 by default, and
Example:
x = range(3, 6)
for n in x:
print(n)
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.
Array Methods
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
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
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]
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.
Lists
Sets
Dictionaries
User-Defined Classes (It purely depends upon the user to define the characteristics)
9. Define class.
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
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:
except ExceptionType as e:
else:
finally:
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.
Starting at My Computer go to the following directory C:\Python38-32. In that folder you should see all the
Python files.
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.
Save your python script with any filename.py (Hi.py) in created folder (pythonscripts).
# File: Hi.py
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.
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.
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.
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.
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")
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.
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.
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!
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.
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).
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
hello >>> |
RESTART: C:\Users\hills\AppData\Local\Programs\Python\Python38-3211-py
(OR)
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
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
Here the identifier age refers to a number value stored at a certain location in memory, the general syntax
for declaring variables her 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.
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
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.
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)
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.
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)
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
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.
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
3 is assigned to a, 4 is assigned to b.
print(add(3,4))
#Output:17
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.
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
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
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
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.
14.(a) Write a python program to declare and print a list of English alphabets.
# Python program to print a list of alphabets
['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.
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 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
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.
Dictionary is ordered
List is ordered Tuple is ordered Set is unordered (Python 3.7 and
above)
class Person:
Output
Alex
24
(OR)
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
Ex-2
class Solution:
__privateCounter = 0
def sum(self):
self.__privateCounter += 1
print(self.__privateCounter)
count = Solution()
count.sum()
count.sum()
Output:
1
2
2
PART-C 10×1=10
16. 16. Write a python program that accepts a string and calculate the number of digits and
letters.
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
if c.isdigit():
d=d+1
elif c.isalpha():
l=l+1
else:
pass
# Print the total count of letters ('l') and digits ('d') in the input string 's'
print("Letters", l)
print("Digits", d)
OUTPUT:
Letters 6
Digits 2