PYTHON
Python is a programming language you can use to tell a computer what to do, using English-like
instructions.
Here (Yasmin) is a string. It is a must to always write strings within “...” In the example below, Name is a
variable, and Yasmin is the string to print anything along with your variable; it is a must to use (a ” , ”) or a f
string.
DATA TYPES
In Python, data types tell the computer what kind of data you're working with—like numbers, text, or lists.
Strings
Integers
Floats
Boolean
None
String (str)
A string is a sequence of characters (letters, numbers, symbols) enclosed in quotes. It’s used to store text.
Integer (int)
An integer is a whole number, no decimal point. An integer could be positive, negative, or zero.
Float (float)
A float is a number with a decimal point. It can also be written in scientific notation.
Boolean (bool)
A boolean represents a truth value — either True or False.
None (NoneType)
None means "nothing" or "no value". It represents the absence of a value.
TYPE
The type() function tells you the data type of a value or a variable.
Assignment operators
KEYWORDS
These are reserved words in Python.
OPERATORS
An operator is a symbol that operates on one or more values (called operands). Think of it like math signs
or logic tools that tell Python what to do with data.
Arithmetic Operators
Relational / Comparison Operators
Logical Operators
ARITHMETIC OPERATORS
Arithmetic operators are symbols that perform mathematical operations like addition, subtraction,
multiplication, and so on.
RELATIONAL OPERATORS
(also called comparison operators) They are used to compare two values.
They always return a Boolean result:
True or False
ASSIGNMENT OPERATORS
Assignment operators are used to assign values to variables.
LOGICAL OPERATORS
Logical operators are used to combine multiple conditions (usually True or False) and return a single
Boolean result.
They help your code make decisions like:
"Is this condition AND that one also true?"
INPUTS IN PYTHON
The input() function takes input from the user (e.g., text typed into the program).
TYPE CONVERSION VS TYPE CASTING
1. Type Conversion (Automatic)
Python automatically converts one data type to another when needed.
2. Type Casting (Manual)
You manually change a variable's type using functions like:
STRINGS
A string in Python is a sequence of characters (letters, digits, symbols) enclosed in quotes.
Single quotes 'Hello’
Double quotes "Hello"
Triple quotes '''Hello''' (for multiline text)
Length of a String len(...)
The length of a string means how many characters it has, including Letters, Numbers, Spaces, and
Symbols.
Indexing
Indexing means accessing characters in a string using their position (index number).
Indexing starts from 0
You can go forward (from left) and backward (from right)
Slicing
Slicing means cutting a part of a string by specifying a start and end position (index).
start: index to begin (included)
end: index to stop (excluded)
If you skip any, Python fills in smart defaults.
STRING FUNCTIONS
INDENTATION
Indentation means adding spaces or tabs at the beginning of a line to show that it belongs inside a
block (like if, for, while, def, etc). Python uses indentation to define the structure of the code, unlike
other languages that use {} brackets.
Correct Indentation Rules
Use 4 spaces (standard) or 1 tab for each indented block..
Be consistent (don’t mix tabs and spaces)
CONDITIONAL STATEMENTS
Conditional statements run different blocks of code based on whether a condition is True or False.
Nested Conditional Statements
A nested conditional statement is an if or if-else block placed inside another if or else block. This
allows your program to make decisions based on multiple layers of conditions.
LIST AND TUPLE
A LIST is a built-in data type in Python used to store multiple items in a single variable. Lists are:
Ordered: Items have a defined order, and it will not change unless explicitly modified.
Mutable: You can change, add, and remove items after the list has been created.
Allow Duplicates: Lists can contain duplicate values.
Heterogeneous: Items can be of different data types, including other lists.
Lists are created using square brackets [], with items separated by comma
LIST SLICING
List slicing is a technique used to extract a specific portion (or "slice") of a list by specifying a range of
indices.
Start: Index to begin the slice (inclusive).
Stop: Index to end the slice (exclusive).
Step: How many elements to skip (optional).
LIST METHODS
TUPLE
A tuple is an ordered, immutable collection of elements in Python. Unlike lists, once a tuple is created, its
elements cannot be modified, added to, or removed.
Ordered: Elements have a defined order, and that order will not change.
Immutable: Once created, elements cannot be changed.
Allow Duplicates: Tuples can contain duplicate values.
Heterogeneous: Can store elements of different data types.
[Link](x)
DICTIONARY IN PYTHON
In Python, a dictionary is a built-in data type that stores key-value pairs. It’s like a real-life dictionary
where you look up a word (the key) to get its meaning (the value).
"name", "age", and "college" are keys
"Yasmin", 20, and "BITS Pilani" are the values
1. [Link]()
Returns all the keys in the dictionary.
2. [Link]()
🔹 Returns all the values in the dictionary.
3. [Link]()
🔹 Returns all key–value pairs as tuples.
4. [Link]('key')
🔹 Safely gets the value of a key.
🔹 Doesn’t give an error if the key doesn't exist.
5. [Link]({'key': value})
🔹 Adds new key–value pairs or updates existing ones.
Set
Unordered -items have no index.
No duplicates – each element is unique.
Mutable – you can add or remove elements.
Elements must be immutable – like numbers, strings, or tuples.
1. add()
Adds an element to the set.
2. remove()
Removes an element from the set.
If the element is not found, it raises an error (KeyError).
3. clear()
Removes all elements from the set, leaving it empty.
Removes and returns a random element from the set (because sets are unordered).
If the set is empty, it raises an error (KeyError).
4. pop()
Removes and returns a random element from the set (because sets are unordered).
If the set is empty, it raises an error (KeyError).
LOOPS
Loops let you repeat a block of code multiple times without writing it again and again.
1. For Loop
Used to iterate over a sequence like a list, string, or range of numbers.:
2. While Loop
Repeats as long as a condition is True.
The count starts at 1.
The while loop checks: is count <= 5? If yes, it runs the loop body.
Inside the loop:
It prints "hello".
Then count += 1 increases count by 1.
This continues until the count becomes 6, and then the loop stops.
BREAK
break is used to exit the loop early, even if the condition is still true.
Continue – Skip One Loop Turn
continue is used to skip the current iteration and move to the next one.
i = 3 is skipped (not printed)
All others are printed
Range
range() is a built-in function that generates a sequence of numbers.
It's most commonly used in for loops like this:
Function
A function is a block of reusable code that performs a specific task.
Instead of repeating code again and again, we write it once in a function and call it whenever needed.
In programming, functions are blocks of reusable code that perform a specific task. They can be built-in
(already available in the language) or user-defined (created by you). Let’s compare them:
Built-in Functions
Definition: These are functions that come preloaded with a programming language.
Examples in Python:
print() – displays output
len() – returns the length of a list/string
type() – returns the type of a variable
sum() – adds elements in an iterable
input() – takes user input
User-defined functions
A user-defined function is a function that you create to perform a specific task. It helps you avoid
repeating code.
Arguments
Arguments are the values you pass into a function when you call it.
Name is the parameter (the placeholder).
"Mini" is the argument (the actual value).
Recursion
Recursion is when a function calls itself to solve a smaller part of the problem.
File I/O in Python
🔹 Reading a File
Once opened in read mode, you can read the file contents using methods like:
. .read() — reads the whole file as a string
.readline() — reads one line at a time
.readlines() — read
🔹 Closing a File
Always close the file using .close() after you finish, so resources are freed.
What is \n in Python?
\n is not a space — it’s a newline character.
It tells Python to move the cursor to the next line when printing or writing text.
File I/O means working with files:
Reading data from files
Writing data to files
Key Python Functions for File I/O
1. Opening a file
1. Text Files
What are they?
Files that contain readable characters — letters, numbers, symbols, formatted as text.
Examples: .txt, .csv, .html, .py files
How Python handles them:
When you open a file in text mode ('r', 'w', 'a'), Python treats the file content as strings (Unicode by
default in Python 3).
Newlines: Python automatically handles newline characters (\n, \r\n) depending on your OS.
Common usage: Reading and writing documents, logs, CSV data, source code, etc.
2. Binary Files
What are they?
Files that contain raw bytes — non-text data that may not be human-readable.
Examples: images (.jpg, .png), audio (.mp3, .wav), video, executable files, compressed files, serialized
data.
How Python handles them:
Open files in binary mode using 'rb', 'wb', or 'ab'. Python reads and writes byte objects instead of
strings.
No newline translation: Binary mode reads/writes exactly the bytes in the file, no changes.
Common usage: Handling media files, data serialization (e.g., pickle), and cryptographic operations.
🔹 Opening a File
Use the open() function to open a file. You must specify the filename and the mode (e.g., read, write).
Modes:
When you open a file in Python without specifying the mode, it automatically opens the file in read mode
('r') by default. This means you can read the file's contents, but if you try to write to the file in this
mode, Python will raise an error because writing is not allowed in read mode.
HOW TO OPEN A FILE ([Link]) IN PYTHON
1. f = open("[Link]", "r")
This line uses the built-in open() function to open a file named "[Link]".
The second argument, "r", specifies that the file is opened in read mode. This means you can only read
the contents of the file, not write to it.
The opened file object is assigned to the variable f. This variable will be used to interact with the file.
2. data = [Link]()
HERE, the read() method is called on the file object f.
The read() method reads the entire content of the file from the current position (which is the beginning of
the file when it's just opened) until the end of the file.
The content that is read from the file is stored as a string in the variable data.
3. print(data)
This line uses the print() function to display the value of the data variable on the console. This will
output the content that was read from the "[Link]" file.
4. print(type(data))
THE line uses the type() function to determine the data type of the data variable.
The print() function then displays this data type on the console. Since the read() method returns the
file content as a string, the output of this line will be <class 'str'>.
5. [Link]()
This line calls the close() method on the file object f.
It's crucial to close the file when you are finished with it. This releases the system resources that were being
used by the open file and ensures that any buffered data is written to the file (though this is more relevant
for write operations).
In summary, this Python code opens a text file named "[Link]", reads its entire content into a string
variable, prints the content, confirms that it is a string, and then closes the file. For this code to run without
error, a file named "[Link]" must exist in the same directory as the Python script.
1. [Link]()
Reads the entire contents of the file as one big string.
2. [Link]()
Reads one line from the file at a time.
Each call to [Link]() returns the next line as a string (including the newline character \n at the
end).
1)Writing mode
f = open('[Link]', 'w')
'w' means write mode: it creates a new file or overwrites if it already exists.
You can also use 'a' to append without erasing what's already in the file.
Suppose we want to add or append something to the already existing [Link] then we change mode from
w to a
And suppose we would like to have our sentence in the next line we use a \n
In the above code, even though we haven't manually created a file named [Link], Python
automatically creates it when we open it in append mode ("a"). This is because the "a" mode allows
appending to an existing file and creates the file if it doesn't already exist.
Mode (r +)
The "r+" mode in Python allows you to read and write to a file, and it starts overwriting from the
beginning of the file without deleting the entire content — only the parts you replace get changed.
What is "r+" mode?
Opens the file for both reading and writing.
Does not create a new file. If the file doesn't exist, you'll get an error.
Writing starts from the beginning and overwrites existing content, character by character.
Mode(w+)
"w+" mode in Python makes existing content disappear, even though it lets you read and write.
What does "w+" mode do?
w = write (and truncate the file to zero length).
+ = read and write.
So, "w+" opens the file for both reading and writing, but clears all previous content as soon as it opens
the file.
Key point:
As soon as you open the file in "w+" mode, Python truncates the file — meaning, it erases everything
inside it, even before you get a chance to read anything.
With syntax in python
Deleting a File in Python
Python doesn’t let you delete a file directly with [Link]() from a file object. Instead, you use
modules like os or pathlib.
[Link]() is a function that deletes the file.
os is a built-in module — no need to install anything.
Here os is a module
Modules — Built-in vs. External
OPP OBJECT ORIENTED PROGRAMM
OOPs stands for Object-Oriented Programming System.
It’s a programming paradigm (a way to design and write programs) that is based on the concept of objects
and classes.
Instead of writing code as a list of instructions (as in procedural programming), you organize it as a
collection of objects that interact with each other.
Real-Life Analogy for OOPs:
Imagine you are designing a car. A Car has properties (color, engine type) and behaviors (start, stop).
You don’t describe everything about a car every time—you create a blueprint (class) once, and then build
many cars (objects) from it.
Key Principles of OOPs:
Encapsulation – Hiding internal details and showing only what’s necessary.
Abstraction – Focusing on essential features, not how they work.
Inheritance – One class (child) can inherit properties/methods from another (parent).
Polymorphism – One function or method behaves differently based on context.
Class
A class is a blueprint or template for creating objects.
It defines attributes (variables) and methods (functions) that the objects will have.
Object
An object is a real-world version of the class. It’s created from the class and does real work.
You can create multiple objects from the same class — like many dogs from the Dog class.
Defining a Class
Let’s say we want to model a Dog.
What’s happening here?
class Dog: → You're creating a blueprint for a dog.
__init__ → A constructor, runs when an object is created.
[Link], [Link] → These are attributes (data).
bark() → This is a method (behavior or function inside the class).
Creating Objects from Class
Here:
dog1 and dog2 are two different dogs (objects).
Both use the same class (Dog) but have different data.
_Init_ Function
All clases have a function called an init function which is always executed when the class is being initiated
Note
Suppose we want to inclue “---” in our original text but python interprets it as a part of code and shows an error
hence to avoid this code we use ( \ ) this acts as escape and hence shows no error and provides the
output as Python “Prodramming
This is for a new line