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!
  • 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:
    1. Open IDLE.
    2. Click File → New File to open the Text Editor.
    3. Type your code in the new window.
    4. Save the file with a .py extension (e.g., circle_area.py).
  • To run the script:
    1. Go to Run → Run Module.
    2. The output appears in the Interactive Interpreter window (Python Shell).
  • 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)
  • 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:
    1. Must start with a letter or underscore (_)
    2. Remaining characters can be letters, numbers, or underscores
    3. Cannot be a Python keyword (e.g., if, while, def, etc.)
    4. Case-sensitive (x and X are different)
  • Best Practice: Use self-descriptive identifiers (e.g., student_age instead of x) 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:
    1. int → whole numbers (e.g., x = 10)
    2. float → decimal numbers (e.g., pi = 3.14)
    3. str → strings or text (e.g., name = "Alice")
    4. 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'>

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, x is an integer, and y is a float.
    • Python automatically converts x to float before performing the addition.
    • The result z becomes a float to maintain precision.
Explicit Type Conversion (Type Casting)
  • Definition: Done manually by the programmer using built-in functions.
  • Functions Used:
    • int() – converts to integer
    • float() – converts to floating-point number
    • str() – 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 a TypeError because 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 integer 10, allowing the addition to proceed correctly.
Summary Table
Conversion TypeDone ByExampleResult Type
ImplicitPython5 + 2.0 → 7.0float
ExplicitProgrammerint("10") + 5 → 15int

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:
  1. Assignment Statement
    • Assigns a value to a variable.
    • Example:
      python x = 10
  2. Print Statement
    • Displays the value or result on the screen.
    • Example:
      python print("Hello, world!")
  3. 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)

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 + 3 is the expression (evaluates to 8)
  • a = 5 + 3 is the statement (assigns 8 to a)

Summary Table

ConceptDescriptionExample
StatementCommand Python executesx = 10
ExpressionProduces a value5 + 3, "Hi" + "There"
If StatementMakes a decisionif x > 5:
While LoopRepeats while condition is truewhile x < 10:
For LoopRepeats a block of codefor 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, use int() like this:

    x = input("Enter an integer number: ")
    x = int(x) # Converts string to integer
    
  • Assigning Input to Variables: The value returned by input() is typically stored in a variable, since input() 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 = π×radius2π \times radius^2
    • Circumference = 2×π×radius2 \times π \times radius
  • print() outputs the calculated values on the screen.