![]() |
VOOZH | about |
Python is a widely-used programming language, celebrated for its simplicity, comprehensive features, and extensive library support. This "Last Minute Notes" article aims to offer a quick, concise overview of essential Python topics, including data types, operators, control flow statements, functions, and Python collections.
Table of Content
First Python Program
Below is a simple Python Program to print "Hello World!":
Hello World!
Indentation
In Python, indentationdefines code blocks. It groups statements with the same indentation level using spaces or tabs, to indicate they belong together.
This is true! I am tab indentation I have no indentation
The first two print statements are indented by 4 spaces, indicating they are part of the if block.
Keywords in Python
| True | False | None | and |
| or | not | is | if |
| else | elif | for | while |
| break | continue | pass | try |
| except | finally | raise | assert |
| def | return | lambda | yield |
| class | import | from | in |
| as | del | global | with |
| nonlocal | async | await |
Comments
Comments in Python are ignored by the interpreter and improve code readability. For single line comments, '#' is used and for multi-line comments, triple quotes(''') are used.
3 5
Variables store data, acting as placeholders for values in a program.
Python variable names can include letters, digits, and underscores, but cannot start with a digit. They are case-sensitive and should not be Python keywords (e.g., if, else, for).
In Python, we can assign values to variables using the = operator. We can also assign values dynamically and perform multiple assignments in one line.
100 100 100 1 2.5 Python
Local variable y: 5 Global variable x: 10
x is a global variable because it is defined outside any function and can be accessed globally.y is a local variable because it is defined inside my_function() and can only be accessed within that function.Python has various built-in data types that allow us to store different kinds of values. Hereโs a brief overview of the main data types:
x = 5, y = -42x = 3.14, y = -0.001name = "Alice", greeting = 'Hello World'True or False. Often used in conditional statements. Example: is_active = True, is_valid = False[]. Example: fruits = ["apple", "banana", "cherry"](). Example: coordinates = (10, 20), colors = ("red", "green", "blue"){}. Example: unique_numbers = {1, 2, 3, 4}, letters = {'a', 'b', 'c'}{} with keys and values separated by a colon(:). Example: student = {"name": "John", "age": 21}result = NoneType Casting
Casting in Python converts one data type to another using built-in functions:
10 5 25
In Python, the print() function is used to display output, while the input() function collects user input.
Printing Output
Use print() to display text, variables, or expressions.
Hello World
Taking Input
Use input() to collect user input. By default, input is returned as a string. You can typecast it to other data types.
Multiple Inputs
Use split() to take multiple inputs in a single line.
In Python, operators are special symbols used to perform operations on variables and values. Python provides a variety of operators, categorized into the following types:
1. Arithmetic Operators
These operators are used to perform basic mathematical operations.
Addition: 19 Subtraction: 11 Multiplication: 60 Division: 3.75 Floor Division: 3 Modulus: 3 Exponentiation: 50625
2. Comparison Operators
These operators compare two values and return a boolean result.
==): Returns True if both operands are equal.!=): Returns True if operands are not equal.>): Returns True if the left operand is greater than the right. <): Returns True if the left operand is less than the right. True if the left operand is greater than or equal to the right. False True False True False True
3. Logical Operators
These operators are used to perform logical operations, often in conditions.
True if both conditions are True.False True False
4. Assignment Operators
These operators assign values to variables.
10 20 10 100 102400
5. Bitwise Operators
Bitwise operators are used to perform operations on binary representations of numbers. These operators work on bits (0s and 1s) and perform bit-level operations.
1 if both bits are 1, otherwise 0. 0 14 -11 14 2 40
6. Membership Operators
These operators test whether a value is a member of a sequence (list, tuple, string, etc.).
True if a value is not found in the sequence.x is NOT present in given list y is present in given list
7. Identity Operators
These operators compare the memory locations of two objects.
True True
Control statements in Python are used to control the flow of execution in a program. They allow you to make decisions, repeat tasks, and handle conditions in your code. The main types of control statements are:
1. Conditional Statements
Conditional statements in Python control the flow of a program by executing code based on specific conditions.
x is greater than 10
2. Loops
Loops in Python allow us to execute a block of code multiple times. Python provides two types of loops: for and while.
for loop
The for loop is used to iterate over a sequence (like a list, tuple, or string) or a range of numbers. It is ideal for iterating over a known collection or when you need to repeat something a fixed number of times.
Syntax:
for item in sequence:
# Execute block of code
0 1 2 3 4
while loop
The while loop is used to execute a block of code as long as the given condition is true. It is ideal when you do not know how many times the loop will run, and the loop continues until a condition is met.
Syntax:
while condition:
# Execute block of code
0 1 2 3 4
3. Loop Control Statements
Python provides three loop control statements to manage the flow of loops:
break: Exits the loop entirely when a certain condition is met.continue: Skips the current iteration and moves to the next iteration of the loop.pass: A placeholder that does nothing. It is used when a statement is syntactically required but no action is needed.i = 0 i = 1 i = 3 i = 4
In Python, a function is a block of reusable code that performs a specific task. It is defined using the def keyword, followed by the function name and parameters (optional). def keyword is the most used keyword in Python. Functions allow you to organize code, improve readability, and avoid repetition.
Syntax:
Return Statement
The return statement ends a function's execution and returns a value to the caller. If no expression follows return, None is returned.
fun() called! sum = 8 Hello! 8
Function Arguments
Arguments are the values or data passed to a function when it is called, enabling the function to perform operations using those inputs. Python functions can accept different types of arguments:
1. Default Arguments
These are values assigned to parameters in case no argument is passed during the function call.
Hello Guest Hello Alice
2. Keyword Arguments
These allow you to pass arguments by explicitly naming the parameter.
Alice is 25 years old.
3. Variable-Length Arguments
These allow you to pass a variable number of arguments to a function. Use *args for non-keyword and **kwargs for keyword arguments. *args allows a function to accept any number of positional arguments as a tuple. **kwargs allows a function to accept any number of keyword arguments as a dictionary.
Alice Bob Charlie
Lambda Functions
A lambda function in Python is an anonymous function defined with the lambda keyword. Unlike regular functions created with def, lambda functions are often used for short, simple tasks.
Syntax:
lambda arguments: expressionKey Features of Lambda Functions:
if conditions.lambda with filter(): Filters elements from a sequence based on a condition.lambda with map(): Applies a function to each element in a list, returning a new list.lambda with reduce(): Applies a function cumulatively to pairs of elements in an iterable.Example:
25 Even [1, 4, 9, 16] [3, 4] [2, 4, 6, 8] 24
Recursion is a process where a function calls itself to solve a problem by breaking it into simpler subproblems. In Python, a recursive function is defined like any other function but includes a call to itself, with conditions that guide the recursion process.
Basic Structure of Recursive Function
def recursive_function(parameters):
if base_case_condition:
return base_result
else:
return recursive_function(modified_parameters)
Base Case: The condition that stops the recursion, preventing infinite loops and ensuring progress toward the solution (e.g., n == 1 in factorial).
Recursive Case: The part of the function that calls itself, reducing the problem size (e.g., return n * factorial(n-1)).
Recursion vs Iteration
Factorial using recursion: 120 Factorial using iteration: 120
A string in Python is a sequence of characters enclosed in quotes. It can contain letters, numbers, and symbols. Python doesn't have a separate character data type, so a single character is treated as a string of length 1.
1. Creating a String
Strings can be created using single (') or double (") quotes. We can access individual characters using indexing (starting from 0). Python also supports negative indexing for accessing characters from the end.
GeeksforGeeks GeeksforGeeks G s
2. String Slicing
Extracting a portion of the string using slicing.
Syntax:string[start:end]
String Immutability
Strings are immutable, so to modify them, you need to create a new string.
GeeksforGeeks
Common String Methods
len(): Returns the length of the string.upper(): Converts to uppercase.lower(): Converts to lowercase.strip(): Removes leading and trailing spaces.replace(old, new): Replaces substring old with new.13 GEEKSFORGEEKS hi geek! Hi Geek! Hi GfG!
Formatting Strings
You can format strings using f-strings or format() method.
Name: Alice, Age: 22
Python Object-Oriented Programming (OOP) helps organize code in terms of objects and classes, improving readability, reusability, and scalability. Key concepts in Python OOPs include:
Python code example that demonstrates all the key concepts of Object-Oriented Programming (OOPs):
Buddy is a Dog Buddy, a Golden Retriever, barks! Whiskers meows! Alice is 30 years old. New age of Alice: 35 Engine started... Vroom!
Animal and Dog are classes. Dog inherits from Animal, demonstrating Inheritance.dog, cat, person, and car are objects (instances) of the classes.Dog class inherits from Animal, and the super() function is used to call the parent class's constructor.Person class hides the age attribute using __age, which is accessed and modified through getter and setter methods.speak method is defined in both Dog and Cat classes, demonstrating method overriding, where different classes can implement the same method differently.Car class has a start_engine method that hides the complex internal details.In Python, modules and packages allow you to organize and reuse code across different programs. A module is a single file that contains functions, classes, and variables, while a package is a collection of related modules.
1. Importing Modules
To use the functions and classes defined in a module, you need to import it. Python provides the import statement to include modules in your script.
Syntax:
import module_nameWe can also import specific functions or variables from a module using from.
from module_name import function_nameExample:
import math
print(math.sqrt(16)) # Output: 4.0
from math import pi
print(pi) # Output: 3.141592653589793
2. Standard Library Overview
Pythonโs Standard Library is a collection of modules that come pre-installed with Python. It provides various functions for handling file operations, data manipulation, regular expressions, networking, and more. Some popular standard modules include math, datetime, os, sys, and random.
Example:
import random
print(random.randint(1, 10))
3. Writing and Using Custom Modules
You can create your own modules by writing Python code in a separate .py file. After creating the file, you can import and use the functions or classes from that file in other scripts.
Step 1: Create a module: Save a Python file (mymodule.py).
# mymodule.py
def greet(name):
return f"Hello, {name}!"
Step 2: Import and use the custom module:
import mymodule
print(mymodule.greet("Alice")) # Output: Hello, Alice!