Review of Python

July 5, 2025
8 views
0 comments
Review of Python

Section 1: Interactive and Script Mode

This section deals with the two fundamental environments where you can write and execute Python code.

Analogy: Think of Interactive Mode as having a live conversation with a calculator, and Script Mode as writing a full recipe to be followed later.

Interactive Mode

This is the direct command-line shell where you can execute one command at a time and get immediate results. It is also known as the REPL (Read-Eval-Print Loop) because it Reads your command, Evaluates it, Prints the result, and Loops back to wait for the next command.

  • How it looks: You'll see the Python prompt, which is three greater-than signs (>>>).
  • Purpose:
    • Testing: Quickly test a small piece of code or a function.
    • Exploring: Experiment with commands to see what they do.
    • Debugging: Check the value of variables while a program is running (in more advanced scenarios).
  • Limitation: The code you write is not saved. Once you close the shell, everything is gone.

Code Example:

>>> 25 * 4
100
>>> my_name = "Arjun"
>>> print("Hello, " + my_name)
Hello, Arjun
>>>

Notice how Python responds instantly after each line is executed.

Script Mode

This is the standard method for writing programs. You write your code in a text file and save it with a .py extension. The Python interpreter then executes all the commands in the file from top to bottom.

  • How it works:
    1. Open a text editor or an Integrated Development Environment (IDE) like IDLE, VS Code, etc.
    2. Write multiple lines of code.
    3. Save the file (e.g., my_first_program.py).
    4. Run the file from the command line (python my_first_program.py) or using the "Run" command in your IDE.
  • Purpose:
    • Building Applications: This is how all real-world software is created.
    • Reusability: You can save your code and run it anytime you want without retyping it.
    • Organization: Allows for complex, multi-line logic that is well-structured.

Code Example (saved in a file named area_calculator.py):

# This program calculates the area of a rectangle
length = 10
width = 5
area = length * width

print("The length is:", length)
print("The width is:", width)
print("The area of the rectangle is:", area)

When you run this script, it executes all lines sequentially and prints the final output.


Section 2: Data Types, Variables, and Keywords

These are the absolute fundamentals of storing and managing information in any program.

Variables

A variable is a named location in memory used to store a value. You can think of it as a labeled box where you put information. The name you give it (the identifier) should be descriptive.

Assignment: You create a variable and give it a value using the assignment operator (=).

score = 95          # Variable 'score' now holds the value 95
student_name = "Ria"  # Variable 'student_name' holds the text "Ria"

Data Types

Python automatically detects the type of data you store in a variable. The primary data types are:

  • Numbers:
    • int: Integer (whole numbers). E.g., 12, -50, 0.
    • float: Floating-point numbers (with decimals). E.g., 19.99, 3.14159.
  • String (str): A sequence of characters, enclosed in single (') or double (") quotes. E.g., "Computer Science", 'Python'.
  • Boolean (bool): Represents one of two values: True or False. It is the basis for all logical decisions.
  • NoneType: A special data type that represents the absence of a value. There is only one None value.

You can check a variable's type using the type() function: print(type(score)) Output: <class 'int'>

Keywords

These are reserved words that have a special meaning in Python. You cannot use them as names for your variables, functions, or any other identifiers.

  • Examples: if, else, for, while, def, class, import, return, True, False, None.

Section 3: Operators and Flow of Control

This section covers how you perform calculations and control the order in which your code is executed.

Operators

  • Arithmetic: Perform mathematical calculations: + (add), - (subtract), * (multiply), / (divide), % (modulus/remainder), ** (exponent).
  • Relational: Compare two values and return a Boolean (True or False): == (equal to), != (not equal to), > (greater than), < (less than), >=, <=.
  • Logical: Combine Boolean expressions: and (both must be true), or (at least one must be true), not (inverts the value).

Flow of Control

This determines the execution path of your program.

  1. Sequential: The default mode. Code is executed line by line, from top to bottom.

  2. Selective (Conditional): Uses if, elif (else if), and else to make decisions. A block of code is executed only if a certain condition is met.

    marks = 75
    if marks >= 90:
        print("Grade: A")
    elif marks >= 80:
        print("Grade: B")
    else:
        print("Grade: C or below")
    
  3. Iterative (Looping): Repeats a block of code multiple times.

    • for loop: Used when you know how many times you want to loop, or you want to iterate over a sequence (like a list or string).

      # Prints numbers from 0 to 4
      for i in range(5):
          print(i)
      
    • while loop: Used when you want to loop as long as a condition remains True.

      count = 1
      while count <= 3:
          print("Looping, count is:", count)
          count = count + 1 # or count += 1
      

Section 4: Functions, Modules, and Built-in Operations

This is about writing organized, reusable, and powerful code.

Built-in Operations/Functions

These are functions that are always available in Python. You don't need to import anything to use them.

  • Examples: print(), input(), len() (finds the length of a sequence), int() (converts to integer), str() (converts to string).

Functions (User-Defined)

A function is a named, reusable block of code that performs a specific task. You define it once using the def keyword and can call it whenever needed.

  • Structure:
    def function_name(parameter1, parameter2):
        # Code to perform the task
        # ...
        return result_value # Optional
    
  • Parameters: Variables listed inside the parentheses in the function definition.
  • Arguments: The actual values you pass to the function when you call it.

Code Example:

# Defining the function
def greet(name):
    print("Hello, " + name + "! Welcome.")

# Calling the function with an argument
greet("Sonia")
greet("Ravi")

Output: Hello, Sonia! Welcome. Hello, Ravi! Welcome.

Modules

A module is a Python file (.py) containing a collection of functions and variables. You can bring these tools into your program using the import statement. This is how Python's functionality is extended.

# Importing the 'math' module to use its functions
import math

# Now we can use functions from the math module
radius = 7
area = math.pi * (radius ** 2)
print("The area of the circle is:", area)

# Importing the 'random' module
import random

# Get a random integer between 1 and 6 (like rolling a die)
dice_roll = random.randint(1, 6)
print("You rolled a:", dice_roll)

Section 5: String, List, Tuple, and Dictionary Manipulation

These are the primary collection data types in Python. It's vital to know their differences.

String (str)

A sequence of characters.

  • Syntax: Enclosed in quotes ('...' or "...').
  • Key Properties: Ordered (each character has an index), Immutable (cannot be changed after creation).
  • Manipulation: Slicing (my_str[0:5]), concatenation (+), methods like .upper(), .lower(), .find().

List (list)

A general-purpose, ordered sequence of items.

  • Syntax: Comma-separated items in square brackets [...].
  • Key Properties: Ordered, Mutable (you can add, remove, or change elements).
  • Manipulation: Indexing (my_list[0]), slicing (my_list[1:3]), methods like .append(item), .pop(), .sort().
subjects = ["Physics", "Chemistry", "Maths"]
subjects.append("Computer Science")  # Adds an item to the end
print(subjects)                   # Output: ['Physics', 'Chemistry', 'Maths', 'Computer Science']
subjects[0] = "Modern Physics"      # Changes an existing item
print(subjects)                   # Output: ['Modern Physics', 'Chemistry', 'Maths', 'Computer Science']

Tuple (tuple)

An ordered sequence of items, similar to a list.

  • Syntax: Comma-separated items in parentheses (...).
  • Key Properties: Ordered, Immutable (cannot be changed). Think of it as a "read-only" list.
  • Use Case: For data that should not be modified, like days of the week or coordinates (10, 20).
# A tuple of RGB color values
red_color = (255, 0, 0)
# red_color[0] = 200  # This would cause a TypeError!

Note: A tuple with one item needs a trailing comma: my_tuple = (1,).

Dictionary (dict)

An unordered collection of key-value pairs.

  • Syntax: Comma-separated key: value pairs in curly braces {...}.
  • Key Properties: Unordered (you access elements by key, not index), Mutable. Keys must be unique and immutable (e.g., strings, numbers, or tuples).
  • Manipulation: Accessing my_dict['key'], adding a new pair my_dict['new_key'] = value, getting all keys with .keys() or values with .values().
student_details = {
    "name": "Priya",
    "roll_no": 21,
    "stream": "Science"
}

# Accessing a value
print(student_details["name"])  # Output: Priya

# Adding a new key-value pair
student_details["city"] = "Delhi"
print(student_details)
# Output: {'name': 'Priya', 'roll_no': 21, 'stream': 'Science', 'city': 'Delhi'}

Arbind Singh

Teacher, Software developer

Innovative educator and tech enthusiast dedicated to empowering students through robotics, programming, and digital tools.

Comments (0)

You need to be signed in to post a comment.

Sign In

No comments yet

Be the first to share your thoughts and insights about this note!

Note Stats

Views8
Comments0
PublishedJuly 5, 2025

Related Notes

Introduction to Computer Science

Class 11 • Computer Science

Python Programming Basics

Class 12 • Computer Science

Database Management Systems

Class 12 • Informatics Practices

Part of Course

CBSE Class XII Computer Science with Python

Price
Free
Review of Python | StudyVatika Notes