Grade 11 - Fundamentals of Programming Notes
Computer Program
- A set of instructions that tells a computer what tasks to perform.
- The computer follows these instructions step by step.
Purpose of Programs
- All computer actions are based on the instructions given in programs.
- No task is done without being explicitly programmed.
Topics Covered in This Unit
- Programming languages: Tools used to write programs (e.g., Python, Java).
- Syntax: The rules of writing code correctly.
- Semantics: The meaning or logic behind the code instructions.
Language Used in This Unit
- The unit uses Python, a high-level programming language.
- Python is used to teach the basic concepts of programming in a simple and readable way
Types of Programming Languages
Machine Language
- A low-level language.
- Written in binary (1s and 0s).
- Understood directly by computers (no translation needed).
- Very fast and memory-efficient, but extremely hard for humans to write and understand.
Assembly Language
- Also a low-level language.
- Uses mnemonics (symbols) instead of 1s and 0s (e.g., MOV, ADD).
- Easier than machine language, but still difficult to use.
- Needs an Assembler to convert it into machine language.
High-Level Language
- Closer to human language (e.g., English-like words).
- Easy to learn and use.
- Examples: Python, Java, C, C++, C#, Perl, Ruby
- Requires translation into machine language using:
- Compiler: Translates the whole program at once.
- Interpreter: Translates and runs the program line by line.
- Compiled Languages: C, C++, Java, C#
- Interpreted Languages: Python, Perl, Ruby
Syntax and Semantics
Syntax
- The rules and structure of a programming language.
- Similar to grammar in human languages.
- If you break syntax rules, the program won’t run and will give a syntax error.
Semantics
- The meaning of the program statements (what the code actually does).
- A program with correct syntax can still behave wrongly due to logic errors.
- Logic error = The program runs but gives wrong results due to incorrect instructions.
Key Terms Recap
- Machine Language: Binary code directly executed by the CPU
- Assembly Language: Symbolic code (mnemonics) translated by an assembler
- High-Level Language: Human-friendly code translated by a compiler or interpreter
- Syntax: Rules for writing correct code
- Semantics: Meaning and behavior of the code
- Syntax Error: Mistake in grammar (code won't run)
- Logic Error: Mistake in meaning (code runs but behaves incorrectly)
Basics of Python
Python Programming Language
- Python is a high-level, easy-to-learn programming language.
- It is widely used for teaching beginners due to its simple syntax.
- Python is free and open-source.
Python's Integrated Development Environment (IDLE)
- IDLE stands for Integrated Development and Learning Environment.
- It is the default environment provided with Python for writing and executing Python code.
- IDLE includes:
- Interactive Interpreter (Shell)
- Text Editor
Interactive Interpreter (Python Shell)
- It is a textual user interface that allows users to:
- Type and execute one line of code at a time.
- Get immediate feedback or results.
- Opened automatically when you start IDLE.
- Best used for:
- Simple testing
- Trying out quick commands
- Learning syntax step-by-step
- Limitation: Not suitable for writing and running multiple lines of code (programs).
Text Editor in IDLE
- Used to write multiple lines of Python code (programs).
- The written code can be saved as a .py file and executed with a single command.
- More convenient for:
- Writing complete programs
- Debugging
- Saving and editing scripts
Using the Interactive Interpreter
- The Interactive Interpreter appears when you open IDLE.
- It includes the Python Shell, a text-based interface to type and run Python code line by line.
- When you type a command or expression and press Enter, Python immediately executes it and shows the result.
- Example:
python print("Hello, world!")- Output:
Hello, world!
- Output:
- The
print()function is used to display text or results on the screen.
Using the Text Editor
- The Text Editor in IDLE is used to write and save multiple lines of Python code (called a script).
- A Python script is saved with the .py extension.
- Steps to create a script:
- Open IDLE.
- Click
File → New Fileto open the Text Editor. - Type your code in the new window.
- Save the file with a
.pyextension (e.g.,circle_area.py).
- To run the script:
- Go to
Run → Run Module. - The output appears in the Interactive Interpreter window (Python Shell).
- Go to
- Example: Calculate the Area of a Circle
- A sample script to calculate the area of a circle with radius 3:
python radius = 3 area = 3.14 * radius * radius print("Area of the circle is:", area)
- A sample script to calculate the area of a circle with radius 3:
- After running, the output will be shown in the shell.
Variables and Data Types
Variables
- Definition: A variable is a memory location used to store data. In Python, variables are created when a value is assigned to them.
- Assignment Operator (=): Used to assign values.
- Left side → variable
- Right side → value or expression
- Examples:
python x = 5 # Assigns 5 to variable x y = 5 + 9 # Assigns 14 to variable y - Viewing Variable Values: Type the variable name and press Enter:
python y # Output: 25 (if y = 25) - Reassigning Values: Variables can be updated:
python y = 30 # y now holds the value 30
Identifiers
- Definition: An identifier is the name given to a variable.
- Rules for Valid Identifiers:
- Must start with a letter or underscore (_)
- Remaining characters can be letters, numbers, or underscores
- Cannot be a Python keyword (e.g., if, while, def, etc.)
- Case-sensitive (x and X are different)
- Best Practice: Use self-descriptive identifiers (e.g.,
student_ageinstead ofx) to improve code clarity.
Data Types
- Definition: A data type specifies the kind of value a variable can hold and the operations that can be performed on it.
- Common Built-in Data Types in Python:
int→ whole numbers (e.g.,x = 10)float→ decimal numbers (e.g.,pi = 3.14)str→ strings or text (e.g.,name = "Alice")bool→ Boolean values (True or False)
- Example of Data Types in Action:
python a = 42 # a is an integer (int) b = 3.14 # b is a float c = "Hello" # c is a string (str) d = True # d is a Boolean (bool) - Automatic Data Type Assignment: The data type is automatically determined by the value assigned to the variable.
Additional Concepts: Strings and the type() Function
- Strings Must Be in Quotation Marks:
- In Python, string values must be enclosed in either single (') or double (") quotation marks.
- Example:
python name = "Alice" # Valid string greeting = 'Hello' # Also valid
- Determining Data Type with
type()Function:- Python provides a built-in function called
type()to check the data type of a variable. - Syntax:
python type(variable_name) - Example:
python x = 10 y = "Hello" print(type(x)) # Output: <class 'int'> print(type(y)) # Output: <class 'str'>
- Python provides a built-in function called
Data Type Conversion
Data type conversion refers to changing the value of one data type into another. Python supports two types of type conversion:
Implicit Type Conversion
- Definition: Done automatically by Python, without programmer intervention.
- Purpose: To prevent loss of data when performing operations involving different data types.
- How it works: Python converts smaller data types to larger ones, such as from int to float.
- Example:
python x = 5 # int y = 3.2 # float z = x + y # z becomes float (8.2) print(type(z)) # Output: <class 'float'>- Here,
xis an integer, andyis a float. - Python automatically converts
xto float before performing the addition. - The result
zbecomes a float to maintain precision.
- Here,
Explicit Type Conversion (Type Casting)
- Definition: Done manually by the programmer using built-in functions.
- Functions Used:
int()– converts to integerfloat()– converts to floating-point numberstr()– converts to string
- Syntax:
python variable_name = data_type(value) - Invalid Operation Example:
python x = 5 # int y = "10" # str z = x + y # ERROR: can't add int and str
Python raises aTypeErrorbecause it can't add a number (int) to text (str). - Corrected with Explicit Conversion:
python x = 5 y = "10" z = x + int(y) # y converted to int print(z) # Output: 15
Here,int(y)converts the string"10"into the integer10, allowing the addition to proceed correctly.
Summary Table
| Conversion Type | Done By | Example | Result Type |
|---|---|---|---|
| Implicit | Python | 5 + 2.0 → 7.0 | float |
| Explicit | Programmer | int("10") + 5 → 15 | int |
Statements and Expressions
What is a Statement?
- A statement is an instruction that Python can execute.
- It tells the computer to do something, like assigning a value, printing output, or making decisions.
Examples of Python Statements:
- Assignment Statement
- Assigns a value to a variable.
- Example:
python x = 10
- Print Statement
- Displays the value or result on the screen.
- Example:
python print("Hello, world!")
- Control Statements
These are used to control the flow of a program:
- If Statement – used for decision making
python if x > 5: print("x is greater than 5") - While Statement – repeats code while a condition is true
python while x > 0: print(x) x = x - 1 - For Statement – repeats code a specific number of times
python for i in range(5): print(i)
- If Statement – used for decision making
What is an Expression?
- An expression is any combination of variables, values, and operators that evaluates to a value.
- Expressions are often part of statements.
Example of Expressions:
a = 5 + 3 # 5 + 3 is an expression, a = 8 is the statement
5 + 3is the expression (evaluates to 8)a = 5 + 3is the statement (assigns 8 to a)
Summary Table
| Concept | Description | Example |
|---|---|---|
| Statement | Command Python executes | x = 10 |
| Expression | Produces a value | 5 + 3, "Hi" + "There" |
| If Statement | Makes a decision | if x > 5: |
| While Loop | Repeats while condition is true | while x < 10: |
| For Loop | Repeats a block of code | for i in range(3): |
Writing a Simple Program
Python Program
Write a program in the text editor that has the following elements:
- Accept the name, age, and Body Mass Index (BMI) of a person from the keyboard using the
input()function, - Convert the values to their appropriate data type,
- Display the values using the
print()function
# Accepting input from the user
name = input("Enter your name: ")
age = int(input("Enter your age: ")) # Convert age to integer
bmi = float(input("Enter your BMI: ")) # Convert BMI to float
# Displaying the values
print("---- Personal Information ----")
print("Name:", name)
print("Age:", age)
print("BMI:", bmi)
Explanation:
input()always returns a string, so:int()is used to convert age to an integer.float()is used to convert BMI to a decimal number.
print()displays the collected and converted values in a readable format.
Understanding the input() Function in Python
Prompt Message: When using
input(), you can provide a prompt string that tells the user what to enter.Example:
x = input("Enter an integer number: ")Return Type is Always a String: No matter what the user types (number, text, etc.), the value returned by
input()is always of type string (str). So if you want another data type, like an integer or a float, you need to convert it explicitly.Type Conversion Example: To convert the string returned by
input()into an integer, useint()like this:x = input("Enter an integer number: ") x = int(x) # Converts string to integerAssigning Input to Variables: The value returned by
input()is typically stored in a variable, sinceinput()acts like an expression that returns a value.Example:
age = input("Enter your age: ")
Here’s a clear and simple example of a Python program that uses input() to accept the radius of a circle from the user, and print() to display the area and circumference:
# Accept radius from the user
radius = float(input("Enter the radius of the circle: "))
# Calculate area and circumference
area = 3.1416 * radius * radius
circumference = 2 * 3.1416 * radius
# Display the results
print("Area of the circle:", area)
print("Circumference of the circle:", circumference)
Explanation:
input()reads data as a string from the keyboard.float()converts the input string into a floating-point number so we can do math.- The program calculates:
- Area =
- Circumference =
print()outputs the calculated values on the screen.