python file
python file
python file
PYTHON PROGRAMMING
Semester: 3rd
1|GCET JAMMU
TOPICS COVERED
S.NO. TOPIC PAGE NO.
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.
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.
3|GCET JAMMU
Applications: Python is widely used in fields such as:
Software Development
Game Development
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:
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 .
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.
Python String
Python List
Python Tuple
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.
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 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:
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:
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.
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:
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:
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.
Syntax
1. if <conditional expression> :
These statements will always be executed. They are part of the main
code.
Code:
age = 18
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:
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.")
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
else:
Output:
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
if number == 3:
if number == 5:
print(number)
Output:
Defining a Function
To define a function, use the def keyword, followed by the function name
and parentheses () containing any parameters.
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
2. Tuples
3. Sets
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
5. Other Structures
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.
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.
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.
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.
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.
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
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:
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])
print("You win!")
27 | G C E T J A M M U
print("You lose!")
print("You lose!")
print("You win!")
print("It's a draw!")
EASY_LEVEL_TURNS = 7
MODERATE_LEVEL_TURNS = 5
HARD_LEVEL_TURNS = 3
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