Open In App

Python A-Z Quick Notes

Last Updated : 10 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Python is a general-purpose, high-level, interpreted programming language that supports multiple programming paradigms, including procedural, object-oriented, and functional programming, and is widely used among the developers’ community. Python was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code.

  • Python is a high-level, interpreted language with easy-to-read syntax.
  • Python is used in various fields like web development, data science, artificial intelligence, and automation.ndn.

Important key features of Python

Python stands out as one of the most popular programming languages due to its versatile and user-friendly features. Here are some of its key highlights:

1. Simple and Readable Syntax: Python’s syntax is clean and easy to understand, making it ideal for beginners.

2. Interpreted Language: Python executes code line by line, eliminating the need for compilation.

3. Dynamically Typed: Variables in Python do not need explicit type declarations.

4. Platform Independence: Python is a cross-platform language that runs easily on Windows, macOS, Linux, and more.

5. Extensive Library Support: Python comes with a comprehensive standard library for tasks like file I/O, regular expressions, and web services.

6. Free and Open Source: Python is free to use, modify, and distribute, encouraging a vast and active community of developers

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

Installation

We have provided detailed, step-by-step instructions to guide you and ensure a successful installation.

To install Python on Windows, macOS, and Linux, follow these given instructions:

Create and Run First Python Program

Once you have Python installed, you can run the program by following these steps:

  1. Open a text editor (e.g., Notepad on Windows, TextEdit on macOS, or any code editor like VS Code, PyCharm, etc.).
  2. Copy the code: print('Hello World') above and paste it into the text editor.
  3. Save the file with .py extension (e.g., Hello.py).
  4. Open the terminal.
  5. Run the program by pressing Enter.

To learn more, check out our article: Getting Started with Python Programming

Code example:

Python
print("Hello, World!")

Output
Hello, World!

Variables

In Python, variables are containers, which is used to store data values. Python supports various datatypes, including integers, floats, strings, and booleans. It represents the kind of value that tells what operations can be performed on a particular data. 

Variables are created when we assign a value to them, using the assignment operator (=).

Example of Variable in Python

An Example of a Variable in Python is a representational name that serves as a pointer to an object. Once an object is assigned to a variable, it can be referred to by that name.

Python
Var = "Geeksforgeeks"
print(Var)

Output
Geeksforgeeks

To learn more, check out our article: Python Variables

Python Data Types

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.

The following are the standard or built-in data types in Python:

Example

Python
a = 5
print(type(a))

b = 5.0
print(type(b))

c = 2 + 4j
print(type(c))

Output
<class 'int'>
<class 'float'>
<class 'complex'>

Numeric Data Types in Python

  • Integers – This value is represented by int class.
  • Float – This value is represented by the float class.
  • Complex Numbers – A complex number is represented by a complex class. For example – 2+3j

Example

Python
a = 5
print(type(a))

b = 5.0
print(type(b))

c = 2 + 4j
print(type(c))

Output
<class 'int'>
<class 'float'>
<class 'complex'>

Sequence Data Types in Python

The sequence Data Type in Python is the ordered collection of similar or different Python data types.

There are several sequence data types of Python:

Python
# Python String
s = "Hello, Python!"
print(s[0])  

# Python List
a = [10, 20, 30, 40]
print(a[1])  

# Python Tuple
tup = (100, 200, 300, 400)
print(tup[2])

Output
H
20
300

Python Keywords

Keywords in Python are reserved words that have special meanings and serve specific purposes in the language syntax. Python keywords cannot be used as the names of variablesfunctions and classes or any other identifier.

TrueFalseNoneand
ornotisif
elseelifforwhile
breakcontinuepasstry
exceptfinallyraiseassert
defreturnlambdayield
classimportfromin
asdelglobalwith
nonlocalAsyncAwait

To learn more, check out our article: Python Keywords

Operators

In Python programming, 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
  2. Comparison Operators
  3. Logical Operators
  4. Bitwise Operators
  5. Assignment Operators
  6. Identity Operators and Membership Operators


Python Operators

To learn more, check out our article: Python Operators

Input and Output

Understanding input and output operations is fundamental to Python programming. With the print() function, you can display output in various formats, while the input() function enables interaction with users by gathering input during program execution.

input (): 

This function first takes the input from the user and converts it into a string. The type of the returned object always will be <class ‘str’>. 

Syntax:

inp = input('STATEMENT')

Example:

Python
# Python program showing 
# a use of input()

val = input("Enter your value: ")
print(val)

Output:

Lightbox

Note: To learn more, check out our article: Taking input in Python

How to Print Output in Python

Python print() function prints the message to the screen or any other standard output device.

Python
# print() function example
print("GeeksforGeeks")

a = [1, 2, 'gfg']
print(a)

Output
GeeksforGeeks
[1, 2, 'gfg']

Print Single and Multiple variable in Python

The code assigns values to variables name and age, then prints them with labels.

Python
name = "Alice"
age = 30
print("Name:", name, "Age:", age)

Output
Name: Alice Age: 30

To learn more, check out our article: Input and Output in Python

Loops and Control Statements

In Python, loops and control statements are essential for controlling the flow of execution.

Python While Loop

A while loop in Python allows you to execute a block of code repeatedly as long as a given condition is true. It's great for scenarios where the number of iterations isn't predefined and depends on runtime conditions.

Key Points:

  • The loop runs as long as the condition evaluates to True.
  • Use break to exit the loop early.
  • Use continue to skip the current iteration and proceed with the next one.

Example: Counting to 10

Python
count = 1
while count <= 10:
    print("Count is:", count)
    count += 1

Output
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

This loop increments count until the condition count <= 10 becomes False.

Python for Loop

There is a “for in” loop which is similar to for each loop in other languages.  It’s ideal for cases where the number of iterations is known or defined by the sequence.

Key Points:

  • Iterates over items in a sequence one by one.
  • Use break to exit the loop early.
  • Use continue to skip the current iteration.

Example: Iterating Over a List

Python
a = ["apple", "banana", "cherry"]
for i in a:
    print(i)

Output
apple
banana
cherry

This loop iterates through each item in the fruits list and prints it.

Python Nested Loops

Python programming language allows using one loop inside another loop. The following section shows a few examples to illustrate the concept. 

Key Points:

  • The outer loop controls the number of times the inner loop executes.
  • You can use any combination of loops (e.g., for inside while).
  • Be mindful of performance, as nested loops can increase computational complexity.

Example: Nested Loops for Multiplication Table

Python
for i in range(1, 4):  # Outer loop
    for j in range(1, 4):  # Inner loop
        print(f"{i} x {j} = {i * j}")
    print("---")  # Separator for better readability

Output
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
---
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
---
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
---

This example demonstrates a multiplication table for numbers 1 through 3, with the outer loop iterating over rows and the inner loop iterating over columns.

Python Loop Control Statements

Loop control statements change execution from their normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements

Python Continue

It returns the control to the beginning of the loop. 

Python
# Prints all letters except 'e' and 's'
for i in 'geeksforgeeks':
	if i == 'e' or i == 's':
		continue
	print(i)

Output
g
k
f
o
r
g
k

Python Break  

It brings control out of the loop.

Python
for i in 'geeksforgeeks':

	# break the loop as soon it sees 'e'
	# or 's'
	if i == 'e' or i == 's':
		break
print(i)

Output
e

To learn more, check out our article: Loops and Control Statements

Functions

Functions in Python are blocks of reusable code that perform a specific task. They help organize your code, make it more readable, and avoid repetition.

Python Function Declaration

The syntax to declare a function is:

Python Functions
  • def: Keyword to define a function.
  • function_name: Name of the function.
  • parameters: Optional values passed to the function.
  • return: (Optional) Sends a result back to the caller.

Types of Functions

  1. Built-in Functions: Predefined in Python, like print(), len(), type().
  2. User-defined Functions: Created by the programmer

Example:

Python
def msg(name):
    return f"Hello, {name}!"

print(msg("AK"))  

Output
Hello, AK!

Benefits of Using Functions

  1. Reusability: Write once, use multiple times.
  2. Modularity: Break complex tasks into smaller parts.
  3. Readability: Makes code more organized and easier to understand.
  4. Maintainability: Easier to update and debug.

Advanced Features

  • Recursion: Functions calling themselves for repeated tasks.
  • Variable-length Arguments: Use *args for unlimited positional arguments and **kwargs for unlimited keyword arguments.

Note: To learn more, check out our article: Python Functions

Object Oriented Programming (OOP)

Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOPs 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.

OOPs Concepts in Python

Python OOPs

1. Class in Python

A class is a blueprint for creating objects. It defines properties (attributes) and methods (functions) that its objects will have.

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

An object consists of:

  • State: It is represented by the attributes of an object.
  • Behavior: It is represented by the methods of an object. 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 (explained above). 

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

Example:

Python
# Define the Animal class
class Animal:
    def __init__(self, name):
        self.name = name  # Assign name attribute

    def speak(self):
        return "This is an animal."  # Define a method to return a string

# Create an instance (object) of the Animal class
dog = Animal("Buddy")

# Access attributes and methods of the object
print(dog.name)
print(dog.speak())

Output
Buddy
This is an animal.

3. Polymorphism in Python

Polymorphism allows the same method to have different implementations in different classes.

4. Encapsulation in Python

Encapsulation restricts direct access to certain attributes and methods to protect the internal state of an object.

5. Inheritance in Python

Inheritance allows a class to derive properties and methods from another class, enabling code reuse.

6. Data Abstraction in Python

Abstraction hides the implementation details of a class and only exposes the essential functionalities.

Getter and Setter

In Python, getters and setters are methods used to access and modify the attributes of a class. They help implement encapsulation, a key concept in object-oriented programming, by providing controlled access to class attributes. Instead of accessing or modifying attributes directly, you use these methods to define specific logic for retrieval or update.

Key Points:

  • Getter: Retrieves the value of an attribute.
  • Setter: Updates or sets the value of an attribute.
  • Encapsulation: Restricts direct access to the internal state of an object, enhancing data integrity.

Using @property Decorators

Python provides a more elegant way to implement getters and setters using @property.

These examples and outputs show how you can use getters and setters effectively to control and manage class attributes in Python.

Getters and setters improve flexibility and robustness in managing an object's attributes. Use them when you anticipate needing validation or additional logic when accessing or setting values.

Note: To learn more, check out our article: Getter and Setter in Python

Multiple Inheritance

Multiple inheritance is a feature in object-oriented programming where a class can inherit attributes and methods from more than one parent class. Python supports multiple inheritance, enabling you to create a class that inherits from multiple classes.

Method Resolution Order (MRO)

Python uses the C3 Linearization (MRO) algorithm to determine the order in which methods are resolved when there is a conflict (i.e., when methods with the same name exist in multiple parent classes).

super() in Multiple Inheritance

The super() function can be used in a multiple inheritance scenario to invoke methods in the MRO.

Composition in Python

Composition is a concept in object-oriented programming where a class is composed of one or more objects of other classes. Instead of inheriting from another class, a class can reuse code by including objects of other classes as its attributes.

Key Characteristics:

  1. Has-a Relationship: One class has another class as a component.
  2. Code Reusability: The behavior of a class can be extended by using other class objects.

Note: To learn more, check out our articles:

Aggregation in Python

Aggregation is a specialized form of composition in object-oriented programming that represents a has-a relationship where one class contains another class as a part, but both can exist independently.

Key Characteristics of Aggregation:

  1. Has-a Relationship: Similar to composition, it denotes a "has-a" relationship between classes.
  2. Independent Lifetimes: The contained object can exist independently of the container object.
  3. Loose Coupling: Promotes loose coupling between classes, making them more modular and reusable

Abstract Classes in Python

Abstract classes in Python are classes that cannot be instantiated directly and are meant to be subclassed.

Key Points:

  1. Purpose: Provide a structure or blueprint for derived classes.
  2. Abstract Methods: Declared but not implemented in the abstract class.
  3. Usage: Subclasses must implement all abstract methods to be instantiated.
  4. Module: Use the abc module and @abstractmethod decorator.

Abstract classes are essential when you want to define a common interface for a group of related classes. They ensure consistent behavior while allowing flexibility in implementation.

Operator Overloading

Operator Overloading allows you to define or change the behavior of operators (+, -, *, etc.) for user-defined classes. Python provides special methods (also known as dunder or magic methods) that can be implemented in a class to override the default functionality of these operators.

Key Points:

  1. Purpose: Make objects of custom classes work with operators.
  2. Magic Methods: Special methods like __add__, __sub__, __mul__, etc., are used for overloading.
  3. Use Case: Enhances readability and usability of custom classes.

By overloading operators, you can make custom classes work seamlessly with standard operations, improving code flexibility and design.

Errors and Exceptions in Python

In Python, errors and exceptions refer to issues that disrupt the normal execution of a program. Understanding them is key to building robust applications.

Errors are classified into two main types: syntax errors and exceptions.

  • Syntax errors: Occur when the code is not properly formatted and cannot be executed.
  • Exceptions: Happen during the program's execution when something unexpected occurs, like dividing by zero or trying to access a non-existent file.

try and except

To handle exceptions in Python, the try and except block is used.

  • Code that might cause an exception is placed inside the try block.
  • The except block defines what to do if an exception occurs.

Example:

Python
try:
    result = 1 / 0
except ZeroDivisionError:
    print("Division by zero is not allowed!")

Output
Division by zero is not allowed!

Here, the program catches the ZeroDivisionError and avoids crashing.

Handling Multiple Exceptions

You can handle multiple exceptions by:

  1. Using separate except blocks for each exception.
  2. Grouping exceptions together in a single block.

else Block

The else block is used to define code that should execute only if no exception is raised in the try block.

Example:

Python
try:
    result = 1 / 2
except ZeroDivisionError:
    print("Division by zero is not allowed!")
else:
    print("The division was successful!")

Output
The division was successful!

finally Block

The finally block is used to define code that should always run, whether or not an exception occurs. It is typically used for cleanup tasks.

Python
try:
    result = 1 / 0
except ZeroDivisionError:
    print("Division by zero is not allowed!")
finally:
    print("This block always runs.")

Output
Division by zero is not allowed!
This block always runs.

Why Use Exception Handling?

Exception handling is crucial in programming to ensure that applications can gracefully handle errors and maintain stability.

Exception handling makes your program:

  • Robust: Prevents crashes from unexpected errors.
  • User-Friendly: Provides meaningful error messages and feedback.
  • Maintainable: Ensures resources (like files or connections) are properly cleaned up.

By using try, except, else, and finally, you can handle errors gracefully and ensure your program runs smoothly.

File Handling in Python

File handling refers to the process of performing operations on a file such as creating, opening, reading, writing and closing it, through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely and efficiently.

Opening a File in Python

To open a file we can use open() function, which requires file path and mode as arguments:

Python
# Open the file and read its contents
with open('geeks.txt', 'r') as file:

This code opens file named geeks.txt.

File Modes in Python

When opening a file, we must specify the mode we want to which specifies what we want to do with the file. Here’s a table of the different modes available:

ModeDescriptionBehavior
rRead-only mode.Opens the file for reading. File must exist; otherwise, it raises an error.
rbRead-only in binary mode.Opens the file for reading binary data. File must exist; otherwise, it raises an error.
r+Read and write mode.Opens the file for both reading and writing. File must exist; otherwise, it raises an error.
rb+Read and write in binary mode.Opens the file for both reading and writing binary data. File must exist; otherwise, it raises an error.
wWrite mode.Opens the file for writing. Creates a new file or truncates the existing file.
wbWrite in binary mode.Opens the file for writing binary data. Creates a new file or truncates the existing file.
w+Write and read mode.Opens the file for both writing and reading. Creates a new file or truncates the existing file.
wb+Write and read in binary mode.Opens the file for both writing and reading binary data. Creates a new file or truncates the existing file.
aAppend mode.Opens the file for appending data. Creates a new file if it doesn’t exist.
abAppend in binary mode.Opens the file for appending binary data. Creates a new file if it doesn’t exist.
a+Append and read mode.Opens the file for appending and reading. Creates a new file if it doesn’t exist.
ab+Append and read in binary mode.Opens the file for appending and reading binary data. Creates a new file if it doesn’t exist.
xExclusive creation mode.Creates a new file. Raises an error if the file already exists.
xbExclusive creation in binary mode.Creates a new binary file. Raises an error if the file already exists.
x+Exclusive creation with read and write mode.Creates a new file for reading and writing. Raises an error if the file exists.
xb+Exclusive creation with read and write in binary mode.Creates a new binary file for reading and writing. Raises an error if the file exists.

To explore File Handling in detail refer to our article: File Handling in Python.


Next Article
Article Tags :
Practice Tags :

Similar Reads