Unit 2: Python Programming — Short Questions
11th Class Computer Science · Unit 2: Unit 2: Python Programming
Introduction to Python Programming
Python's simple syntax (like plain English), readability, and dynamic typing make it easy to learn and use, reducing the learning curve for beginners.
A strong community provides extensive support, tutorials, libraries, and frameworks, enabling problem-solving across diverse fields and accelerating development.
Python supports multiple domains like web development, data analysis, AI, automation, and game development, making it a one-stop solution for varied applications.
The name comes from the comedy show Monty Python's Flying Circus, not the snake, reflecting the language's playful design philosophy.
Writing code, compiling/interpreting, executing, and producing output. These steps translate human logic into machine-executable instructions.
IDEs like PyCharm or VS Code offer features like syntax highlighting, debugging, and code completion, streamlining development and reducing errors.
Adding Python to PATH allows running Python scripts from any directory via the command line without specifying the full installation path.
Basic Python Syntax and Structure
Python uses indentation and minimal symbols (e.g., no semicolons), prioritizing readability over complex syntax.
Comments (single-line '#' or multi-line '"""') explain code logic, improving readability and aiding collaboration.
Variables can hold any data type without prior declaration, allowing rapid prototyping and adaptable code.
They make code self-documenting, reduce reliance on comments, and ease debugging and maintenance.
Names must start with a letter/underscore, avoid reserved keywords, use snakecase, and be case-sensitive.
Integers (int) are whole numbers, while floats (float) represent decimal values (e.g., age = 17 vs. price = 19.99`).
It ensures data integrity by converting user inputs (strings) to appropriate types (e.g., `int(input())`).
Operators and Expressions
An operator is a symbol or sign used to perform a specific operation on data. For example, '+' is used for addition, '-' for subtraction, '*' for multiplication, and '/' for division. Operators help us do calculations or compare values in programming.
An expression is a combination of variables, numbers, and operators that gives a result. For example, '2 + 3', 'a * b', or 'x > y' are all expressions. When the computer runs the code, it calculates the value of the expression.
'/' returns a float (e.g., `10 / 3 = 3.33`), while '//' performs floor division (e.g., `10 // 3 = 3`).
They evaluate relationships between values (e.g., '==', '!=', '>', '<=') and return Boolean results (`True`/`False`).
To combine multiple conditions (e.g., 'x > 5 and x < 10') for complex decision-making.
Operator precedence tells which operator is used first in an expression. Python follows rules to decide the order of operations like, '+, and '-'. It helps to get the correct result from a complex expression.
Control Structures
In programming, we often need to control the flow of our program based on different conditions or repeat certain actions multiple times.
There are two main types of control structures:
1. Decision making
2. Looping
The if statement allows us make decisions based on conditions. If the condition is true, it runs a block of code.
Syntax
if condition:
statement
The if-else statement allows us to execute one block of code if a condition is true and another block if the condition is false.
Syntax
if condition:
statement
else
statement
Python also allows a short-hand if-else statement that can be written in a single line.
#Syntax of short hand if-else statement
actioniftrue if condition else actioniffalse
It enables multi-way branching, allowing different code blocks to execute based on varying conditions.
Using 'if-elif-else' chains or nested conditionals to evaluate complex logical scenarios.
Loops
`while` repeats as long as a condition is true (e.g., counting to 10), while `for` iterates over a sequence (e.g., list items).
It generates a sequence of numbers for controlled iterations (e.g., 'for i in range(5)' runs 0-4).
Python Modules and Built-in Data Structures
They promote code reuse, modularity, and organization by encapsulating logic into callable blocks.
They allow optional arguments (e.g., 'greet(name="Student")), making functions adaptable to varying inputs.
They group related functions/classes into files, enabling reuse across projects and reducing redundancy.
It loads external modules/libraries (e.g., 'import math') to access pre-built functionality.
They support multiple data types, dynamic resizing, and methods like append() and sort() for flexible data manipulation.
To manage large projects, you can organize modules into packages. A package is simply a directory (folder) containing related modules. For example, if you're building an e-commerce platform, you could create a package named ecommerce with modules like products.py, customers.py, and orders.py.
Built-in Data Structures
Tuples are immutable (unchangeable) and use parentheses, while lists are mutable and use square brackets.
It extracts subsets of data (e.g., 'list[1:4]') using start, stop, and step indices for efficient data handling.
They allow reverse traversal (e.g., 'list[-1]' accesses the last item), simplifying operations like retrieving end elements.
Python provides several built-in methods to work with lists:
• append(item) – Adds an item to the end of the list.
Example: mylist.append(5) adds 5 to the end of the list.
• remove(item) – Deletes the first time that item appears in the list.
Example: mylist.remove(3) removes the first 3 it finds.
• sort() – Arranges the list in order, from smallest to biggest.
Example: mylist.sort() sorts numbers like 1, 2, 3, etc.
• reverse() – Flips the list so the last item comes first.
Example: mylist.reverse() turns [1, 2, 3] into [3, 2, 1].
Dictionaries store key-value pairs for fast lookups, while lists maintain ordered, indexed collections.
Modular Programming Python
Modular programming is a technique used to divide a program into smaller, manageable, and reusable pieces called modules. By breaking a program into modules, developers can work on different parts independently and reuse code efficiently. This approach simplifies managing complex programs and promotes code reuse.
It breaks programs into manageable modules, enhancing maintainability, collaboration, and code reuse.
It defines the program's entry point, ensuring code runs only when executed directly, not when imported.
Object-Oriented Programming in Python
Object-Oriented Programming (OOP) in Python is a way of organizing and structuring code by creating classes and objects. A class is a template or blueprint for creating objects, and an object is an instance of a class with specific attributes and behaviors.
A class is like a template for creating things, and an object is an actual thing created from that template. Imagine you want to make a toy car. You first need a blueprint or a template that describes how the toy car should look and function. This template includes details like:
• Color
• Size
• Number of wheels
• Type of material
Advanced Python Concepts
It enables persistent data storage (e.g., reading/writing text or binary files) for applications like logging or configuration.
Exception handling is a mechanism to manage errors that occur during program execution. It allows a program to continue running or gracefully terminate if an error occurs, ensuring more robust and error-resilient code.
In Python, the try block lets you test a block of code for errors, and the except block lets you handle errors if occur.
It automatically closes files after operations, ensuring resource safety even if errors occur.
'w' overwrites existing content, while 'a' adds new data to the end of the file.
Testing and Debugging in Python
It tests individual code units (e.g., functions) using the 'unittest' module to validate correctness.
It provides an interactive debugger to step through code, inspect variables, and analyze runtime behavior.