Unit: 7 Programming Concept (Python)
Complete notes covering programming languages, algorithms, Python basics, data types, operators, control flow, loops, lists, dictionaries, and library functions, based on the CDC syllabus.
7.1 Introduction to Programming Languages
A programming language is a set of instructions written in a specific format that a computer can understand and follow. Just as humans use languages like English or Nepali to communicate, programmers use programming languages to tell a computer exactly what to do.
A program is simply a sequence of these instructions, written to perform a specific task, such as adding two numbers, sorting a list, or displaying a message on screen.
Why We Need Programming Languages
Computers only understand binary (0s and 1s) at the most basic level. Programming languages act as a bridge, letting humans write instructions in a more understandable form, which is then translated into binary for the computer to execute.
7.2 Types of Programming Languages
Programming languages are generally grouped into three levels, based on how close they are to human language versus machine language:
1. Low-Level Language
Very close to machine code (binary), and difficult for humans to read. Includes:
- Machine language — instructions written directly in binary (0s and 1s), understood directly by the computer’s hardware
- Assembly language — uses short codes (called mnemonics) instead of pure binary, slightly easier for humans but still hardware-specific
2. High-Level Language
Written in a way that’s much closer to human language, making it easier to read, write, and debug. Examples include Python, Java, C++, and JavaScript. High-level code must be translated into machine code before a computer can run it.
3. Middle-Level Language
Combines features of both low-level and high-level languages, offering more control over hardware while still being somewhat readable. C is a common example, often used for system-level programming like operating systems.
| Type | Example | Readability |
|---|---|---|
| Low-level | Machine code, Assembly | Very hard for humans |
| Middle-level | C | Moderate |
| High-level | Python, Java, C++ | Easy for humans |
7.3 Programming Tools: Flowchart and Algorithm
Algorithm
An algorithm is a step-by-step set of instructions written in plain language to solve a specific problem, before any actual code is written. It focuses on logic and order, not on any particular programming language’s syntax.
Example: Algorithm to add two numbers
Step 1: Start Step 2: Input two numbers, A and B Step 3: Add A and B, store the result in Sum Step 4: Display Sum Step 5: Stop
Flowchart
A flowchart is a visual diagram that represents the steps of an algorithm using standard shapes and arrows, making the logic of a program easier to follow at a glance.
Common flowchart symbols:
- Oval — represents Start or Stop
- Parallelogram — represents Input or Output
- Rectangle — represents a Process or calculation
- Diamond — represents a Decision (yes/no or true/false)
- Arrows — show the direction/flow of steps
Both algorithms and flowcharts are planning tools used before writing actual code, helping programmers organize their thinking and catch logical errors early.
7.4 Introduction to Coding, Testing, and Debugging
Coding
Coding is the process of actually writing a program in a programming language, translating an algorithm’s logic into real, executable instructions.
Testing
Testing means running a program with different inputs to check whether it behaves correctly and produces the expected output. Good testing includes trying normal inputs, unusual inputs, and edge cases (like empty input or very large numbers).
Debugging
Debugging is the process of finding and fixing errors (called bugs) in a program. Bugs can cause a program to crash, behave unexpectedly, or produce wrong results.
Common types of errors:
- Syntax errors — mistakes in the code’s structure or spelling, such as a missing colon or bracket, which stop the program from running at all
- Logical errors — the program runs without crashing, but produces the wrong result because the logic itself is incorrect
- Runtime errors — the program crashes while running, often due to things like dividing by zero or trying to use data that doesn’t exist
7.5 Compiler and Interpreter
Since computers only understand machine code (binary), high-level code written by programmers must be translated. This translation is done by either a compiler or an interpreter.
Compiler
A compiler translates the entire program into machine code all at once, before the program runs. If there are errors, the compiler reports all of them together, and the program won’t run until they’re fixed. Languages like C and C++ typically use compilers.
Interpreter
An interpreter translates and runs a program line by line, stopping as soon as it hits an error, rather than checking the whole program first. Python uses an interpreter, which is one reason Python is considered beginner-friendly — errors are easier to trace to a specific line.
| Compiler | Interpreter |
|---|---|
| Translates the whole program at once | Translates and runs line by line |
| Faster execution after compiling | Slower, since translation happens during execution |
| Used by C, C++ | Used by Python |
7.6 Introduction to Python Programming
Python is a high-level, interpreted programming language known for its simple, readable syntax, making it one of the most popular languages for beginners and professionals alike.
Why Python Is Popular
- Simple, English-like syntax that’s easy to read and write
- Free and open-source
- Works on Windows, macOS, and Linux
- Used widely in web development, data science, artificial intelligence, and automation
- Has a huge collection of ready-made libraries for almost any task
Your First Python Program
print("Hello, World!")This single line tells Python to display the text “Hello, World!” on the screen. The print() function is used whenever you want to show output.
Setting Up Python
To write and run Python programs, you need two things: the Python interpreter (downloaded from python.org) and a code editor or IDE (Integrated Development Environment) such as IDLE, Thonny, or Visual Studio Code, where you actually write your code.
7.7 Basic Syntaxes
Syntax refers to the set of rules that define how a Python program must be written so the interpreter can understand it correctly.
Key Syntax Rules in Python
- Indentation — Python uses spaces (usually 4) at the start of a line to show which lines belong together, instead of curly braces used by many other languages
- Case sensitivity — Python treats uppercase and lowercase letters as different, so
Nameandnameare two different variables - Comments — text ignored by the interpreter, used to explain code; single-line comments start with
#
# This is a comment
age = 15
if age > 12:
print("You are a teenager")Notice how the line inside the if statement is indented — this tells Python it belongs to that condition.
7.8 I/O Statements and String Formatting
Output with print()
print("Welcome to Python")
print(5 + 3)Input with input()
The input() function lets a program accept data typed by the user. It always returns the value as text (a string), even if the user types a number.
name = input("Enter your name: ")
print("Hello, " + name)String Formatting
String formatting lets you neatly combine text and variables in a single output line. The most common and modern method is the f-string:
name = "Sita"
age = 15
print(f"{name} is {age} years old")Placing an f before the quotation marks lets you insert variables directly inside curly braces {}, without needing to join text and numbers manually.
7.9 Data Types and Variables
Variables
A variable is a named location in memory used to store a value that can change while a program runs. In Python, you don’t need to declare a variable’s type in advance — it’s decided automatically based on the value assigned.
name = "Hari" age = 14 height = 5.4 is_student = True
Common Data Types in Python
| Data Type | Description | Example |
|---|---|---|
| int | Whole numbers | 14, -5, 100 |
| float | Decimal numbers | 5.4, 3.14 |
| str | Text, written in quotes | “Hari”, “Class 9” |
| bool | True or False values | True, False |
You can check a variable’s data type using the type() function:
age = 14 print(type(age))
7.10 Concept of Type Casting
Type casting means converting a value from one data type to another. This is often needed because input() always returns text, even when the user types a number.
age = input("Enter your age: ")
age = int(age)
print(age + 1)Here, int() converts the text entered by the user into a whole number, so it can be used in a calculation.
Common Type Casting Functions
int()— converts a value to a whole numberfloat()— converts a value to a decimal numberstr()— converts a value to text
num = 10 text = str(num) print(text + " apples")
7.11 Operators and Expressions
An operator performs an action on one or more values (called operands), and an expression is a combination of values and operators that produces a result.
Arithmetic Operators
| Operator | Meaning | Example |
|---|---|---|
| + | Addition | 5 + 3 → 8 |
| – | Subtraction | 5 – 3 → 2 |
| * | Multiplication | 5 * 3 → 15 |
| / | Division (gives decimal) | 5 / 2 → 2.5 |
| // | Floor division (whole number) | 5 // 2 → 2 |
| % | Modulus (remainder) | 5 % 2 → 1 |
| ** | Exponent (power) | 5 ** 2 → 25 |
Relational (Comparison) Operators
These compare two values and always return either True or False: == (equal to), != (not equal to), >, <, >=, <=.
print(5 == 5) # True print(5 != 3) # True print(5 > 10) # False
Logical Operators
Used to combine multiple conditions: and (true only if both are true), or (true if at least one is true), not (reverses a result).
age = 15 print(age > 10 and age < 18) # True
Assignment Operators
Used to assign or update the value of a variable: = (assign), += (add and assign), -= (subtract and assign), and similar shortcuts for other operations.
score = 10 score += 5 # same as score = score + 5 print(score) # 15
7.12 Conditional Statement (if, elseif, else)
Conditional statements let a program make decisions and run different code depending on whether a condition is true or false.
marks = 75
if marks >= 80:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")- if — runs its block only if the condition is true
- elif (short for “else if”) — checked only if the previous conditions were false; you can have multiple elif blocks
- else — runs if none of the above conditions were true
In the example above, since marks is 75, the program skips the first condition, checks the elif (75 is greater than or equal to 60), and prints “Grade B”.
7.13 Iteration (for and while)
Iteration means repeating a block of code multiple times, which is useful whenever a task needs to happen more than once, such as printing numbers 1 to 10.
for Loop
Used when you know in advance how many times you want to repeat something.
for i in range(1, 6):
print(i)This prints numbers 1 through 5. The range(1, 6) generates numbers starting at 1 and stopping before 6.
while Loop
Used when you want to repeat something as long as a condition remains true, even if you don’t know the exact number of repetitions in advance.
count = 1
while count <= 5:
print(count)
count += 1This loop keeps running and printing until count becomes greater than 5. Without the line count += 1, the loop would run forever, called an infinite loop.
7.14 List and Dictionary
List
A list is a collection of values stored in a single variable, written inside square brackets and separated by commas. Lists can hold multiple items, and their values can be changed after creation.
fruits = ["apple", "banana", "mango"]
print(fruits[0]) # apple
fruits.append("grape")
print(fruits)- Items in a list are accessed using an index, starting from 0
.append()adds a new item to the end of the listlen(fruits)gives the number of items in the list
Dictionary
A dictionary stores data as key-value pairs, letting you look up a value using a meaningful name (the key) instead of a numbered position.
student = {"name": "Rita", "age": 15, "grade": "9"}
print(student["name"]) # Rita
student["age"] = 16
print(student)Here, "name", "age", and "grade" are keys, and "Rita", 15, and "9" are their corresponding values.
7.15 Library Functions: String and Mathematical Functions
Python comes with many built-in functions that perform common tasks, so you don’t have to write that logic yourself.
String Functions
text = "computer" print(text.upper()) # COMPUTER print(text.lower()) # computer print(text.center(20, "*")) # centers text with * padding print(len(text)) # 8
.upper()— converts text to all uppercase letters.lower()— converts text to all lowercase letters.center(width, char)— centers text within a given width, padding with a chosen characterlen()— returns the number of characters in a string (or items in a list)
Numeric and Mathematical Functions
print(sum([1, 2, 3, 4])) # 10 print(pow(2, 3)) # 8 (2 to the power of 3) print(round(4.678, 2)) # 4.68 print(abs(-9)) # 9 import math print(math.sqrt(16)) # 4.0
sum()— adds up all the numbers in a listpow(x, y)— raises x to the power of yround(number, digits)— rounds a decimal number to a chosen number of digitsabs()— returns the absolute (positive) value of a numbermath.sqrt()— returns the square root of a number, requiresimport mathfirstint()— converts a value to a whole number, dropping any decimal part
Practical Tasks
- Download and install Python from the official python.org website.
- Set up an IDE (such as IDLE, Thonny, or VS Code) and customize the interface (theme, font size) for comfortable coding.
- Demonstrate the use of I/O statements using
input()andprint(). - Demonstrate the concept of constants, variables, and data types with example code.
- Demonstrate the use of various operators (arithmetic, relational, logical, assignment) with example expressions.
- Demonstrate the use of if, elif, and else statements with a real example, such as grading marks.
- Demonstrate the use of a for loop, such as printing a multiplication table.
- Demonstrate the use of a while loop, such as a countdown program.
- Demonstrate the use of a list and dictionary with relevant examples, such as storing and displaying student records.
- Demonstrate and use string functions (upper, lower, center, len) and mathematical functions (sum, pow, round, abs, sqrt) with example code.
Project Work
Develop a simple real-life project using Python programming and libraries, such as a calculator performing basic mathematical operations (addition, subtraction, multiplication, division), using functions, conditionals, and user input covered in this unit.
