UNIT-1: Introduction to Python 1. Origin and Features of Python Origin: Conceived by Guido van Rossum , inspired by "Monty Python's Flying Circus". Features: Beginner's Language: Easy to learn and read. Interpreted: No compilation needed before execution. Interactive Mode: For testing and debugging. Object-Oriented: Supports OOP. Versatile: For various applications (text processing, web, games). Broad Standard Library: Extensive built-in modules. Portable: Runs on various hardware platforms. GUI Programming: Tools for creating graphical interfaces. Limitations: Slower Execution: Interpreter-based, generally slower than compiled languages. Hardware Communication: High-level, uses layers to communicate with hardware, can be slower. Graphics Intensive Apps: Can run slower for applications with intensive graphics. 2. Keywords and Identifiers Keywords: Reserved words in Python. Role: Cannot be used as variable, function, or other identifier names. Nature: Case Sensitive. Total: 35 keywords in Python. Identifiers: Names given to entities like classes, functions, variables. Rules: Combination of letters (a-z, A-Z), digits (0-9), and underscore (_). Cannot start with a digit (e.g., 3callno is invalid; callno3 is valid). Keywords cannot be used. Special symbols cannot be used. 3. Statements Instructions executed by the Python interpreter. Marked by a newline character. Multiline Statements: Explicit: Using continuation character (\). Implied: Inside parentheses () , brackets [] , or braces {} . pass Statement: A null statement that does nothing. Use Cases: Define empty functions, classes, loops; avoid syntax errors when a code block is required but not ready; temporarily disable code. UNIT-2: Control Structure & Data Types 1. Conditional Statements Decision-making statements based on specific conditions. if Statement: Executes code block if condition is True . if test_expression: # Body of if (Statements to execute if condition is true) Example: if 10 > 5: print("10 is greater than 5") print("Program Ended") if-else Statement: Includes an else block executed if if condition is False . if condition: # Executes this block if condition is true else: # Executes this block if condition is false Example (Eligibility for Vote): age = 20 if age >= 18: print("You are eligible to vote") else: print("You are not eligible to vote") if-elif-else Statement: Shortcut for if-else chain with multiple conditions. if condition1: statement1 elif condition2: statement2 # ... more elif blocks else: statement_else Example (Positive/Negative/Zero): num = float(input("Enter a number: ")) if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number") Nested if-else Statement: An if-else statement inside another for multiple dependent conditions. if condition1: # Outer if # Code block for condition 1 being True if condition2: # Inner if # Code block for condition 2 being True else: # Code block for condition 2 being False else: # Outer else # Code block for condition 1 being False Example (Classify number): number = 10 if number > 0: # Inner check: Is the positive number even or odd? if number % 2 == 0: print("The number is positive and even") else: print("The number is positive and odd") else: # The number is not positive # Inner check: Is the non-positive number zero or negative? if number == 0: print("The number is zero") else: print("The number is negative") Conditional Expressions (Ternary Operator): Shorthand for simple if-else . value_if_true if condition else value_if_false Example: age = 16 status = "Adult" if age >= 18 else "Minor" print(status) # Output: Minor 4. Data Types (Mutable vs. Immutable) Objects whose values can be changed after creation are mutable. Objects whose values cannot be changed after creation are immutable. A. Mutable Data Types Values can be changed; memory address (id) remains the same. Data Type Operations Example Code Snippet Dictionary Create, Access, Update, Add, Delete student["age"] = 21 List Create, Access, Update, Add ( append() , insert() ), Delete ( del , remove() , pop() ) students[2] = "Rahul" Set Create, Add ( add() ), Remove ( remove() , discard() ) my_set.add(60) B. Immutable Data Types Values cannot be changed; a new object with a new memory address is created when value appears to change. Data Type Key Characteristics/Operations Example Code Snippet Tuple Ordered collection; supports indexing and slicing. Must be converted to a list and back to update. student = ("Rahul", 21, "CS") int, float Fundamental number types. x = 10; x = x + 5 (creates a new int object) str Ordered sequence of characters. name = "Hello"; name = name + " World" (creates a new string object) UNIT-3: Functions, Modules & Packages 1. Define function. Explain advantages of functions. Definition: A block of organized, reusable code that performs a single, related action. Advantages: Code Reusability: Call multiple times, avoid rewriting code. Modularity: Breaks down programs into manageable blocks, easier to read, understand, debug. Reduced Code Length: Reusing code blocks reduces program size. 2. Difference between built-in and user-defined functions. Feature Built-in Functions User-defined Functions Definition Pre-defined functions (e.g., print() , len() , type() ). Functions created by the programmer to satisfy specific requirements. Availability Automatically available upon running the Python interpreter. Must be explicitly defined using the def keyword. Purpose Perform common, general tasks. Perform specialized tasks unique to the program logic. 3. Explain anonymous (lambda) functions. Definition: Small, single-expression functions that do not require a formal name. Syntax: lambda arguments: expression Key Characteristics: Created using the lambda keyword. Can take any number of arguments but only one expression. Primarily used when a small function is needed for a short period, often as an argument to higher-order functions like map() , filter() , sorted() . 4. Explain recursion with example. Definition: A programming technique where a function calls itself (directly or indirectly) to solve a problem. Components: Base Case: Condition that stops the recursion. Returns a result without a recursive call. Recursive Step: The part of the function where it calls itself, typically with a modified or smaller version of the problem. Example (Factorial): def factorial(n): if n == 0 or n == 1: # Base Case return 1 else: return n * factorial(n - 1) # Recursive Step print(factorial(5)) # Output: 120 5. Explain scope and lifetime of variables. Scope: Region of the program where a variable is accessible. Local Scope: Inside a function. Global Scope: Outside all functions. Lifetime: Period during which the variable resides in memory. Local Variables: Created when function is called, destroyed when it completes. Global Variables: Created when program starts, destroyed when it terminates. 6. Explain pass by value vs pass by reference. Context in Python: "Pass by Object Reference" or "Pass by Assignment". Not strictly pass-by-value or pass-by-reference. Pass by Value (Conceptual): Function receives a copy of the argument's value. Changes to parameter inside function do not affect original variable. (True for immutable objects: integers, strings, tuples). Pass by Reference (Conceptual): Function receives a reference (memory address) to the original variable. Changes to parameter inside function do affect original variable. (True for mutable objects: lists, dictionaries, sets). Python's Mechanism: Python passes the object's reference. If object is mutable (e.g., a list), its contents can be changed via the reference. If object is immutable (e.g., an integer), re-assigning the variable inside the function points it to a new object, leaving the original external object unchanged. 7. What is a module? Why are modules needed? Definition: A Python file (.py extension) containing Python definitions, statements, and functions. Need for Modules: Organization and Structure: Group related code into logical units. Reusability: Code can be reused across programs. Namespace Separation: Avoid name collisions by providing a separate namespace. 8. Explain different ways of importing modules. Import Method Syntax Description Example Standard Import import module_name Imports the entire module. Access contents using module_name.function() . import math Import with Alias import module_name as alias Imports the entire module and assigns a shorter alias. import pandas as pd From...Import from module_name import name1, name2 Imports only specific names (functions, variables). Use names directly without module prefix. from math import sqrt, pi Import All from module_name import * Imports all names from the module directly into the current namespace. (Generally discouraged). from random import * 9. Explain Python packages with example. Definition: A way of organizing related modules into a directory hierarchy using "dotted module names". Structure: Any directory containing a special file named __init__.py (can be empty) is a Python package. Example Structure: my_project/ ├── my_package/ │ ├── __init__.py │ ├── module_a.py │ └── module_b.py └── main.py Importing: To use module_a.py from main.py , use: import my_package.module_a . 10. Write short note on NumPy / matplotlib. NumPy (Numerical Python): Fundamental package for scientific computing in Python. Supports large, multi-dimensional arrays and matrices, and high-level mathematical functions. Core object is the ndarray (n-dimensional array), faster and more memory-efficient than standard Python lists. Matplotlib: Comprehensive library for creating static, animated, and interactive visualizations. Used for generating plots, histograms, power spectra, bar charts, error charts, scatter plots. pyplot module provides a MATLAB-like interface for plotting. UNIT-4: Exception Handling 1. What is an exception? Definition: An event that occurs during program execution, disrupting normal flow. Distinction: Occurs at runtime (unlike syntax errors). Python raises an exception when it encounters an unhandleable situation. 2. Explain try-except-else-finally block. Structure for handling exceptions gracefully: try Block: Code that might raise an exception. except Block: Handles exceptions from the try block. Can specify exception type (e.g., ZeroDivisionError ). else Block: Executes only if the try block completes successfully (no exception). finally Block: Executes always , regardless of exception occurrence or handling. Used for cleanup operations (e.g., closing files). Example: try: result = 10 / 2 # Code to monitor except ZeroDivisionError: print("Cannot divide by zero.") # Code to handle exception else: print(f"Result: {result}") # Code if no exception occurred finally: print("Execution attempt finished.") # Code that always runs 3. List built-in exceptions in Python. ZeroDivisionError : Second operand of division/modulo is zero. TypeError : Operation/function applied to inappropriate object type. NameError : Local or global name not found. FileNotFoundError : File or directory not found. IndexError : Sequence index (list, tuple) out of range. KeyError : Dictionary key not found. ValueError : Function gets argument of correct type but inappropriate value. 4. Explain user-defined exceptions with example. Definition: Exceptions created by the programmer to handle specific application-logic error conditions. Creation: Define a new class inheriting from Exception or its subclasses. Raising: Using the raise keyword. Example (Age Validation): class InvalidAgeError(Exception): "Raised when the input age is less than 18" pass def validate_age(age): if age UNIT-5: File Processing 1. What is a file? Explain different file modes. Definition: A named location on disk/storage medium used to store data permanently. File Modes: Specify purpose for opening a file. Mode Description If File Exists If File Doesn't Exist 'r' (Read) Opens for reading only. Pointer at beginning. Reading starts. Raises FileNotFoundError . 'w' (Write) Opens for writing. Overwrites existing content. Content is erased. Creates a new file. 'a' (Append) Opens for writing. New content added to the end. New data is appended. Creates a new file. 'r+' (Read/Write) Opens for both reading and writing. Pointer at beginning. Reading/writing starts. Raises FileNotFoundError . 'w+' (Write/Read) Opens for both writing and reading. Overwrites existing content. Content is erased. Creates a new file. 2. Explain read() , readline() , readlines() . Methods to read data from a file opened in read mode: read(size) : Reads entire file as a single string, or up to size bytes/characters. readline() : Reads a single line. A newline character ( \n ) is left at end of string. Returns empty string at end of file. readlines() : Reads all lines as a list of strings, each string being a line from the file. 3. Explain write() method with example. Purpose: Writes a string or sequence of characters to a file. Usage: Must be called on a file object opened in a write mode ( 'w' , 'a' , 'w+' , etc.). Return Value: Number of characters successfully written. Example: file = open("sample.txt", "w") chars_written = file.write("Hello Python.\nThis is file writing.") file.close() # chars_written will be 32 4. Explain tell() and seek() functions. Manage the file object's file pointer (cursor): tell() : Purpose: Returns current position of file pointer (cursor). Value: Position as number of bytes from beginning of file. seek(offset, from_what) : Purpose: Changes file pointer position. offset : Number of bytes to move. from_what (Optional): Reference point: $0$ (beginning, default), $1$ (current position), or $2$ (end of file). 5. Explain renaming and deleting files. Operations performed using functions in the built-in os module: Renaming Files ( os.rename() ): Function: os.rename(current_file_name, new_file_name) . Example: os.rename("old_name.txt", "new_name.txt") . Deleting Files ( os.remove() or os.unlink() ): Function: os.remove(file_name) . Example: os.remove("file_to_delete.txt") . Note: Must import os . 6. Explain directories in Python. Concept: A directory (or folder) is a collection of files and other directories. Python's os module provides functions to interact with the file system. Common Directory Operations: os.getcwd() : Get current directory. os.chdir(new_path) : Change directory. os.mkdir(directory_name) : Create directory. os.rmdir(directory_name) : Remove directory (must be empty). os.listdir(path) : List directory contents. UNIT-6: GUI Programming using Tkinter 1. What is Tkinter? Definition: Python's standard GUI (Graphical User Interface) toolkit. A thin object-oriented layer on Tcl/Tk. Features: Cross-platform (Windows, macOS, Linux). Included with standard Python installations, making it easy for simple GUI applications. 2. Explain any five widgets with syntax. Basic building blocks of a Tkinter application: Label: Displays text or an image. label = tk.Label(parent, text="My Label") Button: Executes a function when pressed. button = tk.Button(parent, text="Click Me", command=function_name) Entry: Accepts a single line of text input. entry = tk.Entry(parent) Text: Displays and edits multi-line text. text = tk.Text(parent, height=10, width=50) Frame: Container widget to organize other widgets. frame = tk.Frame(parent) Note: parent is usually the main window or another Frame . 3. Explain layout management in Tkinter. Refers to how widgets are arranged and positioned. Tkinter provides three main methods: 4. Explain pack() , grid() , place() . pack() : Method: Arranges widgets in blocks. Concept: Uses options like side (top, bottom, left, right) and fill . Good for simple, linear layouts. grid() : Method: Organizes widgets in a two-dimensional table (rows and columns). Concept: Widgets placed in specific cells using row and column options. Popular for complex, structured layouts. place() : Method: Specifies exact size and position using absolute coordinates. Concept: Uses x and y coordinates or relative positioning ( relx , rely , relwidth , relheight ). Offers precise control but difficult to manage on window resize. 5. Explain tkMessageBox . Context: tkMessageBox (or tkinter.messagebox ) module displays standard modal dialog boxes (pop-up windows) to the user. These halt application execution until dismissed. Common Functions: showinfo("Title", "Message") showwarning("Title", "Message") showerror("Title", "Message") askyesno("Title", "Message") (Returns True or False )