Python Fundamentals: 54 Essential Concepts and Code Examples

Python Fundamentals: 54 Essential Concepts

1. Key Features of the Python Programming Language

  • Python is easy to read and write, making it quick for beginners to learn.
  • It is an interpreted language, meaning it executes code line-by-line.
  • It has a large standard library and supports multiple programming styles (procedural, object-oriented, functional).

Example: Basic Output

print("Hello Python")

2. Different Data Types in Python and Their Usage

  • int – Whole numbers (e.g., 5, -10).
  • float – Decimal numbers (e.g., 3.14, 0.5).
  • str – Text values (strings).
  • bool – Boolean values (True or False).
  • list, tuple, dict – Used to store groups of values (collections).

Example: Variable Assignment

a = 5        # int
b = 3.14     # float
name = "Ali" # str (string)

3. Structure and Functionality of an If-Else Statement

  • Used to make decisions in a program based on conditions.
  • Runs one block if the condition is true; otherwise, it executes the else block.

Example: Conditional Logic

age = 18
if age >= 18:
    print("Adult")
else:
    print("Minor")

4. Break and Continue Statements in Python Loops

  • break: Stops the loop immediately, exiting the loop structure entirely.
  • continue: Skips the current iteration of the loop and moves to the next one.

Example: Using Break

for i in range(5):
    if i == 3:
        break
    print(i) # Output: 0, 1, 2 (stops when i = 3)

Example: Using Continue

for i in range(5):
    if i == 3:
        continue
    print(i) # Output: 0, 1, 2, 4 (skips printing 3)

5. Ways to Access a Character in a Python String

  • Using indexing (starting from 0): s[0]
  • Using negative indexing (starting from -1 for the last character): s[-1]
  • Using slicing (to extract a substring): s[1:4]

Example: String Access

s = "Python"
print(s[0])  # P
print(s[-1]) # n

6. Concatenation and Repetition Operations on Strings

  • Concatenation (joining): using the + operator.
  • Repetition: using the * operator.

Example: String Operations

"Hello" + " World" # "Hello World"
"Hi" * 3           # "HiHiHi"

7. String Slicing with Examples

  • Slicing means taking a part of a string using the syntax [start:end]. The character at the end index is excluded.

Example: Slicing Syntax

s = "Python"
print(s[0:3]) # "Pyt"
print(s[2:])  # "thon" (from index 2 to the end)
print(s[:4])  # "Pyth" (from the start up to index 4)

8. Immutability of a String in Python

  • Python strings cannot be changed once they are created.
  • To modify a string, you must create a new string based on the original.

Example: Immutability

s = "Hello"
# s[0] = "J" # ← Not allowed (raises TypeError)
s = "J" + s[1:] # Creates a new string: "Jello"

9. Use of the len() Function and Its Purpose

  • The len() function returns the number of items in an object (e.g., characters in a string, or items in a list/tuple/dictionary).

Example: Calculating Length

len("Python") # 6

10. Use of upper() and lower() String Methods

  • upper() → Converts all characters in the string to capital letters.
  • lower() → Converts all characters in the string to small letters.

Example: Case Conversion

"Hello".upper() # "HELLO"
"Hello".lower() # "hello"

11. find() and replace() Methods in String

  • find() returns the index of the first occurrence of a substring. Returns -1 if not found.
  • replace() changes all occurrences of a specified substring with a new one, returning a new string.

Example: Searching and Replacing

"banana".find("na")      # 2
"hello".replace("h", "j") # "jello"

12. Use of the strip() Function

  • The strip() method removes leading and trailing whitespace (spaces, tabs, newlines) from both ends of a string.

Example: Removing Whitespace

"  hello  ".strip() # "hello"

13. Calculating String Length and Practical Uses

  • Use len() to count characters.
  • Useful for validations (e.g., checking password length), controlling loops, and formatting output.

Example: Length Calculation

x = "Welcome"
print(len(x)) # 7

14. Modifying a String Using the replace() Method

  • replace() returns a new string with the specified text replaced, as strings are immutable.

Example: Replacing Substrings

text = "I like apples"
new_text = text.replace("apples", "mangoes")
# new_text is "I like mangoes"

15. Purpose of Lists in Python and Their Usage

  • Lists store multiple items in a single variable.
  • They are mutable, meaning their contents can be changed (added, removed, or modified) after creation.

Example: Creating a List

fruits = ["apple", "banana", "mango"]

16. Different Ways to Access Elements in a List

  • Using indexing (position): list[0]
  • Using negative indexing (from the end): list[-1]
  • Using slicing (range): list[1:3]

Example: List Access

fruits[0]  # 'apple' (first item)
fruits[-1] # 'mango' (last item)

17. Common List Methods and Examples

  • append() – Adds an item to the end of the list.
    fruits = ["apple", "banana"]
    fruits.append("mango") # ["apple", "banana", "mango"]
  • remove() – Deletes the first occurrence of a specified item.
    fruits.remove("banana") # ["apple", "mango"]
  • insert() – Adds an item at a specified position.
    fruits.insert(1, "orange") # ["apple", "orange", "mango"]
  • sort() – Arranges the list items in ascending order (in place).
    numbers = [3, 1, 2]
    numbers.sort() # [1, 2, 3]
  • pop() – Removes and returns the item at a given index (default is the last item).
    numbers.pop() # [1, 2]

18. Comparing Tuples and Lists

FeatureListTuple
MutabilityYes, items can changeNo, items cannot change (Immutable)
Brackets[ ] Square brackets( ) Parentheses
Examplelst = [1, 2, 3]
lst[0] = 10[10, 2, 3]
tup = (1, 2, 3)
tup[0] = 10 → Not allowed (Error)
UsageChangeable data collectionsFixed data (constants)

19. How to Access Values in a Tuple Using Indexing

Tuple elements are accessed using indexing, exactly the same way as lists, starting from index 0.

Example: Tuple Indexing

t = (10, 20, 30)
print(t[1]) # 20

20. How to Use a Dictionary to Store and Access Data

  • A dictionary stores data in key-value pairs. Keys must be unique and immutable.
  • Data is accessed by referencing the key, not the index.

Example: Dictionary Access

student = {"name": "Ali", "age": 20}
print(student["name"]) # "Ali"

21. Role of the keys() and values() Methods in a Dictionary

  • keys() → Returns a view object containing all the keys in the dictionary.
  • values() → Returns a view object containing all the values in the dictionary.

Example: Dictionary Views

student.keys()   # dict_keys(['name', 'age'])
student.values() # dict_values(['Ali', 20])

22. Using len() to Count Items in a Python List

The len() function is used to calculate the number of items (elements) present in a list.

Example: List Length

len([1, 2, 3, 4]) # 4

23. Modifying an Existing List Using append() and remove()

  • append() adds a single item to the end of the list.
  • remove() deletes the first matching item found in the list.

Example: List Modification

colors = ["red", "blue"]
colors.append("green") # ["red", "blue", "green"]
colors.remove("blue")  # ["red", "green"]

24. Why String Methods Do Not Apply to Tuples

String methods (like upper() or strip()) do not work on tuples because tuples store items (which can be any data type), not characters. These methods are exclusive to the str data type.

Example: Invalid Operation

t = ("apple", "banana")
# t.upper() # → ERROR (AttributeError: 'tuple' object has no attribute 'upper')

25. Dictionary Modification Using update() and pop() Methods

  • update() adds new key-value pairs or changes the value of an existing key.
  • pop() removes a specified key and returns its corresponding value.

Example: Dictionary Updates

d = {"a": 1, "b": 2}
d.update({"c": 3}) # {"a": 1, "b": 2, "c": 3}
d.pop("b")         # removes "b", returns 2

26. Differentiating Between Mutable Lists and Immutable Tuples

FeatureList (Mutable)Tuple (Immutable)
ChangeableYes – you can add, remove, or modify items.No – items cannot be changed once created.
Syntax[ ] Square brackets( ) Parentheses
UsageUse when data may change (e.g., queues, stacks).Use when data is fixed (e.g., coordinates, database records).

27. Comparing How Lists and Dictionaries Store Data in Python

FeatureListDictionary
StorageOrdered sequence of items.Key-value pairs (ordered in Python 3.7+).
AccessBy numerical index [0].By unique key dict["key"].
Example[1, 2, 3]{"name": "Ali", "age": 20}
UsageSequential collection of items.Store items with unique identifiers/labels.

28. How Tuple Slicing Helps Extract Specific Values

  • Slicing allows selecting a part of a tuple without modifying the original tuple.
  • Syntax: tuple[start:end] → extracts items from start up to (but not including) end.

Example: Tuple Slicing

t = (10, 20, 30, 40, 50)
print(t[1:4]) # (20, 30, 40)
print(t[:3])  # (10, 20, 30)
print(t[2:])  # (30, 40, 50)

29. Usefulness of the pop() Method in Lists

  • pop() removes an item from a list and returns the removed item.
  • It can remove the last item (default) or an item at a specific index.
  • It is useful for processing items one by one, often simulating stack or queue behavior.

Example: Using pop()

numbers = [10, 20, 30]
x = numbers.pop()   # removes 30, numbers = [10, 20], x = 30
y = numbers.pop(0)  # removes 10, numbers = [20], y = 10

30. Differentiating Between get() and Direct Access in Dictionaries

FeatureDirect Access (d['key'])get() Method (d.get('key'))
Error if key missingYes, raises KeyError.No, returns None or a specified default value.
UsageWhen the key is guaranteed to exist.Safer way to access keys, preventing program crashes.
Exampled = {"a": 1}; d["b"]KeyErrord.get("b")None

31. Output of Applying len() Function on a Dictionary

  • When applied to a dictionary, len() counts the number of key-value pairs (i.e., the number of keys).

Example: Dictionary Length

d = {"a": 1, "b": 2, "c": 3}
print(len(d)) # 3

32. Purpose of Anonymous (Lambda) Functions in Python

  • Anonymous functions (lambda) are small, one-line functions without a formal name.
  • They are useful for short, simple operations, especially when passed as arguments to higher-order functions (like map, filter, or sort).

Example: Lambda Function

f = lambda x: x * 2
print(f(5)) # 10

nums = [1, 2, 3]
print(list(map(lambda x: x + 1, nums))) # [2, 3, 4]

33. Comparing Global and Local Variables in Python

FeatureGlobal VariableLocal Variable
ScopeAccessible anywhere in the program.Accessible only inside the function where it is defined.
DeclarationOutside all functions.Inside a function.
Examplex = 10
def f(): print(x) → 10
def f(): y = 5; print(y) → 5

34. Usage of the math Module in Python

  • The math module provides access to standard mathematical functions and constants (e.g., sqrt(), ceil(), floor(), factorial()).
  • It is essential for performing complex calculations efficiently.

Example: Using the math Module

import math
print(math.sqrt(16))     # 4.0
print(math.factorial(5)) # 120

35. Different Types of Functions in Python

  1. Built-in functions – Pre-defined functions provided by Python (e.g., len(), print()).
  2. User-defined functions – Functions created by the programmer using the def keyword.
  3. Anonymous (lambda) functions – Small, one-line functions without a formal name.

Example: Function Types

def add(a, b): return a + b # User-defined
f = lambda x: x * 2         # Anonymous
print(len("Python"))        # Built-in

36. Comparing Reading and Writing Modes for File Handling

FeatureReading Mode ‘r’Writing Mode ‘w’
PurposeRead data from a file.Write or overwrite a file.
File Must ExistYes (otherwise raises FileNotFoundError).No (creates a new file if it does not exist; overwrites if it does).
Exampleopen("file.txt", "r")open("file.txt", "w")

37. Utility of Using Modules Like math and random

  • math module: Provides reliable, optimized functions for mathematical operations.
  • random module: Used for generating random numbers, making random selections, or shuffling sequences.

Example: Module Utility

import random
import math

print(math.sqrt(25))        # 5.0
print(random.randint(1, 10)) # Random integer between 1 and 10

38. Use of the input() Function for Data Collection

  • The input() function reads user input from the keyboard as a string.
  • The input must be explicitly converted to int, float, etc., if numerical data is required.

Example: Collecting User Input

name = input("Enter name: ")
age = int(input("Enter age: "))
print(name, age)

39. Python Constructor Method (__init__) and Initialization

  • The Constructor (__init__) is a special method that runs automatically when a new object (instance) of a class is created.
  • Its primary role is to initialize the object’s attributes (instance variables).

Example: Constructor

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

s = Student("Ali", 20)
print(s.name, s.age) # Ali 20

40. Purpose of Using try-finally Clause in Exception Handling

  • The try-finally clause ensures that the finally block is executed no matter what – whether an exception occurs in the try block or not.
  • It is crucial for resource cleanup (e.g., closing files, releasing network connections).

Example: Resource Cleanup

try:
    file = open("example.txt", "r")
    data = file.read()
finally:
    file.close() # Always executed, ensuring the file is closed

41. Use of the except Clause in Python

  • The except block is used to catch and handle specific exceptions that occur within the preceding try block, preventing the program from crashing.

Example: Handling Multiple Exceptions

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Invalid input, please enter a number!")

42. Difference Between Class and Instance Attributes

FeatureClass AttributeInstance/Data Attribute
Defined inClass body (outside methods).Inside the constructor (__init__) using self.
Shared amongAll instances of the class.Unique to each individual instance.
Accessed byClass name or instance.Only by instance.

Example: Attributes

class Person:
    species = "Human" # Class attribute
    def __init__(self, name):
        self.name = name # Instance attribute

43. Outcome of Using Multiple Objects from the Same Class

  • Multiple objects (instances) created from the same class each have their own unique set of instance attributes (data).
  • However, they share the same class attributes and methods defined in the class blueprint.

Example: Independent Instances

p1 = Person("Alice")
p2 = Person("Bob")

print(p1.name, p2.name) # "Alice", "Bob" (Unique)
print(p1.species, p2.species) # Both "Human" (Shared)

44. __init__ Method: Automatic Object Value Initialization

The __init__() method is the mechanism Python uses to automatically initialize object values (attributes) immediately upon object creation, ensuring the object starts in a valid state.

Example: Initialization

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Alice", 25)
print(p.name, p.age)

45. Constructing a Basic User-Defined Exception Class

Custom exceptions are created by defining a new class that inherits from the built-in Exception class (or a subclass thereof).

Example: Custom Exception

class MyError(Exception):
    def __init__(self, message):
        self.message = message
    def __str__(self):
        return self.message

# Usage
try:
    raise MyError("This is a custom error!")
except MyError as e:
    print(e)

46. Class vs. Instance Attributes Summary

  • Class attribute: Data shared among all objects of the class (static data).
  • Instance attribute: Data unique for each object (dynamic data).

Example: Attribute Scope

class Example:
    class_attr = 10 # Shared
    def __init__(self, value):
        self.instance_attr = value # Unique

47. Use of try-finally in Managing Resource Cleanup

The try-finally block is the standard pattern for ensuring that critical resources, such as files or database connections, are properly closed or released, even if errors occur during processing.

Example: Safe File Handling

file = open("example.txt", "w")
try:
    file.write("Hello")
finally:
    file.close() # Ensures file is always closed, preventing leaks

48. Difference Between Built-in and User-Defined Exceptions

FeatureBuilt-in ExceptionsUser-defined Exceptions
Defined byPython language core.The programmer (custom classes).
ExamplesZeroDivisionError, ValueError, TypeError.MyError, InvalidInputError.
PurposeHandle common runtime errors.Handle application-specific business logic errors.

49. Benefits of OOP in Large Python Projects

  • Modularity: Classes group related data and methods, making code easier to organize.
  • Reusability: Classes and objects can be reused across different parts of the project or in future projects.
  • Maintainability: Changes in one class are less likely to affect others due to encapsulation.
  • Encapsulation: Hides internal implementation details, protecting data integrity.
  • Inheritance & Polymorphism: Reduces code duplication and supports flexible design.

50. Steps Involved in Creating and Using a Python Class

  1. Define a class: Use the class keyword (e.g., class Car:).
  2. Define attributes and methods: Include __init__ for initialization and other methods for behavior.
  3. Create objects (instantiation): Call the class like a function (e.g., c = Car("Toyota")).
  4. Access attributes and methods: Use dot notation (e.g., c.show() or c.brand).

Example: Class Usage

class Car:
    def __init__(self, brand):
        self.brand = brand
    def show(self):
        print(self.brand)

c = Car("Toyota")
c.show()

51. Skipping Characters in a String Using Slicing

To skip every second character, use slicing with a step value of 2 ([::2]).

Example: Step Slicing

s = "Hello World"
result = s[::2] # Start to end, step 2
print(result) # HloWrd

52. Logical Operation Operators in Python

  • and → Returns True if both operands are True.
  • or → Returns True if at least one operand is True.
  • not → Reverses the truth value of the operand.

Example: Logical Operators

a = True
b = False
print(a and b) # False
print(a or b)  # True
print(not a)   # False

53. The Two Primary Looping Statements in Python

  • for loop: Used for iteration over a sequence (like a list, tuple, or string) or a range of numbers.
  • while loop: Used for iteration that continues as long as a specified condition remains True.

54. Difference Between while and for Loop in Python

Featurefor Loopwhile Loop
IterationIterates over a sequence or range of items.Iterates until a specific condition becomes False.
Known StepsUsually known in advance (definite iteration).Unknown, depends on the condition (indefinite iteration).
Examplefor i in range(5):while i < 5: