Chapter 04a · Computer Science
78 blocks · bilingual

Programming In Python - 4.1 Basic Of Python

LiveBilingual master notes · switch to नेपाली for the full glossary

Complete bilingual study notes for Programming In Python - 4.1 Basic Of Python — every concept explained step by step, with definitions, formulas, and worked examples.

Chapter 4: Programming in Python (Part 1)

Chapter Overview

This chapter revises core Python programming concepts learned earlier and builds on them with user-defined functions and the idea of modules and packages. It focuses on writing correct programs, tracing their output step by step (dry run), and understanding how functions organize code.

  • Revision of Python basics: syntax, data types, operators, string formatting, conditional statements, loops, and library functions.
  • User-defined functions: defining, calling, parameters, arguments, return values, scope, and how data is passed to functions.
  • Dry run practice: tracing programs line by line to find the correct output — a key SEE skill.
  • Modules and packages: organizing reusable code into files and folders.

For SEE, students should be able to write short Python programs, trace the output of given code, explain the purpose of functions and parameters, and describe the difference between modules and packages.

4.1 Revision of the Basics of Python

What is Python?

Python is a high-level, interpreted programming language known for its simplicity and readability. It is widely used in web development, data science, machine learning, automation, and artificial intelligence.

Basic Syntax Rules of Python

  1. 1Python uses indentation instead of curly braces { } to define code blocks.
  2. 2Statements do not need to end with a semicolon.
  3. 3Single-line comments start with #; multi-line comments are written using triple quotes (""" """).
  4. 4Python is case-sensitive — Name and name are treated as different variables.
  5. 5Variable types do not need to be declared; Python assigns types dynamically.
  6. 6Multiple statements can be written on one line using a semicolon ( ; ), though this is not recommended.
  7. 7Long statements can be split using a backslash (\) or by enclosing them in parentheses.

Input and Output Statements

Data Types and Variables

Python provides several built-in data types. Variables store values dynamically and do not need their type declared explicitly.

Example: x = 10 # Integer y = 3.14 # Float name = "John" # String is_valid = True # Boolean

Operators and Expressions

Operators perform operations on values and variables. Python has four commonly used categories: arithmetic, relational, logical, and assignment operators.

Arithmetic Operators

Symbols: +, -, *, / (division), // (floor division), % (modulus), ** (exponentiation)

Example: a, b = 10, 3 print(a + b) # 13 print(a - b) # 7 print(a * b) # 30 print(a / b) # 3.3333333333333335 print(a // b) # 3 print(a % b) # 1 print(a ** b) # 1000

Relational (Comparison) Operators

Symbols: ==, !=, <, >, <=, >=. These compare two values and return True or False.

Example: x, y = 5, 10 print(x == y) # False print(x < y) # True

Logical Operators

Symbols: and, or, not. These combine or invert Boolean values.

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

Assignment Operators

Symbols: =, +=, -=, *=, /=, //=, %=, **=. These assign or update the value of a variable.

Example: x = 5 x += 3 # same as x = x + 3 print(x) # 8

String Formatting in Python

Python offers two common ways to format strings: the older % format specifiers and the modern f-strings (available from Python 3.6 onwards).

% Format Specifiers

f-strings

f-strings format strings by embedding expressions directly inside curly braces { } within an f"" string. The f (or F) before the string enables formatting.

Syntax: f"string {expression}"

Example: name = "Hari" age = 25 print(f"My name is {name} and I am {age} years old.") # Output: My name is Hari and I am 25 years old.

Formatting numbers: price = 49.9876 print(f"Price: {price:.2f}") # Price: 49.99 print(f"Hexadecimal: {255:x}") # Hexadecimal: ff print(f"Octal: {8:o}") # Octal: 10

f-strings can also access dictionary values directly: student = {"name": "Ram", "age": 20, "marks": 90} print(f"Student Name: {student['name']}, Age: {student['age']}, Marks: {student['marks']}")

Conditional Statements (if, elif, else)

Conditional statements are used for decision-making in a program. The elif keyword checks another condition if the first if is False, and else runs when none of the conditions are True.

Example: num = int(input("Enter a number: ")) if num > 0: print("Positive") elif num < 0: print("Negative") else: print("Zero")

Definitions: range, string, list, tuple, dictionary

  1. 1range: A sequence of numbers generated in a specific range. Example: range(1, 5) produces 1, 2, 3, 4.
  2. 2string (str): A sequence of characters enclosed in quotes. Example: "Hello".
  3. 3list: An ordered, mutable (changeable) collection of elements. Example: [1, 2, 3, "apple"].
  4. 4tuple: An ordered, immutable (unchangeable) collection of elements. Example: (10, 20, 30).
  5. 5dictionary (dict): A collection of key-value pairs. Example: {"name": "Alice", "age": 12}.

Loops (Iteration) in Python

A loop repeatedly executes a block of code until a condition is met. Python supports two looping techniques: the for loop and the while loop.

for Loop

The for loop iterates over a sequence such as a range, list, tuple, string, or dictionary.

Example with range: for i in range(1, 6): print(i) # Output: 1 2 3 4 5

Example with a list: fruits = ["Apple", "Banana", "Cherry"] for fruit in fruits: print(fruit)

Looping through a dictionary: student = {"name": "Ram", "Age": 12, "Grade": "10th"} for key in student: print(key) # prints only keys for value in student.values(): print(value) # prints only values for key, value in student.items(): print(f"{key}: {value}") # prints key-value pairs

while Loop

The while loop repeats a block of code as long as a condition remains True.

Example: x = 0 while x < 5: print(x) x += 1 # Output: 0 1 2 3 4

Flowchart comparing how a for loop (iterates over a sequence) and a while loop (repeats while a condition is True) control program flow.

Loop Control Statements

Example of break: for num in range(1, 6): if num == 3: break print(num) # Output: 1 2

Example of continue: for num in range(1, 6): if num == 3: continue print(num) # Output: 1 2 4 5

Example of else with a loop (runs only if no break occurs): for i in range(1, 4): print(i) else: print("Loop finished!") # Output: 1 2 3 Loop finished!

Nested Loops

A loop placed inside another loop is called a nested loop. The inner loop completes all its iterations for each single iteration of the outer loop.

Example: for i in range(1, 4): # Outer loop for j in range(1, 3): # Inner loop print(f"i = {i}, j = {j}")

Library Functions

Library functions are built-in functions in Python used for common tasks such as string manipulation and mathematical operations.

String Functions

Example: text = "hello" print(text.center(10)) print(text.upper()) # HELLO print(text.lower()) # hello print(len(text)) # 5

Math Functions

Example: import math numbers = [1, 2, 3, 4] print(sum(numbers)) # 10 print(pow(2, 3)) # 8 print(round(3.14159, 2)) # 3.14 print(abs(-7)) # 7 print(math.sqrt(16)) # 4.0 print(int(3.7)) # 3

Common Mistakes (4.1)

  • Forgetting to use a colon ( : ) at the end of if, elif, else, for, and while statements.
  • Mixing up = (assignment) and == (comparison) inside a condition.
  • Incorrect indentation, which causes an IndentationError in Python.
  • Confusing / (true division, gives a decimal result) with // (floor division, gives a whole number result).
  • Forgetting to import the math module before using functions like math.sqrt().
  • Using elif/else without a matching if statement above it.

SEE Exam Tips (4.1)

  • Always check indentation carefully — Python relies on it to define blocks.
  • When tracing output, update variable values step by step; do not skip any statement.
  • Remember // gives an integer (whole number) result while / gives a float (decimal) result.
  • Write complete syntax for loops and conditionals, including the colon.
  • Practice writing simple programs using input() and print() together.

Quick Revision (4.1)

  • Python uses indentation, not braces, to define blocks.
  • input() takes user input as a string; print() displays output.
  • Common data types: int, float, str, bool, list, tuple, dict.
  • Arithmetic: + - * / // % **; Relational: == != < > <= >=; Logical: and or not.
  • f-strings: f"text {expression}" is the modern way to format strings.
  • if / elif / else is used for decision-making.
  • for loop iterates over a sequence; while loop repeats while a condition is True.
  • break stops a loop; continue skips an iteration; else with a loop runs only if break was not used.
  • Common string functions: upper(), lower(), center(), len(). Common math functions: sum(), pow(), round(), abs(), sqrt().