python file

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 30

GOVERNMENT COLLEGE OF

ENGINEERING AND TECHNOLOGY

PYTHON PROGRAMMING

Name: Avni Mahajan


Branch: Computer

Roll No.: 231103010

Semester: 3rd

Course Title: MooC

Course No.: MOC3311

Submitted to: Ms. Simmi Dutta

1|GCET JAMMU
TOPICS COVERED
S.NO. TOPIC PAGE NO.

1. Introduction to python 3-4

2. Basic syntax and Data 5-8


types
3. Operators and control 9-15
conditions
4. Functions and Modules 16-17

5. Data Structures 18-19

6. File and Exception 20-21


Handling
7. Object Oriented 22-24
Programming(OOP)
8. Python projects 25-28

1. Introduction to Python
2|GCET JAMMU
Python is a popular, versatile, and beginner-friendly programming
language known for its simplicity and readability. It was created by Guido
van Rossum and first released in 1991, Python has become one of the
most widely used languages in software development, data science,
machine learning, web development, automation, and more.Python is
used across fields and supports integration with other languages like C
and C++.Python’s design emphasizes readability, making it a good fit for
both beginners and experienced developers aiming to build complex
applications or prototypes rapidly.

History and Evolution of Python

Python was developed in the late 1980s by Guido van Rossum, and its first
official release was in 1991. Named after the British comedy group Monty
Python, the language was designed with the goal of emphasizing code
readability. Over the years, Python has undergone several iterations, with
major versions including Python 2.x and Python 3.x. Python 3, released in
2008, introduced significant changes that improved the language but also
broke backward compatibility, leading to a gradual migration from Python
2.

Key Features and Applications

 Readable and Simple Syntax: Python’s syntax resembles natural


language, making it accessible and easy to learn.

 Interpreted Language: Python is executed line-by-line, which


simplifies debugging and testing.

 Cross-Platform Compatibility: Python runs on various platforms,


including Windows, macOS, and Linux.

 Extensive Libraries and Frameworks: Python boasts a rich


ecosystem of libraries (e.g., NumPy, Pandas, TensorFlow) that
support everything from data analysis to web development.

 Dynamic Typing: Variables don’t require explicit declaration of types,


offering flexibility and ease in development.

 Community Support: Python has an active community contributing


to its development and providing support through documentation,
forums, and open-source projects

3|GCET JAMMU
Applications: Python is widely used in fields such as:

 Web Development (using Django, Flask)

 Automation and Scripting

 Software Development

 Game Development

Installing Python and Setting Up the Environment

1. Download Python: Visit the official Python website Python.org to


download the installer for your operating system.

2. Run the Installer: Follow the instructions provided by the installer.


Ensure you check the option to add Python to your system’s PATH.

3. Verify Installation: Open a terminal or command prompt, type


python --version, and press Enter. If installed correctly, the terminal
should display the Python version.

4. Set Up an IDE: Install an integrated development environment (IDE)


like VS Code, PyCharm, or Jupyter Notebook for an improved
development experience.

Writing and Running Python Scripts

1. Using a Text Editor or IDE:

o Open your preferred text editor or IDE.

o Create a new file with the .py extension (e.g., hello.py).

o Write a simple script, like printing a greeting: print("Hello,


World!")

2. Running the Script:

o Open a terminal in the directory where your script is saved.

o Run the script by typing: python hello.py.

4|GCET JAMMU
2. Basic Syntax and Data Types
Python’s syntax is designed to be clean, readable, and easy to follow.
Understanding the basic structure helps you write well-organized and
error-free code.
Indentation: Python relies on indentation (whitespace at the beginning of
a line) to define the scope of loops, functions, and other structures. This is
unlike many other languages that use braces {} for code blocks.The
standard indentation is 4 spaces. Indentation is crucial in Python, as
incorrect indentation can cause errors.
Comments: Comments are used to annotate code, making it easier to
understand. Python ignores comments when executing.
 Single-line comments begin with a #
 Multi-line comments can be made using triple quotes, typically for
docstrings in functions or classes.
Data types in python:

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:

1. Numeric Data Types in Python

5|GCET JAMMU
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 .

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

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

 Complex Numbers – A complex number is represented by a complex


class. It is specified as (real part) + (imaginary part)j . For example –
2+3j.

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

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

3. Boolean Data Type in Python

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
6|GCET JAMMU
Boolean context as well and determined to be true or false. It is denoted
by the class bool.

4. Set Data Type in Python

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.

5. Sequence Data Types in Python

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

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.
Strings in Python can be created using single quotes, double quotes, or
even triple quotes.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.

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.Lists in Python can be created by just placing the
sequence inside the square brackets[].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.

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.

7|GCET JAMMU
tuples cannot be modified after it is created. It is represented by a tuple
class.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.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.

Type casting and conversion :

Type Casting is the method to convert the Python variable datatype into a
certain data type in order to perform the required operation by users. In
this article, we will see the various techniques for typecasting. There can
be two types of Type Casting in Python:

Implicit Type Conversion in Python

In this, method, Python converts the datatype into another datatype


automatically. Users don’t have to involve in this process.

Explicit Type Conversion in Python

In this method, Python needs user involvement to convert the variable


data type into the required data type. Mainly type casting can be done
with these data type functions:

 Int(): Python Int() function take float or string as an argument and


returns int type object.

 float(): Python float() function take int or string as an argument and


return float type object.

 str(): Python str() function takes float or int as an argument and


returns string type object.

Type Conversion in Python:

Python defines type conversion functions to directly convert one data type
to another which is useful in day-to-day and competitive programming.
This article is aimed at providing information about certain conversion
functions.There are two types of Type Conversion in Python:

Implicit Type Conversion in Python

8|GCET JAMMU
In Implicit type conversion of data types in Python, the Python interpreter
automatically converts one data type to another without any user
involvement.

Explicit Type Conversion in Python

In Explicit Type Conversion in Python, the data type is manually changed


by the user as per their requirement. With explicit type conversion, there
is a risk of data loss since we are forcing an expression to be changed in
some specific data type.

3. Operators and control


structures in python
Operators:Operators in general are used to perform operations on values
and variables. These are standard symbols used for logical and arithmetic
operations.

Types of Operators in Python:

1) Arithmetic Operators in Python

Arithmetic operators are used to perform basic mathematical operations


like addition, subtraction, multiplication, and division.

Operat Description Syntax

9|GCET JAMMU
or
+ Addition: adds two operand x +y
- Subtraction: subtracts two operands x –y
* Multiplication: multiplies two operands x *y
/ Division (float): divides the first operand by the x /y
second
// Division (floor): divides the first operand by the x // y
second
% Modulus: returns the remainder when the first x%y
operand is divided by the second
** Power: Returns first raised to power second x ** y

2) Relational operator:

Relational operators are used to compare the values of two operands


(elements being compared). When comparing strings, the comparison is
based on the alphabetical order of their characters (lexicographic order).

Operat Description Syntax


or
Python Equality == Equal to: True if both a==b
Operators operands are equal.
Inequality Operators != Not equal to: True if operands a==b
are not equal.
Greater than Sign > Greater than: True if the left a==b
operand is greater than the
right.
Less than Sign < Less than: True if the left a==b
operand is less than the
right.
Greater than or Equal >= Greater than or equal to: True a==b
to Sign if left operand is greater than
or equal to the right.
Less than or Equal to <= Less than or equal to: True if a==b
Sign left operand is less than or
equal to the right.
Chaining comparison It Consist of mixture of above a==b
operators Operators.

Python Logical Operators

Python logical operators are used to combine conditional statements,


allowing you to perform operations based on multiple conditions.
These Python operators, alongside arithmetic operators, are special
10 | G C E T J A M M U
symbols used to carry out computations on values and variables.Logical
operators are used on conditional statements (either True or False). They
perform Logical AND, Logical OR, and Logical NOT operations.

Operato Description Syntax Example


r
and Returns True if both the x and y x>7 and x>10
operands are true.
or Returns True if either of the x or y x<7 or x>15
operands is true
not Returns True if the operand is not x not(x>7 and x>
false 10)
Truth Table for Logical Operators in Python

X Y X and Y not(X) not(Y)


T T T F F
T F T F T
F T T T F
F F F T T

Python Bitwise Operators

Bitwise operators are used to perform bitwise calculations on integers.


The integers are first converted into binary and then operations are
performed on each bit or corresponding pair of bits, hence the name
bitwise operators. The result is then returned in decimal format.

Operato Name Description Synta


r x
Bitwise & Bitwise Result bit 1, if both operand bits x&y
AND AND are 1; otherwise results bit 0.
operator
Bitwise OR | Bitwise Result bit 1, if any of the operand x|y
operator OR bit is 1; otherwise results bit 0.
Bitwise ^ Bitwise Result bit 1, if any of the operand x^y
XOR XOR bit is 1 but not both, otherwise
operator results bit 0.
Bitwise ~ Bitwise Inverts individual bits. ~x
NOT NOT
operator
Bitwise >> Bitwise The left operand’s value is x>>
right shift right moved toward right by the
shift number of bits
specified by the right operand.

11 | G C E T J A M M U
Bitwise left << Bitwise The left operand’s value is x<<
shift left moved toward left by the
shift number of bits
specified by the right operand.

Assignment Operators:

Assignment Operators are used to assign values to variables. This


operator is used to assign the value of the right side of the expression to
the left side operand.The value the operator operates on is known as the
Operand.

Assignment operators in Python:


Operators Sign Description Syntax
Assignment = Assign the value of the right side of the c=a+b
Operator expression to the left side operand.
Addition += Add right side operand with left side operand and a += b
Assignment then assign the result to left operand.
Operator
Subtraction -= Subtract right side operand from left side a -= b
Assignment operand and then assign the result to left
Operator operand.
Multiplication *= Multiply right operand with left operand and then a *= b
Assignment assign the result to the left operand.
Operator
Division /= Divide left operand with right operand and then a /= b
Assignment assign the result to the left operand.
Operator
Modulus %= Divides the left operand with the right operand a %= b
Assignment and then assign the remainder to the left
Operator operand.
Floor Division //= Divide left operand with right operand and then a //= b
Assignment assign the value(floor) to left operand.
Operator
Exponentiation **= Calculate exponent(raise power) value using a **= b
Assignment operands and then assign the result to left
Operator operand.
Bitwise AND &= Performs Bitwise AND on operands and assign the a &= b
Assignment result to left operand.
Operator
Bitwise OR |= Performs Bitwise OR on operands and assign the a |= b
Assignment value to left operand.
Operator
Bitwise XOR ^= Performs Bitwise XOR on operands and assign the a ^= b
Assignment value to left operand.
Operator
Bitwise Right Shift >>= Performs Bitwise right shift on operands and a >>= b
Assignment assign the result to left operand.
Operator
<<= Performs Bitwise left shift on operands and assign a <<= b
12 | G C E T J A M M U
Bitwise Left Shift the result to left operand.
Assignment
Operator
Walrus Operator := Assign a value to a variable within an expression. a := exp

Control Structures in Python:


Control Structures are just a way to specify flow of control in programs.
Any algorithm or program can be more clear and understood if they use
self-contained modules called as logic or control structures. It basically
analyzes and chooses in which direction a program flows based on certain
parameters or conditions.

Selection/Decision Control Statements:


The statements used in selection control structures are also referred to as
branching statements or, as their fundamental role is to make decisions,
decision control statements. A program can test many conditions using
these selection statements, and depending on whether the given
condition is true or not, it can execute different code blocks.. Here are
some most commonly used control structures:

1) Only if 2) if-else 3) The nested if 4) The complete if-


elif-else

Simple if:If statements in Python are called control flow statements. The
selection statements assist us in running a certain piece of code, but only
in certain circumstances. There is only one condition to test in a basic if
statement.

The if statement's fundamental structure is as follows:

Syntax

1. if <conditional expression> :

2. The code block to be executed if the condition is True

These statements will always be executed. They are part of the main
code.

Code:

age = 18

if age >= 18:

print("You are eligible to vote.")


if-else

13 | G C E T J A M M U
If the condition given in if is False, the if-else block will perform the code
t=given in the else block.

number = -5

if number > 0:

print("The number is positive.")

else:
The nested if:
print("The number is negative.")
A nested
Output: if is an if statement placed inside another if (or elif or else)
block. This allows you to add additional conditions that only apply if the
The
first number is negative.
condition is true. Nested if statements are useful when you need to
check multiple conditions in a structured way.

Example of a Nested if

Let's say we want to check if a person is eligible to vote and, if they are
eligible, whether they are eligible to run for office.
gg
age = 25
citizen = True
# First check if the person is eligible to vote
if age >= 18:
if citizen:
print("You are eligible to vote.")

# Nested if to check eligibility to run for office


if age >= 30:
print("You are also eligible to run for office.")
else:
print("You are not old enough to run for office.")
else:
print("Only citizens can vote.")
else:
print("You are not old enough to vote.")

OUTPUT:
4)
Youif-elif-else:
are eligible to vote.
You are not old enough to run for office. 14 | G C E T J A M M U
A complete if-elif-else structure in Python allows you to handle multiple
conditions in sequence. It begins with an if condition, followed by one or
more elif (short for "else if") conditions, and ends with an optional else
block. Each condition is checked in order, and only the first condition that
is True will execute its block of code.

age = 45

if age < 13:

print("You are a child.")

elif age < 20:

print("You are a teenager.")

elif age < 60:

print("You are an adult.")

else:

print("You are a senior.")

Output:

You are an adult.

Iteration logic, or repetitive flow:


Iteration logic, or repetitive flow, in programming refers to executing a
block of code multiple times. This is typically done using loops, which
repeat a set of instructions until a specified condition is met. In Python,
the two main types of loops are for loops and while loops.
1)For loop:
A for loop is used to iterate over a sequence, like a list, tuple, dictionary,
set, or string. It repeats for each item in the sequence.Example: Using a
for loop to print each element in a list.

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:

print(fruit)

Output:
2)While loop
apple
A while loop repeats as long as a condition remains True. It’s useful when
banana
the number of iterations isn’t known beforehand. Example: Using a while
loop
cherryto count dow

15 | G C E T J A M M U
3)Using break and continue
 break: Exits the loop early when a condition is met.
 continue: Skips the current iteration and moves to the next.
Example: break and continue

for number in range(1, 6):

if number == 3:

continue # skip number 3

if number == 5:

break # stop the loop when number is 5

print(number)

Output:

4. Functions and Modules


16 | G C E T J A M M U
Functions in Python

A function is a block of reusable code that performs a specific task.


Functions allow you to divide your code into smaller, modular pieces,
which can be called as needed throughout a program.

Defining a Function

To define a function, use the def keyword, followed by the function name
and parentheses () containing any parameters.

Types of Functions in Python


Below are the different types of functions in Python:
 Built-in library function: These are Standard functions in Python
that are available to use.
 User-defined function: We can create our own functions based on
our requirements.
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.
Calling a Function in Python:After creating a function in Python we can
call it by using the name of the functions Python followed by parenthesis
containing parameters of that particular function. Below is the example for
calling def function Python.
Python Function Arguments
Arguments are the values passed inside the parenthesis of the function. A
function can have any number of arguments separated by a comma.
In this example, we will create a simple function in Python to check
whether the number passed as an argument to the function is even or
odd.
Types of Python Function Arguments: Python supports various types
of arguments that can be passed at the time of the function call. In
Python, we have the following function argument types in Python:
Default ArgumentsA default argument is a parameter that assumes a
default value if a value is not provided in the function call for that
argument. The following example illustrates Default arguments to write
functions in Python.

17 | G C E T J A M M U
Return Statement in Python Function: The function return statement
is used to exit from a function and go back to the function caller and
return the specified value or data item to the caller. The syntax for the
return statement is:
return [expression_list]
The return statement can consist of a variable, an expression, or a
constant which is returned at the end of the function execution. If none of
the above is present with the return statement a None object is returned.
Pass by Reference and Pass by Value: One important thing to note is,
in Python every variable name is a reference. When we pass a variable to
a function , a new reference to the object is created.
When we pass a reference and change the received reference to
something else, the connection between the passed and received
parameters is broken. For example, consider the below program as
follows:

Modules in Python:
A module is a file containing Python code (usually a .py file) that defines
functions, classes, and variables. Modules help organize code by grouping
related functions and data. You can import modules into your program to
use the functions and variables they contain.
Creating and Importing a Module
Creating a Module: Save your code in a file with a .py extension.
Importing a Module: Use the import statement to use functions from
mymath.py in another Python file.
Importing Specific Functions:You can import specific functions or
variables from a module using from import .
Using Built-in and External Modules: Python has many built-in
modules, such as math, datetime, and random. You can also install and
use third-party modules with pip.

Scope of variables:
Scope of Variables
The scope of a variable refers to the regions in the code where the
variable is accessible. Python has four main scopes, which follow the
LEGB rule:
1. Local: Variables defined within a function.
2. Enclosing: Variables in the enclosing function, typically for nested
functions.
3. Global: Variables defined at the top level of a script or module.

18 | G C E T J A M M U
4. Built-in: Names that are always available in Python, such as
keywords and functions like print() and len().

5. Data Structures
A data structure is a storage that is used to store and organize data.
It is a way of arranging data on a computer so that it can be accessed
and updated efficiently.A data structure is not only used for organizing
the data. It is also used for processing, retrieving, and storing data.
Python has several built-in data structures that allow for efficient
storage and manipulation of data. Here's an overview of the primary
data structures you'll encounter in Python:

1. Lists

 Definition: Ordered, mutable collections that allow duplicate


elements.
 Syntax: my_list = [1, 2, 3, 4]
 Key Operations: Append (.append()), insert (.insert()), remove
(.remove()), pop (.pop()), slicing, indexing.
 Use Case: Use lists when you need a collection of ordered items
that might change in size or content.

2. Tuples

 Definition: Ordered, immutable collections, allowing duplicate


elements.
 Syntax: my_tuple = (1, 2, 3, 4)
 Key Operations: Indexing, slicing, unpacking.
 Use Case: Use tuples when you need a fixed-size collection of
elements that should not be changed, like coordinates or fixed data
sets.

3. Sets

 Definition: Unordered collections of unique elements.


 Syntax: my_set = {1, 2, 3, 4}

19 | G C E T J A M M U
 Key Operations: Add (.add()), remove (.remove()), union (|),
intersection (&), difference (-).
 Use Case: Use sets when you need to store unique items or
perform set operations like union, intersection, and difference.

4. Dictionaries

 Definition: Key-value pairs, where each key must be unique.


 Syntax: my_dict = {"name": "Alice", "age": 25}
 Key Operations: Access by key (my_dict["name"]), add or update
entries, delete (.pop()), .keys(), .values(), .items().
 Use Case: Use dictionaries when you need to map unique keys to
specific values, like a database record or JSON-like data structure.

5. Other Structures

 Strings: While technically not a "data structure," strings (str) in


Python are immutable sequences of characters, often used similarly
to lists.
 Named Tuples: Similar to tuples, but with named fields for easier
readability.
Each of these data structures offers unique advantages and is chosen
based on the problem's specific requirements.

20 | G C E T J A M M U
6. File and exception Handling
Python file handling refers to the process of working with files on the
filesystem. It involves operations such as reading from files, writing to
files, appending data, and managing file pointers .
Python File Open
Before performing any operation on the file like reading or writing, first,
we have to open that file. For this, we should use Python’s inbuilt
function open() but at the time of opening, we have to specify the mode,
which represents the purpose of the opening file.
f = open(filename, mode)
Where the following mode is supported:
1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already
contains some data, then it will be overridden but if the file is not
present then it creates the file as well.
3. a: open an existing file for append operation. It won’t override
existing data.
4. r+: To read and write data into the file. This mode does not override
the existing data, but you can modify the data starting from the
beginning of the file.
5. w+: To write and read data. It overwrites the previous file if one
exists, it will truncate the file to zero length or create a file if it does
not exist.
6. a+: To append and read data from the file. It won’t override existing
data.

Exceptions: Exceptions are raised when the program is syntactically


correct, but the code results in an error. This error does not stop the
execution of the program, however, it changes the normal flow of the
program.

21 | G C E T J A M M U
Different types of exceptions in python :
 SyntaxError: This exception is raised when the interpreter
encounters a syntax error in the code, such as a misspelled
keyword, a missing colon, or an unbalanced parenthesis.
 TypeError: This exception is raised when an operation or function is
applied to an object of the wrong type, such as adding a string to an
integer.
 NameError: This exception is raised when a variable or function
name is not found in the current scope.
 IndexError: This exception is raised when an index is out of range
for a list, tuple, or other sequence types.

Try and Except Statement – Catching Exceptions: Try and


except statements are used to catch and handle exceptions in Python.
Statements that can raise exceptions are wrapped inside the try block
and the statements that handle the exception are written inside except
block.Example:
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")
Catching Specific Exception
AOutput:
try statement can have more than one except clause, to specify
handlers for= 2different exceptions. Please note that at most one handler will
Second element
be
An executed.
error occurred For example, we can add IndexError in the above code. The
general syntax for adding specific exceptions are –

Advantages of Exception Handling:


 Improved program reliability: By handling exceptions properly,
you can prevent your program from crashing or producing incorrect
results due to unexpected errors or input.
 Simplified error handling: Exception handling allows you to
separate error handling code from the main program logic, making it
easier to read and maintain your code.
 Cleaner code: With exception handling, you can avoid using
complex conditional statements to check for errors, leading to
cleaner and more readable code.
 Easier debugging: When an exception is raised, the Python
interpreter prints a traceback that shows the exact location where
the exception occurred, making it easier to debug your code.
Disadvantages of Exception Handling:
22 | G C E T J A M M U
 Performance overhead: Exception handling can be slower than
using conditional statements to check for errors, as the interpreter
has to perform additional work to catch and handle the exception.
 Increased code complexity: Exception handling can make your
code more complex, especially if you have to handle multiple types
of exceptions or implement complex error handling logic.
 Possible security risks: Improperly handled exceptions can
potentially reveal sensitive information or create security
vulnerabilities in your code, so it’s important to handle exceptions
carefully and avoid exposing too much information about your
program.

7. Object-Oriented Programming
(OOP) concept in Python:
In Python 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.

OOPs Concepts in Python:


 Class in Python
 Objects in Python
 Polymorphism in Python
 Encapsulation in Python
 Inheritance in Python
 Data Abstraction in Python

Class :A class is a collection of objects which contains the blueprints or


the prototype from which the objects are being created. It is a logical
entity that contains some attributes and methods. Classes are created by
keyword class.Attributes are the variables that belong to a
class.Attributes are always public and can be accessed using the dot (.)
operator. Eg.: Myclass.Myattribute.

23 | G C E T J A M M U
Objects:In object oriented programming Python, The object is an entity
that has a state and behavior associated with it.More specifically, any
single integer or any single string is an object. An object consists of:
 State: It is represented by the attributes of an object. It also reflects
the properties of an object.
 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.

Inheritance: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.
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.

Polymorphism:Polymorphism simply means having many forms.Itallows


methods to do different things based on the object calling them. In OOP,
polymorphism is often achieved by method overriding or through
functions like len() that can work with multiple data types.

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
24 | G C E T J A M M U
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.

Data Abstraction :It hides unnecessary code details from the user. Also,
when we do not want to give out sensitive parts of our code
implementation and this is where data abstraction came.Data Abstraction
in Python can be achieved by creating abstract classes.

Python Packages for Game


Development

 PyGame: PyGame is a set of libraries and tools for creating video


games and multimedia applications using Python. It provides
functions for handling graphics, sound, input devices, and more,
making it easier to develop games with Python.
 Panda3D: Python Panda3D is a game development framework that
provides tools and libraries for creating 3D games and simulations
using the Python programming language. It offers features for
rendering graphics, handling input, and managing assets, making it
suitable for both hobbyists and professional game developers.
 Pyglet: Pyglet is a Python library used for creating games and
multimedia applications. It provides tools for handling graphics,
sound, input devices, and windowing. With Pyglet, developers can
build interactive experiences efficiently in Python.
 Arcade: Python Arcade is a beginner-friendly Python library for
creating 2D games. It provides tools for handling graphics, sound,
input devices, and other game-related functionalities, making game
development accessible and fun.

25 | G C E T J A M M U
 PyOpenGL: PyOpenGL is a Python binding to OpenGL, a powerful
graphics library for rendering 2D and 3D graphics. It allows Python
developers to access OpenGL’s functionality for creating interactive
 Cocos2d: Python Cocos2d is a simple and powerful game
development framework for Python. It provides tools and libraries
for creating 2D games, making game development more accessible
and efficient for Python developers.

8. PYTHON PROJECTS

→ TREASURE HUNT GAME


print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.")
choice1 = input('You\'re at a crossroad, where do you want to go? '
'Type "left" or "right".\n').lower()
if choice1 == "left":
choice2 = input('You\'ve come to a lake. '
'There is an island in the middle of the lake. '
'Type "wait" to wait for a boat. '
'Type "swim" to swim across.\n').lower()
if choice2 == "wait":
choice3 = input("You arrive at the island unharmed. "
"There is house with 3 doors. One red, "
"one yellow and one blue. "
"Which colour do you choose?\n").lower()
if choice3 == "red":
print("It's a room full of fire. Game Over")
elif choice3 == "yellow":
print("You found the treasure. You Win!")
elif choice3 == "blue":
print("You enter a room of beasts. Game Over.")
else:
print("You chose a door that doesn't exist. Game Over.")
else:

26 | G C E T J A M M U
print("You got attacked by an angry trout. Game Over.")

else:
print("You fell in to a hole. Game Over.")

OUTPUT:

→ ROCK PAPER SCISSOR

import random

user_choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n"))

print(game_images[user_choice])

computer_choice = random.randint(0, 2)

print("Computer chose:")

print(game_images[computer_choice])

if user_choice >= 3 or user_choice < 0:

print("You typed an invalid number. You lose!")

elif user_choice == 0 and computer_choice == 2:

print("You win!")

elif computer_choice == 0 and user_choice == 2:

27 | G C E T J A M M U
print("You lose!")

elif computer_choice > user_choice:

print("You lose!")

elif user_choice > computer_choice:

print("You win!")

elif computer_choice == user_choice:

print("It's a draw!")

→ GUESS THE NUMBER

from random import randint

EASY_LEVEL_TURNS = 7
MODERATE_LEVEL_TURNS = 5
HARD_LEVEL_TURNS = 3

def check_answer(user_guess, actual_answer, turns):


if user_guess > actual_answer:
print("Ohhh!!!! you need to guess a smaller number!")
return turns - 1
elif user_guess < actual_answer:
print("Ohhh!!! you need to guess a higher number")
return turns - 1
else:
print(f"You got it. The number is {actual_answer}")
def set_difficulty():
globals()
level = input("Choose the level of difficulty: Type 'easy' or "
"'moderate' or 'hard'").lower()
if level == "easy":
return EASY_LEVEL_TURNS
elif level == "moderate":
return MODERATE_LEVEL_TURNS
else:

28 | G C E T J A M M U
return HARD_LEVEL_TURNS
def game():
print("Welcome to the Number guessing game")
print("I am thinking of the number between 1 and 50")
answer = randint(1, 50)
turns = set_difficulty()
guess = 0
while guess != answer:
print(f"You have {turns} attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
turns = check_answer(guess, answer, turns)
if turns == 0:
print("You are out of guesses. You lose!")
print(f"Psst , the correct answer is {answer}")

return
elif guess != answer:
print("Guess again")

game()

OUTPUT:

29 | G C E T J A M M U
30 | G C E T J A M M U

You might also like