[go: up one dir, main page]

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

Project Report Aryan Batra 19 Sep

Project Report Aryan Batra 19 Sep

Uploaded by

ashishmattoo985
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views72 pages

Project Report Aryan Batra 19 Sep

Project Report Aryan Batra 19 Sep

Uploaded by

ashishmattoo985
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 72

MOOC REPORT

ON
PROGRAMMING WITH PYTHON

Submitted in the partial fulfillment of requirement for the award of degree

BACHELOR OF TECHNOLOGY
IN
COMPUTER SCIENCE ENGINEERING

Submitted by

Aryan Batra
( 13 / 23 )

Under the guidance of

Prof. Kiranpal Kour

Department of Computer Science Engineering


Mahant Bachittar Singh College of Engineering and Technology,
Jammu 2024-2025
I

DECLARATION

I hereby declare that the MOOC Report entitled “PROGRAMMING WITH


PYTHON” is an authentic record of my own carried out as requirement for the
award of degree of BTECH (CSE) of Mahant Bachittar Singh College of
Engineering & Technology, Jammu.

Date : Aryan Batra


Roll No : 13/23

Certified that the above statement made by the student is correct to the best of my
knowledge and belief.

Ms. Kiranpal Kour

Course Coordinator, CSE Deptt


II

ACKNOWLEDGEMENT

It is my fortune that I had got opportunity to carry my MOOC course


“PROGRAMMING WITH PYTHON” under the supervision of Prof. Kiranpal
Kour in the department of Computer Science Engineering, Mahant Bachittar Singh
College of Engineering and Technology (MBSCET), Jeevan Nagar, Jammu
affiliated to University of Jammu. I would like to thanks from the deepest of my
heart for guiding and sharing their valuable knowledge with me.

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.

DATE : Aryan Batra


Roll No: 13/23
III

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,

functions, and modules. Object-Oriented Programming (OOP) principles about declaring

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

relational databases, specifically SQLite.


C O N T E N T S

DECLARATION I

ACKNOWLEDGEMENT II

ABSTRACT III

LIST OF TABLES IV

LIST OF FIGURES V

CHAPTER 1 INTRODUCTION TO PYTHON 1-10


1.1. Introduction 1
1.2. Python Interpreter 1-2
1.2.1. What are Intrepreters 1
1.2.2. How Intrepreters function in Python 2
1.3. Python Versions 3-4
1.3.1. Python 2x 3
1.3.2. Python 3x 4
1.3.3. Difference in Python 2x and 3x 4
1.4. Python Features 4-6
1.5. Basic Syntax In Python 6 - 10
1.5.1. Python Identifiers
6
1.5.2. Python Lines and Indentation
8
1.5.3. Python Multi Lines
Statements 9
1.5.4. Python Quotations 9
1.5.5. Python Multi Statements 10

CHAPTER 2 USING VARIABLES IN PYTHON


10 - 24
2.1. Introduction
10
2.2. What are Python Data Types
11
2.3. Numeric Data Types
2.4. Sequence Data Types 13
2.4.1. String Data Type 14 - 24
2.4.2. List Data Type 14
2.4.3. Tuple Data Type 16
2.4.4. Boolean Data Type 18
2.4.5. Set Data Type 20
2.4.6. Dictionary Data Type 22
24

CHAPTER 3 BASIC PROGRAMMING IN PYTHON 25 - 31


3.1. Introduction 25
3.2. Condtitional Statements 26 - 28
3.2.1. If statement 26
3.2.2. If else statement 26
3.2.3. Nested If else statement
27
3.2.4. If-elif-else statement
27
3.2.5. Ternary Conditional statement
28
3.3. Loop Statements
3.3.1. While loop 28 - 29
3.3.2. For loop 28
3.4. Using Functions 29
3.4.1. Creating a function 30 - 31
3.4.2. Calling a function 30
31

CHAPTER 4 OBJECT ORIENTED PROGRAMMING 32 - 39


USING PYTHON
4.1. Introduction 32
4.2. Python Class 33
4.3. Python Objects 33
4.4. Python self 35
4.5. Python init 35
4.6. Python Inheritance 37
4.7. Python Polymorphism 38
4.8. Python Encapsulation 39

CHAPTER 5 CONNECTING TO SQLITE 40 - 45


DATABASE 40
5.1. Introduction 41
5.2. Connecting to SQLite 43
5.3. SQLite Database 43
5.3.1. Advantages of SQLite 45
5.3.2. SQLite Commands
ASSIGNMENT 46-58

BIBLOGRAPHY 59

IV

LIST OF TABLES

S.NO TABLE NO TABLE NAME PAGE NO

1. 1.1 Python Keywords 7-8

2. 2.1 Numeric Data Types Examples 13


V

LIST OF FIGURES

TABLE

S.NO NO TABLE NAME PAGE NO

1. 2.1 Python Data Types 11

2. 3.1 Python Function 31

3. 4.1 Python Encapsulation 39

4. 5.1 SQLite Connection In Python 42


PROGRAMMING WITH

C H A P T E R - 1

INTRODUCTION TO PYTHON PROGRAMMING

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.

1.2 PYTHON INTERPRETER

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.

1.2.1 What are Interpreters?

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.

1.2.2 How interpreters function in Python?

Python interpreter is written in C programming language as we all know that C is


considered as mother of all programming languages, Python interpreter called “CPython”.
Initially in source code analysis, Python get source and check for some Indentation rule and
check for errors. if there are any errors Python stops its execution and make to modify to prevent
errors. This process is called Lexical analysis in python which states that dividing the source
code into list of individual tokens. In Byte code generation, once the python interpreter receives
the tokens, it generates AST (Abstract Structure tree) which coverts to byte code and then byte
code can be saved in (.py) extension. At last, by using Python Virtual Machine, interpreter loads
the machine language and PVM converts in into 0s and 1 s which prints the results.

1.3 PYTHON VERSIONS

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.

1.3.3 Difference in Python 2 & 3

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.

3. Storage of Strings : In Python 2, strings are stored as ASCII by default whereas, in


Python 3, strings are stored as UNICODE.

4. Division of Integers : In Python 2, the division of two integers resulted in an integral


value. For example, 9/2 yields 4 in Python 2 whereas the division of two integers results in a
floating-point value in Python 3. For example, 9/2 yields 4.5 in Python 3.

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.

8. Ease Of Syntax : The syntax of Python 2 is more complicated as compared to the


syntax of Python 3. Python 3 syntax is easy to understand.

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.

11. Backward Compatibility : It is possible to port Python 2 code to Python 3 but to do


this a lot of effort is required. On the other hand, Python 3 is not backwards compatible with
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.

1.4 FEATURES IN PYTHON

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.

4. Object-Oriented Language : One of the key features of Python is Object-Oriented


programming. Python supports object-oriented language and concepts of classes, object encapsulation,
etc.

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.

6. High-Level Language : Python is a high-level language. When we write programs in Python,


we do not need to remember the system architecture, nor do we need to manage the memory.

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.

1.5 BASIC SYNTAX IN PYTHON

1.5.1 Identifiers in python


Identifiers in Python are used to identify variables, objects, classes, functions, and other
identifiers. They are significant in writing effective code in the Python programming language
as they make complex programming tasks simpler. All identifiers have a specific set of rules
that need to be followed while creating identifiers : they should begin with either an alphabet (a-
z) or an underscore (_), and after that can contain any combination of alphanumeric characters

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.

Here are naming conventions for identifiers in Python:

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.

4. In Python programming language If the identifier ends with two trailing


underscores then the identifier can be called by a language-defined special name.

Table 1.1 : Python Keywords

and as assert

break class continue

def del elif

else except False

finally for from

global if import

in is lambda

None nonlocal not

DEPARTMENT OF CSE, 7
PROGRAMMING WITH
or pass raise

return True try

while with yield

1.5.2 Python Lines and Indentation

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

1.5.3 Python Multi-Line Statements


Python enables multi-line statements by allowing you to continue a statement onto the
following line by using backslashes (\). This helps make code easier to comprehend and breaks
up lengthy expressions into many lines for easier comprehension. As an alternative, you can
create multi-line statements without the usage of backslashes by using parentheses or brackets
for data structures like lists, dictionaries, or tuples.

Example Code :
result = 1 + \
2+\
3+\
4+\
5
print(result)

1.5.4 Quotations in Python


Python quotes are a great way to express thoughts and opinions, and Python makes it
easy to use them in code. Double quotes in Python provide two different types of quoting: raw
strings and regular string literals. Raw strings are best for specifying fixed patterns when a
backslash is used as an escape character, whereas regular string literals must be enclosed in
double quotes when the backslash needs to be used as an escape character. When dealing with
Python quotes, it's important to remember to use the same type of quote when starting and
ending your strings; otherwise, syntax errors may occur. With the right know-how, python
quotations can help make your code more concise and readable.
Example Code :
# This is a double quotes
print("Hello, World!")

DEPARTMENT OF CSE, 9
PROGRAMMING WITH

1.5.5 Multiple Statements on a Single Line


Semicolons (;) are used in Python to separate lines containing several statements.
In order to ensure readability, this concise syntax should only be used sparingly.
Example Code :
a = 1; b = 2; c = a + b

DEPARTMENT OF CSE, 1
PROGRAMMING WITH
C H A P T E R -2

USING VARIABLES IN PYTHON

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.

Fig 2.1 : Python Data Types

2.2 What are Python Data Types?

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

2.3 Numeric Data Types in Python

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.

3. Complex Numbers – A complex number is represented by a complex class. It is specified as


(real part) + (imaginary part)j . For example – 2+3j.

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.

a = 5print("Type of a: ", type(a))


b = 5.0print("\nType of b: ", type(b))
c = 2 + 4jprint("\nType of c: ", type(c))

Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>

Table 2.1 : Numeric Data Type Examples

INT LONG FLOAT COMPLEX

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-786 0122L -21.9 9.322e-36j

080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j

-0490 535633629843L -90. -.6545+0J

-0x260 -052318172735L -32.54e100 3e+26J

0x69 -4721885298529L 70.2-E12 4.53e-7j

2.4 Sequence Data Types in Python

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.

2.4.1 String Data Type

Strings in Python are arrays of bytes representing Unicode characters. A string is a


collection of one or more characters put in a single quote, double-quote, or triple-quote. In
Python, there is no character data type Python, a character is a string of length one. It is
represented by str class.

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.

String1 = 'Welcome to the Geeks World'


print("String with the use of Single Quotes: ")
print(String1)
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes:")
print(String1)
print(type(String1))
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
String1 = '''Geeks For Life'''
print("\nCreating a multiline String: ")
print(String1)

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

2. Accessing elements of String : In Python programming , individual characters of a


String can be accessed by using the method of Indexing. Negative Indexing allows negative
address references to access characters from the back of the String, e.g. -1 refers to the last
character, -2 refers to the second last character, and so on.

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

2.4.2 List Data Type

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.

List = []print("Initial blank List: ")


print(List)
List = ['GeeksForGeeks'] print("\
nList with the use of String: ")
print(List)
List = ["Geeks", "For", "Geeks"] print("\
nList containing multiple values: ")
print(List[0])
print(List[2])
List = [['Geeks', 'For'], ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)

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

2.4.3 Tuple Data Type

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.

tuple1 = tuple([1, 2, 3, 4, 5])


print("First element of tuple")
print(tuple1[0])
print("\nLast element of tuple")
print(tuple1[-1])
print("\nThird last element of tuple")
print(tuple1[-3])

Output:
First element of tuple

DEPARTMENT OF CSE, 1
PROGRAMMING WITH
1
Last element of tuple
5
Third last element of tuple
3

2.4.4 Boolean Data Type

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

set1 = set(["Geeks", "For", "Geeks"])


print("\nInitial set")
print(set1) print("\
nElements of set: ") for i in
set1:
print(i, end=" ")
print("Geeks" in set1)

Output:
Initial set:
{'Geeks', 'For'}
Elements of set:
Geeks For
True

2.4.6 Dictionary Data Type in Python

A dictionary in Python is an unordered collection of data values, used to store data


values like a map, unlike other Python Data Types that hold only a single value as an element, a
Dictionary holds a key: value pair. Key-value is provided in the dictionary to make it more
optimized. Each key-value pair in a Dictionary is separated by a colon : , whereas each key is
separated by a ‘comma’.

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'}

2. Accessing Key-value in Dictionary : In order to access the items of a dictionary refer


to its key name. Key can be used inside square brackets. There is also a method called get() that
will also help in accessing the element from a dictionary.

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’ .

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}


print("Accessing a element using key:")
print(Dict['name'])
print("Accessing a element using get:")
print(Dict.get(3))

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

BASIC PROGRAMMING IN PYTHON


3.1 INTRODUCTION

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.

3.2 CONDITIONAL STATEMENTS

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.

3.2.1 If Conditional Statement in Python


If the simple code of block is to be performed if the condition holds then the if statement
is used. Here the condition mentioned holds then the code of the block runs otherwise not.

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

3.2.2 If else Conditional Statement in Python


In a conditional if Statement the additional block of code is merged as an else statement
which is performed when if condition is false.

Syntax of Python If-Else:

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

3.2.4 If-elif-else Conditional Statements in Python


The if statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest of the
ladder is bypassed. If none of the conditions is true, then the final “else” statement will be
executed.

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

3.2.5 Ternary Expression Conditional Statements in Python


The Python ternary Expression determines if a condition is true or false and then returns
the appropriate value in accordance with the result. The ternary Expression is useful in cases
where we need to assign a value to a variable based on a simple condition, and we want to keep
our code more concise — all in just one line of code.

Syntax: [on_true] if [expression] else [on_false]


expression: conditional_expression | lambda_expr

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

3.3 LOOPING STATEMENTS

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.

3.3.1 While Loop in Python


In Python, a while loop is used to execute a block of statements repeatedly until a given
condition is satisfied. When the condition becomes false, the line immediately after the loop in
the program is executed.

Python While Loop Syntax:


while expression:
statement(s)

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

3.3.2 For Loop in Python

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.

For Loop Syntax:


for iterator_var in sequence:
statements(s)

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

3.4 Python Functions

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

Some Benefits of Using Functions :


1. Increase Code Readability
2. Increase Code Reusability

Python Function Declaration :


The syntax to declare a function is

Fig 3.1 : Python Function

3.4.1 Creating a Function in Python


We can define a function in Python, using the def keyword. We can add any type of
functionalities and properties to it as we require. By the following example, we can understand
how to write a function in Python. In this way we can create Python function definition by using
def keyword.

Example :

def fun():
print("Welcome to GFG")

3.4.2 Calling a Function in Python

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 :

def add(num1: int, num2: int) -> int:


num3 = num1 + num2
return num3

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

OBJECT ORIENTED PROGRAMMING IN PYTHON

4.1 INTRODUCTION

Object Oriented Programming is a fundamental concept in Python, empowering developers to build


modular, maintainable, and scalable applications. By understanding the core OOP principles—classes,
objects, inheritance, encapsulation, polymorphism, and abstraction—programmers can leverage the full
potential of Python’s OOP capabilities to design elegant and efficient solutions to complex problems.
Object-oriented Programming (OOPs) is a programming paradigm that uses objects and classes in
programming. It aims to implement real-world entities like inheritance, polymorphisms, encapsulation,
etc. in the programming. The main concept of object-oriented Programming (OOPs) or oops concepts in
Python is to bind the data and the functions that work together as a single unit so that no other part of
the code can access this data.

OOP Concepts :

Class in Python

Objects in Python

Polymorphism in Python

Encapsulation in Python

Inheritance in Python

Data Abstraction in Python

4.2 Python Class

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

Some points on Python class:

1. Classes are created by keyword class.

2. Attributes are the variables that belong to a class.

3. Attributes are always public and can be accessed using the dot (.) operator.

Eg. : Myclass.Myattribute

Class Definition Syntax :

class ClassName:
# Statement-1
.
.
.
# Statement-N

Example:

class Dog:

pass

4.3 Python Objects

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.

The identity can be considered as the name of the dog.

State or Attributes can be considered as the breed, age, or color of the dog.

The behavior can be considered as to whether the dog is eating or sleeping.

Creating an Object :

This will create an object named obj of the class Dog defined above.

obj = Dog()

4.4 The Python self

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.

4.5 The Python init Method

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.

Creating a class and object with class and instance attributes

DEPARTMENT OF CSE, 3
PROGRAMMING WITH

class Dog:

# class attribute

attr1 = "mammal"

# Instance attribute

def init (self, name):

self.name = name

# Driver code

# Object instantiation

Rodger = Dog("Rodger")

Tommy = Dog("Tommy")

# Accessing class attributes

print("Rodger is a {}".format(Rodger. class .attr1))

print("Tommy is also a {}".format(Tommy. class .attr1))

# Accessing instance attributes

print("My name is {}".format(Rodger.name))

print("My name is {}".format(Tommy.name))

Output

Rodger is a mammal

Tommy is also a mammal

My name is Rodger

My name is Tommy

DEPARTMENT OF CSE, 3
PROGRAMMING WITH

4.6 Python Inheritance

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 represents real-world relationships well.

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.

4.7 Python Polymorphism

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):

print("There are many types of birds.")

def flight(self):

print("Most of the birds can fly but some cannot.")

class sparrow(Bird):

def flight(self):

print("Sparrows can fly.")

class ostrich(Bird):

def flight(self):

print("Ostriches cannot fly.")

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

There are many types of birds.

Most of the birds can fly but some cannot.

There are many types of birds.

Sparrows can fly.

There are many types of birds.

Ostriches cannot fly.

4.8 Python Encapsulation

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.

Fig 4.1 : Encapsulation

DEPARTMENT OF CSE, 3
PROGRAMMING WITH

C H A P T E R -5

CONNECTING TO SQLITE DATABASE IN PYTHON

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:

Characteristics of SQLite Database :

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

5.2 CONNECTING TO DATABASE

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.

query = 'SQL query;'


cursor.execute(query)
result = cursor.fetchall()
print('SQLite Version is {}'.format(result))

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:

# Connect to DB and create a cursor


sqliteConnection =
sqlite3.connect('sql.db') cursor =
sqliteConnection.cursor() print('DB Init')

# Write a query and execute it with


cursor query = 'select sqlite_version();'
cursor.execute(query)

# Fetch and output


result result =
cursor.fetchall()
print('SQLite Version is {}'.format(result))

# Close the
cursor
cursor.close()

# Handle errors
except sqlite3.Error as error:
print('Error occurred - ',
error)

# Close DB Connection irrespective of


success # or failure
finally:

Fig 5.1 : SQLITE CONNECTION IN PYTHON

5.3 SQLITE DATABASE

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.

2. SQLite is an in-process library that implements a self-contained, serverless, zero-


configuration, transactional SQL database engine. It is a popular choice as an embedded database
for local/client storage in application software such as web browsers. It is also used in many other
applications that need a lightweight, embedded database.

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.

5.3.1 ADVANTAGES OF SQLITE

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.

2. Embeddability: SQLite is designed to be embedded into other applications. It is a self-contained,


serverless database engine, which means you can include it in your application without the need for a
separate database server.

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.

5.3.2 SQLITE COMMANDS

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:

CREATE TABLE: creates a new table in the database.

ALTER TABLE: modifies an existing table in the database.

DROP TABLE: deletes a table from the database.

CREATE INDEX: creates a new index on a table.

DROP INDEX: deletes an index from a table.

DML (Data Modification Language) is used to modify the data stored in the database. Some examples

of DML statements in SQLite are:

INSERT INTO: inserts a new row into a table.

UPDATE: updates the data in one or more rows of a table.

DELETE FROM: deletes one or more rows from a table

DQL (Data Query Language) is used to retrieve data from the database. Some examples of DQL

statements in SQLite are:

DEPARTMENT OF CSE, 4
PROGRAMMING WITH
SELECT: retrieves data from one or more tables in the database.

JOIN: retrieves data from multiple tables based on a common field.

GROUP BY: groups the results of a query by one or more fields.

HAVING: filters the results of a query based on a condition

CHAPTER – 9

DEPARTMENT OF CSE, 4
PROGRAMMING WITH
ASSIGNMENT

DEPARTMENT OF CSE, 4
PROGRAMMING WITH

DEPARTMENT OF CSE, 4
PROGRAMMING WITH

SOLUTION

Your reason for


Data field identifier Data type Example using this
data type
Names may
contain letters
player_name String Virat Kohli
and any other
characters.
Country name
may contain
country String India
letters and any
other characters.
fours Integer 120
Number of
Number_of_matches integer 339 matches contain
integer value
india=["virat
kohli",""m.s.dhoni",
A changeable
"yuvraj singh","rohit
Team List collection of
sharma","Bhuvneshw
player names.
ar
kumar",""a.rahane"]
p1={'name':'Virat
Kohli', 'runs':25238, This is a
'4(fours)':120,'6(sixes collection of
player_stats Dictionary
)':80, 'balls':119, relevant player
'role':'bat', stats.
'field':0,’100’:83}
Run rate is the
runs required per
run_rate Float 3.2 delivery. This
can have decimal
values.

DEPARTMENT OF CSE, 4
PROGRAMMING WITH

DEPARTMENT OF CSE, 4
PROGRAMMING WITH

DEPARTMENT OF CSE, 5
PROGRAMMING WITH

SOLUTION

# score_calculator.py

# functions used for score calculation

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

and strike_rate <= 1 else 0) + (4 if strike_rate > 1 else 0) + x['4'] + x['6']*2

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) +

(4 if economy_rate>=3.5 and economy_rate<=4.5 else 0) + (7 if economy_rate>=2 and

economy_rate<3.5 else 0) + (10 if economy_rate<2 else 0)

return score

return {'name':x['name'],'bowlscore':score}

DEPARTMENT OF CSE, 5
PROGRAMMING WITH

# main.py

import score_calculator #Importing score_calculator module

#Giving Inputs as dictionary

p1={'name':'Virat Kohli', 'role':'bat', 'runs':112, '4':10, '6':0, 'balls':119, 'field':0}

p2={'name':'du Plessis', 'role':'bat', 'runs':120, '4':11, '6':2, 'balls':112, 'field':0}

p3={'name':'Bhuvneshwar Kumar', 'role':'bowl', 'wkts':1, 'overs':10, 'runs':71, 'field':1}

p4={'name':'Yuzvendra Chahal', 'role':'bowl', 'wkts':2, 'overs':10, 'runs':45, 'field':0}

p5={'name':'Kuldeep Yadav', 'role':'bowl', 'wkts':3, 'overs':10, 'runs':34, 'field':0}

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)

print("The maximum scorer is {} with score {}".format(max_scorer,max(scores.values())))

DEPARTMENT OF CSE, 5
PROGRAMMING WITH

DEPARTMENT OF CSE, 5
PROGRAMMING WITH
SOLUTION

# main.py

class book:

""" BOOk detaails."""

def init (self,a='Concept of physics',b='R.K Bansal',c='S>L Arorah',d=500,q=600 ):

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

elif self.quan>500 and self.quan<=1500:

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

elif self.quan>500 and self.quan<=1500:

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

a=input(" Enter the title of the book ")

b=input(" Enter the author ofthe book ")

c=input(" Enter the publisher of book ")

d=int(input(" Enter the price of the book "))

e=int(input(" Enter the total number of books sold "))

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()

print(" Title is {} \n Publisher is {} \n Author is {} \n Price was {} \n Total sold {} \n Royalty is {}

\n".format(x.title,x.publisher,x.author,x.price,x.quan,z))

if f==2:

print("b")

g=input("Enter the format of ebook")

z=y.royalty()

y.set_format(g)

print(" Title is {} \n Publisher is {} \n Author is {} \n Price was {} \n Total sold {} \n Format is {} \n

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

You might also like