Project Report Aryan Batra 19 Sep
Project Report Aryan Batra 19 Sep
ON
PROGRAMMING WITH PYTHON
BACHELOR OF TECHNOLOGY
IN
COMPUTER SCIENCE ENGINEERING
Submitted by
Aryan Batra
( 13 / 23 )
DECLARATION
Certified that the above statement made by the student is correct to the best of my
knowledge and belief.
ACKNOWLEDGEMENT
I would also like to include special thanks of gratitude to Internshala and their
course instructor Mr.Anuj Kalbalia for their quality of course delivering.
A BS T R A C T
Programming with Python begins by familiarizing oneself with the process of installing Python
and navigating the Python interpreter and development environment, laying a solid
foundation for language's syntax, historical context, and the distinctions between Python 2.x and
3.x versions. A crucial component of programming with Python involves the utilization of
variables and data types, gaining a solid understanding of working with numbers, strings, lists,
tuples and dictionaries - the building blocks for constructing more complex programs.
Significant emphasis has been placed on core programming concepts such as conditionals, loops,
classes, creating objects, implementing inheritance, and customizing object behavior through the
use of magic methods has been discussed. The curriculum covers the integration of Python with
DECLARATION I
ACKNOWLEDGEMENT II
ABSTRACT III
LIST OF TABLES IV
LIST OF FIGURES V
BIBLOGRAPHY 59
IV
LIST OF TABLES
LIST OF FIGURES
TABLE
C H A P T E R - 1
1.1 INTRODUCTION
Python is a widely used general-purpose, high-level programming language. It was created by Guido
van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with
an emphasis on code readability, and its syntax allows programmers to express their concepts in
fewer lines of code. Python is a programming language that lets you work quickly and integrate
systems more efficiently. There are two major Python versions: Python 2 and Python 3. Both are
quite different.
It is an interpreted language because it executes line-by-line instructions. There are actually two way
to execute python code one is in Interactive mode and another thing is having Python prompts which
is also called script mode. Python does not convert high level code into low level code as many other
programming languages do rather it will scan the entire code into something called bytecode. every
time when Python developer runs the code and start to execute the compilation part execute first and
then it generate an byte code which get converted by PVM Python Virtual machine that understand
the analogy and give the desired output.
Interpreters are the computer program that will convert the source code or an high level
language into intermediate code (machine level language). It is also called translator in
programming terminology. Interpreters executes each line of statements slowly. This process
DEPARTMENT OF CSE, 1
PROGRAMMING WITH
is called Interpretation. For example Python is an interpreted language, PHP, Ruby, and
JavaScript.
There were a variety of reasons as to why there were different versions of Python available. Firstly, a
lot of industry code had been already written in Python 2, and therefore, completely migrating from
Python 2 to Python 3 would have turned out to be a very time-consuming and difficult job. Moreover,
in order to work with configuration management tools like Puppet or Ansible, knowledge of both
Python 2 and Python 3 was required. However, over the course of time, Python 3 has been developed in
a way to is suitable for a broad variety of fields like web development, data science, analytics scripting,
etc. Python 3 has a lot of rich libraries and can easily be integrated with other languages. Therefore, the
need for both versions of Python can be easily understood. In the end, efforts were made to make
Python 3 support a lot of major functionalities which Python 2 offered, and in 2020, Python 2 saw its
demise.
1.3.1 Python 2
Python 2.0 was introduced to the tech world in the year 2000. Created by the BeOpen
Python Labs team, the purpose of the introduction of Python 2 was to make programming
simple and easy to learn for the common masses. Python 2 was successful in implementing the
technical details of the Python Enhancement Proposal (PEP). However, after the introduction of
DEPARTMENT OF CSE, 2
PROGRAMMING WITH
Python 3, Python 2 could not find a lot of its usage in the tech world and the year 2020 marked
the end of Python 2’s legacy with Python 2.7 being its latest version.
1.3.2 Python 3
Released in the year 2008, Python 3 was not just another version of Python 2 after
debugging. The introduction of Python was mostly surrounded by the motive that redundancy –
writing repetitive code or writing the same piece of code again and again – should be removed
from coding. Python 3 is backwards incompatible and aims at eliminating the problems which
new programmers face while learning a programming language.
Based on the following parameters, the differences between Python 2 and Python 3 can
easily be made out. They are as follows :
1. Year of Release : Python 2 was released in the year 2000 whereas Python 3 was
released in the year 2008.
2. Print Keywords : In Python 2, print is a statement rather than a function, on the other
hand, in Python 3, print is considered to be a function and not a statement.
5. Exceptions : In Python 2, exceptions are used to enclose the notations, on the other
hand, In Python 3, parentheses are used to enclose the exceptions.
6. Variable Leakage : In Python, if the global variables are used inside a for-loop,
their values do change. Whereas, the value of variables never changes in Python 3.
DEPARTMENT OF CSE, 3
PROGRAMMING WITH
7. Iteration : In Python 2, the xrange() function has been defined for iterations whereas
in Python 3, to perform iterations, the new Range() function is introduced.
9. Libraries : Python 3 is the future, therefore many developers are now creating libraries
for the use of Python 3 strictly. The libraries created for Python 2 are now not forwards-
compatible. 2.x library may be ported to 3.x but it can be a complicated task. It is not
recommended for beginners.
10. Usage In Today’s Times : Since 2020, Python 2 has been outdated for use whereas
Python 3 is still in use by the developers and is more popular than Python 2.
12. Application : The utilisation of Python 2 was done mostly to become a DevOps
Engineer. Now it is no longer in use after 2020.
In this section we will see what are the features of Python programming language :
1. Free and Open Source : Python language is freely available at the official website. Since it
is open-source, this means that source code is also available to the public. So you can download it, use
it
as well as share it.
2. Easy to code : Python is a high-level programming language. Python is very easy to learn
the language as compared to other languages like C, C#, Javascript, Java, etc. It is very easy to code in
the
DEPARTMENT OF CSE, 4
PROGRAMMING WITH
Python language and anybody can learn Python basics in a few hours or days. It is also a developer-
friendly language.
3. Easy to Read : As you will see, learning Python is quite simple. As was already
established, Python’s syntax is really straightforward. The code block is defined by the indentations
rather than by semicolons or brackets.
5. GUI Programming Support : Graphical User interfaces can be made using a module such
as PyQt5, PyQt4, wxPython, or Tk in Python. PyQt5 is the most popular option for creating
graphical
apps with Python.
7. Large Community Support : Python has gained popularity over the years. Our questions
are constantly answered by the enormous StackOverflow community. These websites have already
provided answers to many questions about Python, so Python users can consult them as needed.
8. Easy to Debug : Excellent information for mistake tracing. You will be able to
quickly identify and correct the majority of your program’s issues once you understand how
to interpret Python’s error traces. Simply by glancing at the code, you can determine what it is
designed to perform.
9. Python is a Portable language : Python language is also a portable language. For example,
if we have Python code for Windows and if we want to run this code on other platforms such as
Linux, Unix, and Mac then we do not need to change it, we can run this code on any platform.
10. Python is an Integrated language : Python is also an Integrated language because we can
easily integrate Python with other languages like C, C++, etc.
DEPARTMENT OF CSE, 5
PROGRAMMING WITH
11. Interpreted Language : Python is an Interpreted Language because Python code is executed
line by line at a time. like other languages C, C++, Java, etc. there is no need to compile Python code
this makes it easier to debug our code. The source code of Python is converted into an immediate form
called bytecode.
12. Large Standard Library : Python has a large standard library that provides a rich set of
modules and functions so you do not have to write your own code for every single thing. There are
many libraries present in Python such as regular expressions, unit-testing, web browsers, etc.
13. Dynamically Typed Language : Python is a dynamically-typed language. That means the
type (for example- int, double, long, etc.) for a variable is decided at run time not in advance because of
this feature we don’t need to specify the type of variable.
14. Frontend and backend development : With a new project py script, you can run and write
Python codes in HTML with the help of some simple tags <py-script>, <py-env>, etc. This will help
you do frontend development work in Python like javascript. Backend is the strong forte of Python it’s
extensively used for this work cause of its frameworks like Django and Flask.
15. Allocating Memory Dynamically : In Python, the variable data type does not need to be
specified. The memory is automatically allocated to a variable at runtime when it is given a value.
Developers do not need to write int y = 18 if the integer value 15 is set to y. You may just type y=18.
DEPARTMENT OF CSE, 6
PROGRAMMING WITH
(a-z, 0-9). Moreover, identifiers are case-sensitive so it’s important to note that 'x' and 'X' would
be considered two different identifiers.
1. In the Python programming language the class names start with an uppercase letter
and all the other identifiers start with a lowercase letter.
2. In this language, if an identifier starts with a single leading underscore that can indicate
that the particular identifier is a private identifier.
3. In this language if an identifier starts with two leading underscores that can indicate a
strongly private identifier.
and as assert
global if import
in is lambda
DEPARTMENT OF CSE, 7
PROGRAMMING WITH
or pass raise
Python programming language does not provide any braces to indicate the code blocks
for function definitions or class or flow control. The codes are denoted by line identification.
The use of indentation in Python is crucial. It plays an important role in making Python code
easier to read, follow, and use - while incorrectly formatted code can be difficult to decipher and
use. Indentation provides visual structure to your code and has a big impact on the readability of
the code. Indentation also helps with debugging, as misaligned statements can easily help you
identify the errors. In Python, indentation is used to show a group of related statements, so
proper use of indentation increases the productivity of developers too. Without it, understanding
even simple programs in Python would be almost impossible.
Example Code :
# This is a comment
# Comments start with a '#' symbol and are not executed
# Define a variable
my_variable = 42
# Use an if statement with indentation
if my_variable > 50:
print("The variable is greater than 50")
else: print("The variable is not greater than 50")
# Define a function
def greet(name):
print("Hello, " + name + "!") # Call the function greet("Alice") greet("Bob")
DEPARTMENT OF CSE, 8
PROGRAMMING WITH
Example Code :
result = 1 + \
2+\
3+\
4+\
5
print(result)
DEPARTMENT OF CSE, 9
PROGRAMMING WITH
DEPARTMENT OF CSE, 1
PROGRAMMING WITH
C H A P T E R -2
2.1 INTRODUCTION
Python Data types are the classification or categorization of data items. It represents the kind of value
that tells what operations can be performed on a particular data. Since everything is an object in Python
programming, Python data types are classes and variables are instances (objects) of these classes. The
following are the standard or built-in data types in Python: Numeric, Sequence Type, Boolean, Set,
Dictionary.
A data type in Python is a classification of specific types of data by a certain value or certain types of
mathematical or logical operations. The way that data items are categorized or classified is known as
their data type. It stands for the type of value that indicates the types of operations that can be carried
out on a specific set of data. In this programming, python variables are instances (objects) of
these python classes, and data types are truly classes because everything is an object.
DEPARTMENT OF CSE, 1
PROGRAMMING WITH
Example Code :
x = "Hello World"
x = 50
e": 24}
x = {"geeks", "for", "geeks"}
x = frozenset({"geeks", "for", "geeks"})
x = Truex = 60.5
x = 3j
x = ["geeks", "for", "geeks"]
x = ("geeks", "for", "geeks")
x = range(10)
x = {"name": "Suraj", "ag
x = bytearray(4)
x = memoryview(bytes(6))
x = None
The numeric data type in Python represents the data that has a numeric value. A numeric value can be
an integer, a floating number, or even a complex number. These values are defined as Python
int , Python float , and Python complex classes in Python. The various numeric data types in python
are as follows :
1. Integers – This value is represented by int class. It contains positive or negative whole numbers
(without fractions or decimals). In Python, there is no limit to how long an integer value can be.
2. Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive
or negative integer may be appended to specify scientific notation.
DEPARTMENT OF CSE, 1
PROGRAMMING WITH
Note – type() function is used to determine the type of Python data type.
Example: This code demonstrates how to determine the data type of variables in Python using the type()
function . It prints the data types of three variables : a (integer) , b (float) , and c (complex) . The output
shows the respective data type Python for each variable.
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
DEPARTMENT OF CSE, 1
PROGRAMMING WITH
The sequence Data Type in Python is the ordered collection of similar or different Python data types.
Sequences allow storing of multiple values in an organized and efficient fashion. There are several
sequence data types of Python: Python String, Python List, Python Tuple.
1. Creating Strings : Strings in Python can be created using single quotes, double quotes,
or even triple quotes.
Example: This Python code showcases various string creation methods. It uses single
quotes, double quotes, and triple quotes to create strings with different content and includes a
multiline string. The code also demonstrates printing the strings and checking their data types.
Output:
DEPARTMENT OF CSE, 1
PROGRAMMING WITH
String with the use of Single Quotes:
Welcome to the Geeks World
String with the use of Double Quotes:
I'm a Geek
<class 'str'>
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"
<class 'str'>
Creating a multiline String:
Geeks
For
Life
Example: This Python code demonstrates how to work with a string named ‘ String1′ . It
initializes the string with “GeeksForGeeks” and prints it. It then showcases how to access the
first character ( “G” ) using an index of 0 and the last character ( “s” ) using a negative index of
-1.
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
print("\nFirst character of String is: ")
print(String1[0])
print("\nLast character of String is: ")
print(String1[-1])
Output:
DEPARTMENT OF CSE, 1
PROGRAMMING WITH
Initial String:
GeeksForGeeks
First character of String is:
G
Last character of String is:
s
Lists are just like arrays, declared in other languages which is an ordered collection of
data. It is very flexible as the items in a list do not need to be of the same type.
1. Creating a List in Python : Lists in Python can be created by just placing the sequence
inside the square brackets[].
Example: This Python code demonstrates list creation and manipulation. It starts with an
empty list and prints it. It creates a list containing a single string element and prints it. It creates
a list with multiple string elements and prints selected elements from the list. It creates a multi-
dimensional list (a list of lists) and prints it. The code showcases various ways to work with lists,
including single and multi-dimensional lists.
DEPARTMENT OF CSE, 1
PROGRAMMING WITH
Output:
Initial blank List:
[]
List with the use of String:
['GeeksForGeeks']
List containing multiple values:
Geeks
Geeks
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
2. Python Access List Items : In order to access the list items refer to the index
number. Use the index operator [ ] to access an item in a list. In Python, negative sequence
indexes
represent positions from the end of the array. Instead of having to compute the offset as in
List[len(List)-3], it is enough to just write List[-3]. Negative indexing means beginning from the
end, -1 refers to the last item, -2 refers to the second-last item, etc.
Example :
List = ["Geeks", "For", "Geeks"]
print("Accessing element from the list")
print(List[0])
print(List[2])
print("Accessing element using negative indexing")
print(List[-1])
print(List[-3])
Output:
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
DEPARTMENT OF CSE, 1
PROGRAMMING WITH
Just like a list, a tuple is also an ordered collection of Python objects. The only
difference between a tuple and a list is that tuples are immutable i.e. tuples cannot be modified
after it is created. It is represented by a tuple class.
1. Creating a Tuple in Python : In Python Data Types, tuples are created by placing a
sequence of values separated by a ‘comma’ with or without the use of parentheses for grouping
the data sequence. Tuples can contain any number of elements and of any datatype (like strings,
integers, lists, etc.). Note: Tuples can also be created with a single element, but it is a bit tricky.
Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to
make it a tuple.
Example: This Python code demonstrates different methods of creating and working
with tuples. It starts with an empty tuple and prints it. It creates a tuple containing string
elements and prints it. It converts a list into a tuple and prints the result. It creates a tuple from a
string using the tuple() function. It forms a tuple with nested tuples and displays the result.
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
DEPARTMENT OF CSE, 1
PROGRAMMING WITH
Tuple3 = (Tuple1, Tuple2) print("\
nTuple with nested tuples: ")
print(Tuple3)
Output:
Initial empty Tuple:
()
Tuple with the use of String:
('Geeks', 'For')
Tuple using List:
(1, 2, 4, 5, 6)
Tuple with the use of function:
('G', 'e', 'e', 'k', 's')
Tuple with nested tuples:
((0, 1, 2, 3), ('python', 'geek'))
2. Access Tuple Items : In order to access the tuple items refer to the index number.
Use the index operator [ ] to access an item in a tuple. The index must be an integer. Nested
tuples
are accessed using nested indexing.
Example : The code creates a tuple named ‘ tuple1′ with five elements: 1, 2, 3, 4, and 5 .
Then it prints the first, last, and third last elements of the tuple using indexing.
Output:
First element of tuple
DEPARTMENT OF CSE, 1
PROGRAMMING WITH
1
Last element of tuple
5
Third last element of tuple
3
Python Data type with one of the two built-in values, True or False. Boolean objects that
are equal to True are truthy (true), and those equal to False are falsy (false). However non-
Boolean objects can be evaluated in a Boolean context as well and determined to be true or false.
It is denoted by the class bool.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will
throw an error.
Example: The first two lines will print the type of the boolean values True and False,
which is <class ‘bool’>. The third line will cause an error, because true is not a valid keyword in
Python. Python is case-sensitive, which means it distinguishes between uppercase and lowercase
letters. You need to capitalize the first letter of true to make it a boolean value.
print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not defined
DEPARTMENT OF CSE, 2
PROGRAMMING WITH
2.4.5 Set Data Type
In Python Data Types, a Set is an unordered collection of data types that is iterable,
mutable, and has no duplicate elements. The order of elements in a set is undefined though it
may consist of various elements.
1. Create a Set in Python : Sets can be created by using the built-in set() function with
an iterable object or a sequence by placing the sequence inside curly braces, separated by
a ‘comma’. The type of elements in a set need not be the same, various mixed-up data type
values can also be passed to the set.
Example: The code is an example of how to create sets using different types of values,
such as strings , lists , and mixed values
set1 = set()
print("Initial blank Set: ")
print(set1)
set1 = set("GeeksForGeeks") print("\
nSet with the use of String: ")
print(set1)
set1 = set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: ")
print(set1)
set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks']) print("\
nSet with the use of Mixed Values")print(set1)
Output:
Initial blank Set:
set()
Set with the use of String:
{'F', 'o', 'G', 's', 'r', 'k', 'e'}
Set with the use of List:
{'Geeks', 'For'}
DEPARTMENT OF CSE, 2
PROGRAMMING WITH
Set with the use of Mixed Values
{1, 2, 4, 6, 'Geeks', 'For'}
2. Access Set Items : Set items cannot be accessed by referring to an index, since sets
are unordered the items have no index. But you can loop through the set items using a for loop,
or ask if a specified value is present in a set, by using the in the keyword.
Example: This Python code creates a set named set1 with the
values “Geeks” , “For” and “Geeks” . The code then prints the initial set, the elements of the set
in a loop, and checks if the value “Geeks” is in the set using the ‘ in’ operator
Output:
Initial set:
{'Geeks', 'For'}
Elements of set:
Geeks For
True
DEPARTMENT OF CSE, 2
PROGRAMMING WITH
1. Create a Dictionary in Python : In Python, a Dictionary can be created by placing a
sequence of elements within curly {} braces, separated by ‘comma’. Values in a dictionary can
be of any datatype and can be duplicated, whereas keys can’t be repeated and must be
immutable. The dictionary can also be created by the built-in function dict(). An empty
dictionary can be created by just placing it in curly braces{}. Note – Dictionary keys are case
sensitive, the same name but different cases of Key will be treated distinctly.
Example: This code creates and prints a variety of dictionaries. The first dictionary is
empty. The second dictionary has integer keys and string values. The third dictionary has mixed
keys, with one string key and one integer key. The fourth dictionary is created using
the dict() function, and the fifth dictionary is created using the [(key, value)] syntax.
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print("\
nDictionary with the use of Integer Keys: ")
print(Dict)
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} print("\
nDictionary with the use of Mixed Keys: ")
print(Dict)
Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)
Dict = dict([(1, 'Geeks'), (2, 'For')]) print("\
nDictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
DEPARTMENT OF CSE, 2
PROGRAMMING WITH
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': 'Geeks'}
Dictionary with the use of dict():
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with each item as a pair:
{1: 'Geeks', 2: 'For'}
Example: The code in Python is used to access elements in a dictionary. Here’s what it
does, It creates a dictionary Dict with keys and values as { 1: ‘Geeks’, ‘name’: ‘For’, 3:
‘Geeks’} . It prints the value of the element with the key ‘name’ , which is ‘For’ . It prints the
value of the element with the key 3, which is ‘Geeks’ .
Output:
Accessing a element using key:
For
Accessing a element using get:
Geeks
DEPARTMENT OF CSE, 2
PROGRAMMING WITH
C H A P T E R -3
Conditionals allow us to make decisions in our code. By using statements like if, elif, and else, we can
execute different blocks of code based on specific conditions. This enables our programs to respond
dynamically to varying inputs and situations. Loops are powerful constructs that enable us to repeat a
block of code multiple times. We will delve into two primary types of loops in Python: for loops and
while loops. These tools are invaluable for tasks that require iteration, such as processing items in a list
or executing a block of code until a certain condition is met. Functions are reusable pieces of code that
perform a specific task. By defining functions, we can organize our code into manageable sections,
making it easier to read, maintain, and debug. We will learn how to create functions, pass arguments,
and return values, which will enhance our programming efficiency. Finally, we will explore modules,
which are files containing Python code that can be imported and used in other programs. Modules allow
us to organize our code into separate files, promoting reusability and modularity. We will discuss how
to create our own modules and how to leverage existing ones from the Python Standard Library.
Conditional Statements are statements in Python that provide a choice for the control flow based on a
condition. It means that the control flow of the Python program will be decided based on the outcome
of the condition.
Syntax of If Statement:
if condition:
# Statements to execute if
# condition is true
DEPARTMENT OF CSE, 2
PROGRAMMING WITH
Code:
if 10 > 5:
print("10 greater than 5")
print("Program ended")
Output:
10 greater than 5
Program ended
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Code:
x=3
if x == 4:
print("Yes")
else:
print("No")
Output:
No
DEPARTMENT OF CSE, 2
PROGRAMMING WITH
3.2.3 Nested if..else Conditional Statement in Python
Nested if..else means an if-else statement inside another if statement. Or in simple words
first, there is an outer if statement, and inside it another if – else statement is present and such
type of statement is known as nested if statement. We can use one if or else if statement inside
another if or else if statements.
Code:
letter = "A"
if letter == "B":
print("letter is B")
else:
if letter == "C":
print("letter is C")
else:
if letter == "A":
print("letter is A")
else:
print("letter isn't A, B and C")
Output:
letter is A
Code:
letter = "A"
if letter == "B":
print("letter is B")
elif letter == "C":
DEPARTMENT OF CSE, 2
PROGRAMMING WITH
print("letter is C")
elif letter == "A":
print("letter is A")
else:
print("letter isn't A, B or C")
Output:
letter is A
Code:
a = 2, b = 10
print("Both a and b are equal" if a == b else "a is greater than b"
if a > b else "b is greater than a")
Output:
b is greater than a
DEPARTMENT OF CSE, 2
PROGRAMMING WITH
Python programming language provides two types of Python loopshecking time : For loop and While
loop to handle looping requirements.
All the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code. Python uses indentation as its
method of grouping statements.
Example: The given Python code uses a ‘while' loop to print “Hello Geek” three times
by incrementing a variable called ‘count' from 1 to 3.
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
Output:
Hello Geek
Hello Geek
Hello Geek
DEPARTMENT OF CSE, 2
PROGRAMMING WITH
For loops are used for sequential traversal. For example: traversing
a list or string or array etc. In Python, there is “for in” loop which is similar to foreach loop in
other languages. It can be used to iterate over a range and iterators.
Example:
The code uses a Python for loop that iterates over the values from 0 to 3 (not including
4), as specified by the range(0, n) construct. It will print the values of ‘i' in each iteration of the
loop.
n=4
for i in range(0, n):
print(i)
Output:
0
1
2
3
Function is a block of statements that return the specific task. The idea is to put some commonly
or repeatedly done tasks together and make a function so that instead of writing the same code again
and again for different inputs, we can do the function calls to reuse code contained in it over and over
again.
DEPARTMENT OF CSE, 3
PROGRAMMING WITH
Example :
def fun():
print("Welcome to GFG")
DEPARTMENT OF CSE, 3
PROGRAMMING WITH
After creating a function in Python we can call it by using the name of the functions
followed by parenthesis containing parameters of that particular function.
Example :
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
DEPARTMENT OF CSE, 3
PROGRAMMING WITH
C H A P T E R -4
4.1 INTRODUCTION
OOP Concepts :
Class in Python
Objects in Python
Polymorphism in Python
Encapsulation in Python
Inheritance in Python
A class is a collection of objects. A class contains the blueprints or the prototype from which the objects
are being created. It is a logical entity that contains some attributes and methods.
DEPARTMENT OF CSE, 3
PROGRAMMING WITH
3. Attributes are always public and can be accessed using the dot (.) operator.
Eg. : Myclass.Myattribute
class ClassName:
# Statement-1
.
.
.
# Statement-N
Example:
class Dog:
pass
In object oriented programming Python, The object is an entity that has a state and behavior associated
with it. It may be any real-world object like a mouse, keyboard, chair, table, pen, etc. Integers, strings,
floating-point numbers, even arrays, and dictionaries, are all objects. More specifically, any single
integer or any single string is an object. The number 12 is an object, the string “Hello, world” is an
object, a list is an object that can hold other objects, and so on.
An object consists of :
State: It is represented by the attributes of an object. It also reflects the properties of an object.
DEPARTMENT OF CSE, 3
PROGRAMMING WITH
Behavior: It is represented by the methods of an object. It also reflects the response of an object to other
objects.
Identity: It gives a unique name to an object and enables one object to interact with other objects.
To understand the state, behavior, and identity let us take the example of the class dog.
State or Attributes can be considered as the breed, age, or color of the dog.
Creating an Object :
This will create an object named obj of the class Dog defined above.
obj = Dog()
Class methods must have an extra first parameter in the method definition. We do not give a value for
this parameter when we call the method, Python provides it. If we have a method that takes no
arguments, then we still have to have one argument. This is similar to this pointer in C++ and this
reference in Java.
When we call a method of this object as myobject.method(arg1, arg2), this is automatically converted
by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self is about.
The init method is similar to constructors in C++ and Java. It is run as soon as an object of a class
is instantiated. The method is useful to do any initialization you want to do with your object. Now let us
define a class and create some objects using the self and init method.
DEPARTMENT OF CSE, 3
PROGRAMMING WITH
class Dog:
# class attribute
attr1 = "mammal"
# Instance attribute
self.name = name
# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
Output
Rodger is a mammal
My name is Rodger
My name is Tommy
DEPARTMENT OF CSE, 3
PROGRAMMING WITH
In Python object oriented Programming, Inheritance is the capability of one class to derive or inherit the
properties from another class. The class that derives properties is called the derived class or child class
and the class from which the properties are being derived is called the base class or parent class. The
benefits of inheritance are:
It provides the reusability of a code. We don’t have to write the same code again and again. Also, it
allows us to add more features to a class without modifying it.
It is transitive in nature, which means that if class B inherits from another class A, then all the
subclasses of B would automatically inherit from class A.
Types of Inheritance
Single Inheritance: Single-level inheritance enables a derived class to inherit characteristics from a
single-parent class.
Multilevel Inheritance: Multi-level inheritance enables a derived class to inherit properties from an
immediate parent class which in turn inherits properties from his parent class.
Hierarchical Inheritance: Hierarchical-level inheritance enables more than one derived class to inherit
properties from a parent class.
Multiple Inheritance: Multiple-level inheritance enables one derived class to inherit properties from
more than one base class.
In object oriented Programming Python, Polymorphism simply means having many forms. For example,
we need to determine if the given species of birds fly or not, using polymorphism we can do this using a
single function.
DEPARTMENT OF CSE, 3
PROGRAMMING WITH
Example : This code demonstrates the concept of Python oops inheritance and method overriding in
Python classes. It shows how subclasses can override methods defined in their parent class to provide
specific behavior while still inheriting other methods from the parent class.
class Bird:
def intro(self):
def flight(self):
class sparrow(Bird):
def flight(self):
class ostrich(Bird):
def flight(self):
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
DEPARTMENT OF CSE, 3
PROGRAMMING WITH
obj_spr.intro()obj_spr.flight()
obj_ost.intro()obj_ost.flight()
Output
In Python object oriented programming, Encapsulation is one of the fundamental concepts in object-
oriented programming (OOP). It describes the idea of wrapping data and the methods that work on data
within one unit. This puts restrictions on accessing variables and methods directly and can prevent the
accidental modification of data. To prevent accidental change, an object’s variable can only be changed
by an object’s method. Those types of variables are known as private variables. A class is an example
of encapsulation as it encapsulates all the data that is member functions, variables, etc.
DEPARTMENT OF CSE, 3
PROGRAMMING WITH
C H A P T E R -5
5.1 INTRODUCTION
Python SQLite3 module is used to integrate the SQLite database with Python. It is a standardized
Python DBI API 2.0 and provides a straightforward and simple-to-use interface for interacting with
SQLite databases. There is no need to install this module separately as it comes along with Python after
the 2.5x version.
Python comes with built-in support for SQLite through the sqlite3 module, which allows you to interact
with an SQLite database directly from Python code. This makes it an excellent choice for applications
that require a lightweight database without the overhead of a full database management system.
pysqlite is an external library in Python that provides SQLite database access. It was the original
interface to the SQLite relational database management system before it became integrated into
Python’s standard library as sqlite3. Since Python 2.5 and above, sqlite3 is included in Python’s
standard library, which essentially provides the same functionalities as pysqlite. If you are using Python
2.5 or later, it is recommended to use sqlite3 instead. Here’s a basic example of using sqlite3:
SQLite is a C-language library that implements a small, fast, self-contained, high-reliability, full-
featured, SQL database engine.
It is embedded into the end program. SQLite reads and writes directly to ordinary disk files. A complete
SQL database with multiple tables, indices, triggers, and views, is contained in a single disk file.
DEPARTMENT OF CSE, 4
PROGRAMMING WITH
It is used predominantly for applications that need a lightweight database without the need for a
network-accessible database management syste
Connecting to the SQLite Database can be established using the connect() method, passing the name of
the database to be accessed as a parameter. If that database does not exist, then it’ll be created.
sqliteConnection = sqlite3.connect('sql.db')
To execute some queries after the connection is being made. For that, a cursor has to be created using
the cursor() method on the connection instance, which will execute our SQL queries.
cursor = sqliteConnection.cursor()
print('DB Init')
The SQL query to be executed can be written in form of a string, and then executed by calling
the execute() method on the cursor object. Then, the result can be fetched from the server by using
the fetchall() method, which in this case, is the SQLite Version Number.
The below example will connect to an SQLite database and will run a simple query select
sqlite_version(); to find the version of the SQLite we are using.
Example:
DEPARTMENT OF CSE, 4
PROGRAMMING WITH
import sqlite3
try:
# Close the
cursor
cursor.close()
# Handle errors
except sqlite3.Error as error:
print('Error occurred - ',
error)
SQLite is a highly efficient, serverless, and self-contained SQL database engine that stands out
for its simplicity and ease of integration. Designed to be embedded within
DEPARTMENT OF CSE, 4
PROGRAMMING WITH
applications, SQLite eliminates the need for separate database server processes and complex
configurations.
1. SQLite is a lightweight, serverless, self-contained, and highly reliable SQL database engine. It is
widely used due to its simplicity, ease of setup and zero-configuration nature.
3. SQLite is ACID-compliant and implements most of the SQL standards, using a dynamically and
weakly typed SQL syntax that does not guarantee domain integrity.
4. One of the main benefits of using SQLite is that it is very easy to get started with. To create a new
database in SQLite, you simply need to create a new file on your filesystem and connect to it using the
SQLite3 API.
There are several reasons why you might choose to use SQLite in your project:
1. Ease of use: SQLite is very easy to get started with, as it requires no setup or configuration. You
can simply include the library in your project and start using it.
3. Lightweight: SQLite is a very lightweight database engine, with a small library size (typically less
than 1MB). This makes it well-suited for use in applications where the database is embedded directly
into the application binary, such as mobile apps.
DEPARTMENT OF CSE, 4
PROGRAMMING WITH
4. Serverless: As mentioned earlier, SQLite is a serverless database engine, which means there is no
need to set up and maintain a separate database server process. This makes it easy to deploy and
manage, as there are no additional dependencies to worry about.
5. Cross-platform: SQLite is available on many platforms, including Linux, macOS, and Windows,
making it a good choice for cross-platform development.
6. Standalone: SQLite stores all of the data in a single file on the filesystem, which makes it easy to
copy or backup the database.
7. High reliability: SQLite has been widely tested and used in production systems for many years, and
has a reputation for being a reliable and robust database engine.
In SQLite, DDL (Data Definition Language) is used to create and modify database objects such as
tables, indices, and views. Some examples of DDL statements in SQLite are:
DML (Data Modification Language) is used to modify the data stored in the database. Some examples
DQL (Data Query Language) is used to retrieve data from the database. Some examples of DQL
DEPARTMENT OF CSE, 4
PROGRAMMING WITH
SELECT: retrieves data from one or more tables in the database.
CHAPTER – 9
DEPARTMENT OF CSE, 4
PROGRAMMING WITH
ASSIGNMENT
DEPARTMENT OF CSE, 4
PROGRAMMING WITH
DEPARTMENT OF CSE, 4
PROGRAMMING WITH
SOLUTION
DEPARTMENT OF CSE, 4
PROGRAMMING WITH
DEPARTMENT OF CSE, 4
PROGRAMMING WITH
DEPARTMENT OF CSE, 5
PROGRAMMING WITH
SOLUTION
# score_calculator.py
def batscore(x):
runs = x['runs']
strike_rate = runs/x['balls']
score = runs//2 + (5 if runs >= 50 else 0) + (10 if runs >= 100 else 0) + (2 if strike_rate >= 80/100
return score
return {'name':x['name'],'batscore':score}
def bowlscore(x):
wkts = x['wkts']
economy_rate = x['runs']/x['overs']
fields=x['field']
score = 10*wkts + (10*fields if fields>=1 else 0 ) +(5 if wkts>=3 else 0) + (10 if wkts>=5 else 0) +
return score
return {'name':x['name'],'bowlscore':score}
DEPARTMENT OF CSE, 5
PROGRAMMING WITH
# main.py
players = [p1,p2,p3,p4,p5] # Making a list of dictionaries so that we can iterate through each dictionary
scores = {}
for i in players:
if i['role'] == 'bat':
score = score_calculator.batscore(i)
scores[i['name']] = score
print("'name':{},'batscore':{}".format(i['name'],score))
else:
score = score_calculator.bowlscore(i)
scores[i['name']] = score
DEPARTMENT OF CSE, 5
PROGRAMMING WITH
print("'name':{},'bowlscore':{}".format(i['name'],score))
max_scorer = max(scores,key=scores.get)
DEPARTMENT OF CSE, 5
PROGRAMMING WITH
DEPARTMENT OF CSE, 5
PROGRAMMING WITH
SOLUTION
# main.py
class book:
self.title=a
self.author=b
self.publisher=c
self.price=d
self.quan=q
royal=0
def get_title(self):
return self._title
def set_title(self,a):
self.title=a
return
def get_author(self):
return self.author
def set_author(self,b):
self.author=b
return
def get_publisher(self):
return self.publisher()
def set_publisher(self,c):
DEPARTMENT OF CSE, 5
PROGRAMMING WITH
self.publisher=c
return
def get_price(self):
return self.price
def
set_price(self,d):
self.price=d
return
def get_quan(self):
return self.quan
def set_quan(self,e):
self.quan=e
return
def royalty(self):
if self.quan<=500:
royal=.1*self.price*self.quan
royal=.125*self.price*(self.quan-500)+.1*self.price*500
elif self.quan>1500:
royal=.1*self.price*500+.125*self.price*1000+.15*self.price*(self.quan-1500)
return royal
class ebook(book):
"""E-BOOK Detais"""
def init(self,aa='PDF'):
DEPARTMENT OF CSE, 5
PROGRAMMING WITH
self._fromat=aa
DEPARTMENT OF CSE, 5
PROGRAMMING WITH
def get_format(self):
return self.format
def set_format(self,b):
self.format=b
return
def royalty(self):
if self.quan<=500:
royal=.1*self.price*self.quan
royal=.125*self.price*(self.quan-500)+.1*self.price*500
elif self.quan>1000:
royal=.1*self.price*500+.125*self.price*1000+.15*self.price*(self.quan-1500)
royal=royal-(.12*royal)
return royal
f=int(input(" Enter 1 for normal book and enter 2 for e book "))
x=book()
x.set_title(a)
x.set_author(b)
x.set_publisher(c)
x.set_price(d)
DEPARTMENT OF CSE, 5
PROGRAMMING WITH
x.set_quan(e)
y=ebook()
if f==1:
z=x.royalty()
\n".format(x.title,x.publisher,x.author,x.price,x.quan,z))
if f==2:
print("b")
z=y.royalty()
y.set_format(g)
Royalty is {} \n".format(y.title,y.publisher,y.author,y.price,y.quan,y.format,z))
DEPARTMENT OF CSE, 5
PROGRAMMING WITH
BIBLIOGRAPHY
For successfully completing my project report, I have taken references from the following
https://www.geeksforgeeks.org/
https://www.geeksforgeeks.org/python-data-types/
https://www.geeksforgeeks.org/loops-in-python/
https://www.geeksforgeeks.org/python-oops-concepts/
https://www.geeksforgeeks.org/introduction-to-sqlite/
https://www.geeksforgeeks.org/conditional-statements-in-python/
DEPARTMENT OF CSE, 6