Important Python Points
This section highlights the essential concepts and features every Python learner should know. From core syntax and data types to advanced topics like modules, functions, and error handling, these key points provide a quick and effective reference for mastering Python and also for cracking the MCQs. Whether you're a beginner or brushing up your skills, these insights will strengthen your understanding and boost your coding confidence.
Quick Navigation
Google Colab
Colab is a hosted Jupyter Notebook service that requires no setup to use and provides free of charge access to computing resources, including GPUs and TPUs. Colab is especially well suited to machine learning, data science, and education.
- •Google Colab is a free hosted Jupyter Notebook service that requires no setup to use and provides free of charge access to computing resources, including GPUs and TPUs.
- •In Google Colab the code run on the browser and the data is stored in the cloud.
- •Google Colab is sync with the google drive.
- •In Google Colab GPU and TPU are available for free.
- •In Google Colab you can easily upload, download, and share your notebook with others.
- •Google Colab support .ipynb files format.
- •Google Colab features to export the notebook to other formats like HTML, PDF, and Python.
- •In Google Colab we can clear all the outputs by using Runtime > Clear all outputs.
- •Google colab offers auto save feature with Drive.
Introduction to Python
Python is a versatile, high-level, interpreted programming language known for its readability and extensive libraries. It was created by Guido van Rossum in the late 1980s and first released in 1991. Python is used for various tasks, including data analysis, machine learning, web development, and automation
- •Python is a high-level, interpreted programming language with easy syntax and dynamic semantics.
- •Python is a beginner-friendly or readable language, making it easy to learn and use.
- •The extension of the python file is .py
- •Python is a dynamically typed language, which means that the type of the variable is determined at runtime.
- •Python language was created by Guido van Rossum in 1991.
- •Python follows an object-oriented approach to make code reusable and maintainable.
- •Python is use for web development, data analysis, artificial intelligence, and scientific computing.
- •Python has 3 stable versions, 2.x, 3.x, and 3.10.x.
- •Python is best for scripting or automating tasks.
- •Python use input() function to print the output.python
print('Hello, World!')
- •Python use print() function to print the output.python
print('Hello, World!')
- •In python the indentation (whitespace) is important and it is used to define code blocks instead of braces or keywords.python
if x > 5: print('x is greater than 5') else: print('x is not greater than 5')
- •Comments in Python start with the # character and extend to the end of the line.python
# This is a comment x = 5 # This is also a comment
- •Multi-line comments can be created using triple quotes (''' or """).python
''' This is a multi-line comment '''
Data Types
Data types in Python define the kind of value a variable can hold. Python is a dynamically typed language, meaning you don’t need to declare the type of a variable explicitly. It automatically detects the data type at runtime.
- •Python has several built-in data types including numbers, strings, lists, tuples, sets, and dictionaries.
- •Python has 3 basic data types: int, float, str, and bool.
- •Python has 4 collection data types: list, tuple, set, and dictionary.
- •Python use type() function to get the type of the variable.python
print(type(10)) # <class 'int'>
- •In python strings and tuples are immutable, Lists are mutable, Dictionaries are mutable and type are based on key-value pairs, Sets are mutable and does not allow duplicate values, Booleans are immutable and can only be True or False, None is a special type of its own and is immutable, and Typed conversion is possible with the int(), str() but in Functions.python
#Tuple my_tuple : tuple = (1, 2, 3) #List my_list : list = [1, 2, 3] #Dictionary my_dict : dict = {'name': 'John', 'age': 30, 'city': 'New York'} #Set my_set : set = {1, 2, 3} #Boolean my_bool : bool = True #None my_none : None = None
- •Numbers include integers (int), floating-point (float), and complex numbers.python
x = 10 # int y = 10.5 # float z = 1+2j # complex
- •Strings are sequences of characters enclosed in single, double, or triple quotes.python
name = 'John' message = "Hello, World!" paragraph = '''This is a multi-line string'''
- •Lists are ordered, mutable collections that can contain items of different data types.python
my_list = [1, 'Hello', 3.14, True]
- •Tuples are ordered, immutable collections similar to lists but cannot be modified after creation.python
my_tuple = (1, 'Hello', 3.14, True)
- •Sets are unordered collections of unique elements.python
my_set = {1, 2, 3, 4, 5}
- •Dictionaries are unordered collections of key-value pairs.python
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
Operators, Keywords, and Variables
Keywords are reserved words in Python that have special meanings and cannot be used as variable names. They are used to define the structure of the program and the operations that can be performed on the data.
- •Python has 4 types of operators: Arithmetic, Assignment, Comparison, Logical.
- •Arithmetic operators are used to perform mathematical operations on numbers. And they are +, -, *, /, %, **, //.python
x + y # Addition x - y # Subtraction x * y # Multiplication x / y # Division x % y # Modulus x ** y # Exponentiation x // y # Floor division
- •Assignment operators are used to assign values to variables. And they are =, +=, -=, *=, /=, %=, **=, //=.python
x = y # Assignment x += y # Addition assignment x -= y # Subtraction assignment x *= y # Multiplication assignment x /= y # Division assignment x %= y # Modulus assignment x **= y # Exponentiation assignment x //= y # Floor division assignment
- •Comparison operators are used to compare two values and return a boolean value (True or False). And they are ==, !=, >, <, >=, <=.python
x == y # Equal x != y # Not equal x > y # Greater than x < y # Less than x >= y # Greater than or equal to x <= y # Less than or equal to
- •Logical operators are used to combine conditional statements. And they are and, or, not.python
x and y # Logical AND x or y # Logical OR not x # Logical NOT
- •Keywords are reserved words in Python that have special meanings and cannot be used as variable names. They are used to define the structure of the program and the operations that can be performed on the data.python
if, elif, else, for, while, def, return, import, from, as, in, is, not, and, or, True, False, None
- •Variables are used to store data in Python. And they are defined using the = operator.python
x = 10 y = 20 z = x + y
String and Casting
Strings in Python are immutable sequences used to store text. Casting allows conversion between different data types, like numbers to strings.
- •The text is written in the form of a string. And it is enclosed in single, double, or triple quotes.python
name = 'John' #single quote message = "Hello, World!" #double quote paragraph = '''This is a multi-line string''' #triple quote
- •String is a sequence of characters enclosed in single, double, or triple quotes.python
name = 'John' message = "Hello, World!" paragraph = '''This is a multi-line string'''
- •In python the length of the string is found using the len() function.python
len(name) #output: 4 len(My name is Ali) #output: 11 len(I am web developer) #output: 15
- •In python string is immutable.python
name = 'John' name[0] = 'A' # This will raise an error
- •In python + operator is used to concatenate two strings.python
name = 'Ali' message = "Hello, Dear!" paragraph = 'I am a web developer' print(message + I am + name + And + paragraph) #output: Hello, Dear! I am Ali And I am a web developer
- •In python * operator is used to repeat the string.python
name = 'Ali' print(name * 3) #output: AliAliAli
- •In python we use str.upper() to convert the string to uppercase and str.lower() to convert the string to lowercase.python
name = 'Ali' print(name.upper()) #output: ALI print(name.lower()) #output: ali
- •In python we use str.replace() to replace the string.python
name = 'Ali' print(name.replace('Ali', 'Ahmed')) #output: Ahmed
- •In python we use str.slice() to slice the string.python
name = 'Ali Askari' print(name[0:3]) #output: Ali
- •In python we use str.split() to split the string.python
name = 'Ali' print(name.split(' ')) #output: ['Ali']
- •In python we use str.strip() to remove the leading and trailing whitespace from a string.python
name = ' Ali ' print(name.strip()) #output: Ali
- •In python we use str.join() to join the string.python
name = ['Ali', 'Askari'] print(' '.join(name)) #output: Ali Askari
- •In python we use str.find() to find the index of the string.python
name = 'Ali' print(name.find('A')) #output: 0
- •In python we use str.count() to count the number of occurrences of a substring in a string.python
name = 'Ali' print(name.count('A')) #output: 1
- •In python we use in operator to check if a substring is present in a string.python
name = 'Ali' print('A' in name) #output: True
- •In python we use in operator to check if a substring is present in a string.python
name = 'Ali' print('A' in name) #output: True
- •In python Typecasting is the conversion of one data type to another data type.python
name = 'Ali' print(int(name)) #output: 1
- •In python we use int() to convert the string to integer, float() to convert the string to float, str() to convert the string to string, bool() to convert the string to boolean, list() to convert the string to list, tuple() to convert the string to tuple, set() to convert the string to set, and dict() to convert the string to dictionary.python
name = 'Ali' print(int(name)) #output: 1 print(float(name)) #output: 1.0 print(str(name)) #output: Ali nprint(bool(name)) #output: True
- •In python escape characters are used to escape the special characters in a string.python
name = 'Ali' print('I'm a web developer') #output: I'm a web developer These are the Escape Characters: \n #new line \t #tab \r #carriage return \b #backspace
Control Flow
Statements that control the flow of execution in Python
- •Control flow is the order in which the statements are executed in a program.
- •Conditional statements (if, elif, else) allow code to execute based on certain conditions.python
if age < 18: print('Minor') elif age >= 18 and age < 65: print('Adult') else: print('Senior')
- •If statement is executed if the condition is true.python
if age < 18: print('Minor')
- •Elif statement is executed when the if condition is false and the current condition is true.python
elif age >= 18 and age < 65: print('Adult')
- •Else statement is executed when the if, and elif condition is false.python
else: print('Senior')
- •Logical operators are used to combine conditional statements. And they are and, or, not.python
if age < 18: print('Minor') elif age >= 18 and age < 65: print('Adult') else: print('Senior')
- •For loop is used to iterate over a sequence (like a list, tuple, dictionary, set, or string).python
for i in range(5): print(i) # Prints 0, 1, 2, 3, 4
- •While loop is used to execute a block of code repeatedly until a condition is met.python
while count < 5: print(count) count += 1
- •break statement exits the loop prematurely.python
for i in range(10): if i == 5: break print(i) # Prints 0, 1, 2, 3, 4
- •Continue statement skips the current iteration and continues with the next.python
for i in range(10): if i % 2 == 0: continue print(i) # Prints odd numbers: 1, 3, 5, 7, 9
- •Pass is a dummy statement that does nothing. It is used to make the code syntactically correct.python
for i in range(10): pass # This will do nothing
- •Nested Loop and conditions is possible in python.
Lists, Tuples, and Dictionaries
Lists, Tuples, and Dictionaries in Python
- •List is a collection of items that are ordered and mutable. And it is represented as [].
- •Tuple is a collection of items that are ordered and immutable. And it is represented as ()
- •Dictionary is a collection of key-value pairs. And it is represented as {}.
- •In list we can take the elements by using positive and negative index number.python
list = [1, 2, 3, 4, 5] print(list[0]) #output: 1 print(list[-1]) #output: 5
- •append() method is used to add an element to the end of the list.python
list = [1, 2, 3, 4, 5] list.append(6) print(list) #output: [1, 2, 3, 4, 5, 6]
- •pop() method is used to remove an element from the list at a specific index.python
list = [1, 2, 3, 4, 5] list.pop(0) print(list) #output: [2, 3, 4, 5]
- •remove() method is used to remove an element from the list.python
list = [1, 2, 3, 4, 5] list.remove(3) print(list) #output: [1, 2, 4, 5]
- •insert() method is used to add an element to the list at a specific index.python
list = [1, 2, 3, 4, 5] list.insert(0, 0) print(list) #output: [0, 1, 2, 3, 4, 5]
- •extend() method is used to add multiple elements to the end of the list.python
list = [1, 2, 3, 4, 5] list.extend([6, 7, 8]) print(list) #output: [1, 2, 3, 4, 5, 6, 7, 8]
- •Tuple is a collection of items that are ordered and immutable. And it is represented as ()
- •In Dictionary we use key and value to store the data.python
dict = {'name': 'Ali', 'age': 20, 'city': 'Tehran'} print(dict['name']) #output: Ali
- •In Dictionary every key is unique and immutable.
- •IN operators check if a key is present in the dictionary.python
dict = {'name': 'Ali', 'age': 20, 'city': 'Tehran'} print('name' in dict) #output: True
- •Len() function is used to get the length of the dictionary.python
dict = {'name': 'Ali', 'age': 20, 'city': 'Tehran'} print(len(dict)) #output: 3
Sets
Sets in Python are unordered collections of unique, immutable elements. They are defined using curly braces {} or the set() constructor. Sets are mutable, allowing addition and removal of elements, but the elements themselves must be immutable (e.g., numbers, strings, tuples). Sets are commonly used for membership testing, removing duplicates, and performing mathematical set operations like union, intersection, and difference.
- •Set is a collection of items that are unordered and mutable.
- •Set remove the duplicate elements from the list.python
list = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] set = set(list) print(set) #output: {1, 2, 3, 4, 5}
- •In set we can use add() method to add an element to the set.python
set = {1, 2, 3, 4, 5} set.add(6) print(set) #output: {1, 2, 3, 4, 5, 6}
- •In set we can use remove() method to remove an element from the set.
- •In set we can use clear() method to remove all elements from the set.python
set = {1, 2, 3, 4, 5} set.clear() print(set) #output: set()
- •In set we can use union() method to join two sets.python
set1 = {1, 2, 3, 4, 5} set2 = {6, 7, 8, 9, 10} print(set1.union(set2)) #output: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
- •In set we can use intersection() method to find the common elements in two sets.python
set1 = {1, 2, 3, 4, 5} set2 = {6, 7, 8, 9, 10} print(set1.intersection(set2)) #output: set()
- •In set we can use difference() method to find the difference between two sets.python
set1 = {1, 2, 3, 4, 5} set2 = {6, 7, 8, 9, 10} print(set1.difference(set2)) #output: {1, 2, 3, 4, 5}
- •Sets are mutable but the list of elements in the set must be immutable.python
set = {1, 2, 3, 4, 5} set.add(6) #output: {1, 2, 3, 4, 5, 6}
- •In set IN Operators check if an element is present in the set.python
set = {1, 2, 3, 4, 5} print(1 in set) #output: True
- •In set the order of the elements is not fixed.python
set = {1, 2, 3, 4, 5} print(set) #output: {1, 2, 3, 4, 5}
- •In set we can use len() function to get the length of the set.python
set = {1, 2, 3, 4, 5} print(len(set)) #output: 5
- •In set set() can convert the iterable to set.python
set = set([1, 2, 3, 4, 5]) print(set) #output: {1, 2, 3, 4, 5}
- •In set we can use frozenset() to create an immutable set.python
set = frozenset([1, 2, 3, 4, 5]) print(set) #output: frozenset({1, 2, 3, 4, 5})
Functions
Functions in Python are defined using the def keyword. They can take parameters and return values. Functions are used to organize code and make it reusable.
- •Functions are declared using the def keyword.python
def greet(name): return f'Hello, {name}'
- •Functions can take parameters(input) and return values(output).python
def greet(name): return f'Hello, {name}'
- •Default parameters are the parameters that are assigned a default value.python
def greet(name='World'): return f'Hello, {name}'
- •We can return multiple values from a function.python
def add_sub(a, b): return a+b, a-b
- •keyword arguments improve the readability of the code.python
def greet(name='World', age=20): return f'Hello, {name} and you are {age} years old'
- •Function can be nested in another function.python
def outer_function(): print('This is the outer function.') def inner_function(): print('This is the inner function.') # Call the inner function inner_function() # Call the outer function outer_function() #output: This is the outer function. This is the inner(nested) function.
- •Docstrings are used to describe the function.python
def greet(name): '''This function greets the user with a message.''' return f'Hello, {name}'
- •Lambda functions are small, anonymous functions that can have any number of arguments, but can only have one expression.python
def square(x): return x*x
- •We can use the *args and **kwargs to pass a variable number of arguments to a function.python
def add(*args): return sum(args) def add_sub(a, b): return a+b, a-b
Enums
Enums in Python are a way to define a set of named values that are immutable and can be used to represent a finite set of options.
- •Enums are used to define a set of named values that are immutable and can be used to represent a finite set of options.python
from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3
- •Enum are created by importing Enum class from enum module.python
from enum import Enum
- •Define enums by using Enum class.python
from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3
- •Enum members have name and value.python
from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3
- •Enum members can be accessed by their name.python
from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3
- •Enum members can be accessed by their value.
- •
Object-Oriented Programming
Class-based object-oriented programming in Python
- •Classes are created using the class keyword and can contain attributes and methods.python
class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): return f'Hello, my name is {self.name}'
- •The __init__ method initializes the object's attributes when the object is created.python
class Dog: def __init__(self, name, breed): self.name = name self.breed = breed
- •Inheritance allows a class to inherit attributes and methods from another class.python
class Animal: def __init__(self, name): self.name = name class Dog(Animal): def bark(self): return 'Woof!'
- •Encapsulation is the bundling of data and methods that operate on that data within a single unit (class).
- •Polymorphism allows methods to do different things based on the object they are acting upon.
Modules and Packages
Organizing code into modules and packages
- •A module is a file containing Python definitions and statements that can be imported and used in other Python programs.
- •Modules are imported using the import statement.python
import math print(math.sqrt(16)) # Output: 4.0
- •Specific functions or objects can be imported from a module.python
from math import sqrt print(sqrt(16)) # Output: 4.0
- •Packages are collections of modules in directories that give a package hierarchy.
- •The __init__.py file makes a directory a Python package.
Exception Handling
Handling errors and exceptions in Python
- •Exceptions are runtime errors that can be caught and handled in your code.
- •The try block contains code that might raise an exception.python
try: result = 10 / 0 except ZeroDivisionError: print('Cannot divide by zero!')
- •The except block contains code that is executed if an exception occurs in the try block.python
try: num = int('abc') except ValueError: print('Invalid conversion')
- •The else block contains code that is executed if no exceptions occur in the try block.python
try: num = int('123') except ValueError: print('Invalid conversion') else: print('Conversion successful')
- •The finally block contains code that is always executed, regardless of whether an exception occurred.python
try: file = open('file.txt', 'r') except FileNotFoundError: print('File not found') finally: file.close() # This will always be executed
File Handling
Reading from and writing to files in Python
- •The open() function is used to open a file, with modes like 'r' (read), 'w' (write), 'a' (append), etc.python
file = open('file.txt', 'r')
- •It's best to use the with statement when working with files as it automatically closes the file after use.python
with open('file.txt', 'r') as file: content = file.read()
- •read() method reads the entire file, readlines() reads all lines into a list, and readline() reads one line at a time.
- •write() method writes a string to the file, and writelines() writes a list of strings.python
with open('file.txt', 'w') as file: file.write('Hello, World!')
- •The 'a' mode appends to the file instead of overwriting it.python
with open('file.txt', 'a') as file: file.write('\nNew line appended')
Advanced Python Concepts
More complex Python features and techniques
- •List comprehensions provide a concise way to create lists based on existing lists.python
squares = [x*x for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
- •Generators are iterators that generate values on-the-fly, saving memory.python
def count_up_to(n): i = 0 while i < n: yield i i += 1
- •Decorators add functionality to an existing function without modifying it.python
@timer def slow_function(): time.sleep(2)
- •Context managers (using the with statement) simplify resource management.
- •Async programming with async/await allows efficient handling of I/O-bound operations.python
async def fetch_data(): async with aiohttp.ClientSession() as session: async with session.get('https://api.example.com/data') as response: return await response.json()