Chapitre 10
Implementing algorithms using a programming language
Lecture : 39 minQuiz de 16 questions
# Implementing algorithms using a programming language
## Introduction to programming
### 1. Introduction
Welcome to the exciting world of programming! In this lesson, we will begin our journey into understanding how computers work and, more importantly, how we can give them instructions. Programming is like learning a new language, but instead of talking to another person, you're talking to a computer. It's how we create everything from simple apps to complex websites and even video games. By the end of this lesson, you'll have a basic understanding of what programming is, why it's important, and some fundamental concepts.
### 2. Key Concepts
#### What is Programming?
Programming is the process of writing instructions that a computer can understand and follow to perform a specific task. These instructions are called **code**, and they are written in a specific **programming language**. Think of it as writing a detailed recipe for a computer to follow, step by step.
#### Why Learn Programming?
Learning to program offers many benefits:
* **Problem-Solving Skills:** Programming teaches you to break down complex problems into smaller, manageable steps.
* **Automation:** You can create programs to automate repetitive tasks, saving time and effort.
* **Creativity:** You can bring your ideas to life by building your own applications, games, or websites.
* **Career Opportunities:** Programming is a highly demanded skill in various industries today.
* **Understanding Technology:** It helps you understand how the digital world around us operates.
#### Programming Languages
A **programming language** is a set of rules and symbols used to write computer programs. Just like human languages, there are many different programming languages, each with its strengths and common uses. Some popular examples include:
* **Python:** Known for its simplicity and readability, great for beginners, used in web development, data science, AI.
* **Java:** Used for Android app development, enterprise-level systems.
* **C++:** Used for game development, operating systems, high-performance applications.
* **JavaScript:** Primarily used for making websites interactive.
In our examples, we will often use Python because it's very beginner-friendly.
##### Syntax
Every programming language has its own set of rules called **syntax**. Syntax dictates how words, symbols, and punctuation should be arranged to form valid instructions. If you break the syntax rules, the computer won't understand your instructions, similar to how incorrect grammar can make a human sentence confusing.
##### Keywords
**Keywords** are special words reserved by a programming language that have a specific meaning and purpose. You cannot use keywords for your own purposes, like naming a variable. Examples in Python include `if`, `else`, `for`, `while`, `print`, `input`.
##### Variables
A **variable** is like a labelled box in the computer's memory where you can store data. You give the box a name, and you can put different values inside it. The value stored in a variable can change (vary) as the program runs.
Example in Python:
`name = "Ali"`
`age = 15`
`score = 95.5`
##### Data Types
**Data types** classify the kind of value a variable can hold. Knowing the data type helps the computer understand how to handle the data. Common data types include:
* **Integer (`int`):** Whole numbers (e.g., \( 5 \), \( -12 \), \( 100 \)).
* **Float (`float`):** Numbers with decimal points (e.g., \( 3.14 \), \( 0.5 \), \( -9.9 \)).
* **String (`str`):** Text, enclosed in single or double quotes (e.g., `"Hello World"`, `'Python'`).
* **Boolean (`bool`):** Represents truth values, either `True` or `False`.
##### Operators
**Operators** are special symbols that perform operations on values and variables.
* **Arithmetic Operators:** Used for mathematical calculations.
* `+` (Addition): \( 5 + 3 = 8 \)
* `-` (Subtraction): \( 10 - 4 = 6 \)
* `*` (Multiplication): \( 2 * 6 = 12 \)
* `/` (Division): \( 10 / 2 = 5 \)
* `%` (Modulus - gives the remainder of a division): \( 10 \% 3 = 1 \)
* `**` (Exponentiation - raises to the power of): \( 2 \text{**} 3 = 8 \) (which is \( 2^3 \))
* **Comparison Operators:** Used to compare two values, resulting in a `True` or `False` (Boolean) value.
* `==` (Equal to): \( 5 == 5 \) is `True`
* `!=` (Not equal to): \( 5 != 3 \) is `True`
* `<` (Less than): \( 7 < 10 \) is `True`
* `>` (Greater than): \( 12 > 8 \) is `True`
* `<=` (Less than or equal to): \( 5 <= 5 \) is `True`
* `>=` (Greater than or equal to): \( 10 >= 7 \) is `True`
* **Logical Operators:** Used to combine conditional statements.
* `and`: `True` if both conditions are `True`.
* `or`: `True` if at least one condition is `True`.
* `not`: Reverses the logical state of its operand.
##### Control Structures
Control structures dictate the order in which instructions are executed in a program. They allow programs to make decisions and repeat actions.
* **Sequential:** Instructions are executed one after another, in the order they are written. This is the simplest flow.
* **Selection (Conditional Statements):** Allows the program to make decisions and execute different blocks of code based on whether a certain condition is `True` or `False`. The most common are `if`, `else if` (or `elif` in Python), and `else` statements.
* **Iteration (Loops):** Allows a block of code to be repeated multiple times. This is useful for tasks that need to be performed over and over. Common loops are `for` loops and `while` loops.
#### Algorithms
Before you write any code, you need an **algorithm**. An algorithm is a step-by-step set of instructions for solving a problem or accomplishing a task. It's the logic behind your program. For example, a recipe for baking a cake is an algorithm. Once you have a clear algorithm, you can then translate it into a specific programming language.
### 3. Vocabulary
* **Programming:** The process of creating instructions for a computer to follow.
* **Programming Language:** A formal language with specific rules used to write computer programs.
* **Code:** The set of instructions written in a programming language.
* **Syntax:** The set of rules that define how code must be written for a language.
* **Variable:** A named storage location in a computer's memory that holds data.
* **Data Type:** A classification of data that specifies what kind of value a variable can hold (e.g., integer, string).
* **Operator:** A symbol that represents an operation to be performed (e.g., addition, comparison).
* **Algorithm:** A step-by-step procedure or formula for solving a problem.
* **Bug:** An error or flaw in a computer program that causes it to produce an incorrect or unexpected result.
* **Debugging:** The process of finding and fixing errors (bugs) in code.
### 4. Examples
Here are some simple Python code examples to illustrate the concepts we've discussed:
#### Example 1: Variables and Basic Arithmetic
```python
# This is a comment - comments are ignored by the computer
# They are used to explain your code to humans
# Declare variables and assign values
student_name = "Sarah"
math_score = 85
science_score = 90
# Calculate the average score using arithmetic operators
total_score = math_score + science_score
average_score = total_score / 2
# Print the results to the console
print("Student Name: " + student_name)
print("Math Score: " + str(math_score)) # Convert int to str for printing
print("Science Score: " + str(science_score))
print("Average Score: " + str(average_score))
```
#### Example 2: Using Conditional Statements (if-elif-else)
```python
# This program checks if a student passed based on their average score
average_score = 72.5 # Let's use the average from the previous example
if average_score >= 80:
print("Excellent! You got a Grade A.")
elif average_score >= 60: # else if average_score is 60 or more
print("Good! You got a Grade B.")
elif average_score >= 40: # else if average_score is 40 or more
print("You passed with a Grade C.")
else:
print("You need to improve. Grade D.")
```
#### Example 3: Using Loops (for loop)
```python
# This program prints numbers from 1 to 5 using a for loop
for number in range(1, 6): # range(1, 6) generates numbers 1, 2, 3, 4, 5
print(number)
print("Countdown:")
for i in range(5, 0, -1): # range(start, stop, step) - counts down from 5 to 1
print(i)
print("Lift off!")
```
### 5. Exercises
Answer the following questions to test your understanding:
1. In your own words, explain the difference between an **algorithm** and a **program**.
2. Identify three different **data types** and provide a real-world example of information that would be stored using each type.
3. What would be the output of the following Python code snippets?
a. `result = (15 / 4) + 2`
`print(result)`
b. `x = 10`
`y = 20`
`print(x > y and x != y)`
c. `message = "Python is fun"`
`print(message + "!")`
4. Write a simple Python `if-else` statement that checks if a variable `temperature` (assume it's an integer) is greater than `25`. If it is, print "It's hot!"; otherwise, print "It's not too hot."
5. Write a `for` loop in Python that prints the even numbers from `2` to `10` (inclusive).
### 6. Assignment
Complete the following tasks and submit your work:
1. **Research and Describe:** Choose two different programming languages (other than Python) and for each, describe:
* Its name.
* What it is commonly used for.
* One distinguishing feature (e.g., speed, ease of use, type of applications).
2. **Greeting Program:** Write a Python program that asks the user for their name and then prints a personalized greeting message. For example, if the user enters "David", the program should print "Hello, David! Welcome to programming."
* *(Hint: Use the `input("What is your name? ")` function to get input from the user.)*
3. **Area Calculator:** Write a Python program that calculates the area of a rectangle. Your program should:
* Ask the user to enter the `length` of the rectangle.
* Ask the user to enter the `width` of the rectangle.
* Calculate the `area` (Area \( = \) Length \( \times \) Width).
* Print the calculated `area` to the user.
* *(Remember to convert input from string to a number using `float()` or `int()` if needed.)*
4. **Define and Exemplify:** Explain what `syntax` means in programming and provide a small example of a **syntax error** you might encounter (you can make one up) and how to correct it.
### 7. Summary
In this lesson, we introduced the fundamental concepts of programming. We learned that programming is about giving step-by-step instructions to computers using a specific **programming language**. Key takeaways include:
* **Algorithms** are the logical steps to solve a problem, and **programs** are their implementation in code.
* **Syntax** defines the rules for writing code, while **keywords** are reserved words with special meanings.
* **Variables** are used to store different types of **data** (like integers, floats, strings, booleans).
* **Operators** perform actions on data, from arithmetic to comparisons and logical operations.
* **Control structures** like sequential flow, **selection** (if-else), and **iteration** (loops) manage how a program executes instructions.
Understanding these basics is crucial as you continue to explore the exciting journey of computer science and learn to build powerful applications.
## Write, compile and execute a program 1 (python)
### Introduction
Welcome to your first step into the exciting world of programming with Python! In this lesson, you will learn the fundamental process of creating a simple computer program. We'll cover how to write your instructions, what happens when a computer reads them, and how to see the results of your work. By the end of this lesson, you'll be able to write, save, and run your very own Python program.
### Key Concepts
#### What is a Program?
A computer program is essentially a set of step-by-step instructions that tells a computer what to do. Think of it like a recipe for a computer: you provide specific instructions, and the computer follows them precisely to achieve a particular task or solve a problem. These instructions are written in a special language that computers can understand.
#### What is a Programming Language? (Introducing Python)
A programming language is a formal language that allows us to communicate instructions to a computer. Just like humans use languages like English or Swahili, computers have their own languages. There are many programming languages, such as Java, C++, JavaScript, and Python.
Python is one of the most popular and easiest programming languages to learn. It is known for its clear, readable syntax, which makes it an excellent choice for beginners. Python is used in many areas, including web development, data science, artificial intelligence, and more.
#### Writing Python Code
To write Python code, you typically use a text editor or an Integrated Development Environment (IDE). An IDE, like Python's built-in IDLE, provides a complete environment to write, run, and debug your code.
When you write Python code:
* Each instruction is usually on a new line.
* You save your code in a file with a `.py` extension (e.g., `my_program.py`). This extension tells the computer that it's a Python script.
#### Executing Python Code: The Interpreter
Unlike some programming languages that are 'compiled' into a separate machine-readable file before running, Python is an *interpreted* language. This means:
* **Python Interpreter:** A special program called the Python interpreter reads your `.py` file line by line.
* **Execution:** As the interpreter reads each line, it translates it into machine instructions and executes it immediately.
* There is no separate 'compilation' step that you, as the programmer, directly manage before running the code.
##### How to Run a Python Program:
1. **Using IDLE (Python's IDE):** You can open your `.py` file in IDLE and press F5 or go to `Run > Run Module`.
2. **Using the Command Line (Terminal):** Open your command prompt (Windows) or terminal (macOS/Linux), navigate to the folder where your `.py` file is saved, and type: `python your_program_name.py` and press Enter.
#### Outputting Information: The `print()` Function
One of the most common things a program does is display information to the user. In Python, we use the `print()` function for this.
* The `print()` function takes whatever you put inside its parentheses `()` and displays it on the screen (usually the console or terminal).
* If you want to display text, you must enclose it in single quotes (`'...'`) or double quotes (`"..."`). These are called **strings**.
#### Comments in Python
Comments are notes within your code that are intended for humans reading the code, not for the computer. The Python interpreter completely ignores comments.
* They start with a hash symbol (`#`).
* They are essential for explaining what your code does, making it easier for you and others to understand later.
### Vocabulary
* **Program:** A set of instructions given to a computer to perform a specific task.
* **Algorithm:** A step-by-step procedure or formula for solving a problem or achieving a specific task.
* **Programming Language:** A formal language used to write instructions that a computer can understand and execute.
* **Python:** A popular, high-level, interpreted programming language known for its readability and versatility.
* **Interpreter:** A program that directly executes instructions written in a programming language, line by line, without requiring them to be compiled into a machine-language program first.
* **Syntax:** The set of rules that defines how programs should be written in a particular programming language.
* **Execute:** To carry out an instruction or run a program.
* **Code:** The instructions written in a programming language.
* **Script:** Another term for a program, often referring to a relatively simple program written in an interpreted language like Python.
* **`print()` function:** A built-in Python function used to display output (text, numbers, etc.) to the console.
* **Comment:** Non-executable text in a program, marked with `#`, used by programmers to explain parts of the code.
### Examples
#### Example 1: Your First Program - "Hello, World!"
Let's write a simple program that displays a greeting message.
```python
# This is our very first Python program!
# It will print a greeting message to the console.
print("Hello, Form Three Students!")
print("Welcome to Computer Science with Python.")
```
**How to run it:**
1. Open a text editor (like Notepad, VS Code, or Python IDLE).
2. Type the code exactly as shown above.
3. Save the file as `hello.py` in a folder you can easily find (e.g., `C:\PythonPrograms`).
4. Open your command line/terminal, navigate to that folder (e.g., type `cd C:\PythonPrograms`).
5. Run the program by typing `python hello.py` and pressing Enter.
**Expected Output:**
```
Hello, Form Three Students!
Welcome to Computer Science with Python.
```
#### Example 2: Simple Arithmetic
This program performs a basic calculation and prints the result.
```python
# This program calculates the sum of two numbers.
# First number
number1 = 15
# Second number
number2 = 25
# Calculate the sum
sum_result = number1 + number2
# Print the result
print("The first number is:", number1)
print("The second number is:", number2)
print("The sum of the two numbers is:", sum_result)
```
**Explanation:**
* `number1 = 15` and `number2 = 25` are examples of **variables**. Variables are like containers that hold data. Here, `number1` holds the value 15, and `number2` holds 25.
* `sum_result = number1 + number2` calculates the sum and stores it in a new variable called `sum_result`.
* The `print()` statements now display not just text, but also the values stored in our variables.
### Exercises
1. **Greeting Program:** Write a Python program that prints your name and your favourite hobby on separate lines. Remember to save it as a `.py` file and run it.
2. **Multiplication:** Create a Python program that calculates the product of 8 and 15. Print the two numbers and their product, similar to Example 2.
3. **Code Comments:** Take your program from Exercise 2 and add comments to explain what each line of code does. For instance, `# This line declares the first number.`
### Assignment
1. **Research:** Briefly explain two advantages of using Python for programming compared to other programming languages you might know or have heard about.
2. **Creative Program:** Write a Python program that:
* Prints a friendly message to a friend or family member (e.g., "Hi [Friend's Name], hope you're having a good day!").
* Calculates the result of \( (100 - 45) \times 2 \)..
* Prints the calculated result clearly labeled (e.g., "The result of the calculation is: [result]").
* Includes at least three meaningful comments throughout your code to explain different sections.
3. **Explain:** In your own words, describe what the Python **interpreter** does when you run a Python script.
### Summary
Today, you've taken a significant step into computer programming. We learned that a program is a set of instructions for a computer, and Python is a powerful yet easy-to-read language for writing these instructions. You discovered how to write simple Python code in a `.py` file and how the Python interpreter executes it line by line. The `print()` function is essential for displaying output, and comments (`#`) are vital for making your code understandable to humans. Keep practicing, and you'll soon be writing more complex and exciting programs!
## Write, compile and execute a program 2 (Python)
### Introduction
Welcome to our second lesson on writing, compiling, and executing programs, this time focusing on **Python**. Python is one of the most popular and versatile programming languages in the world. It's known for its clear syntax and readability, making it an excellent choice for learning how to implement algorithms. In this lesson, we will explore how to write Python code, understand its execution process, and run your first programs.
### Key Concepts
#### What is Python?
* **High-Level Language:** Python is considered a high-level programming language, meaning it's designed to be easier for humans to read and write than low-level languages like assembly code. It handles many complex tasks automatically, allowing you to focus on the logic of your program.
* **Interpreted Language:** This is a crucial distinction. Unlike *compiled languages* (like C++ or Java) that require a separate step to convert your entire source code into machine code (an executable file) before running, Python is an *interpreted language*. The **Python interpreter** reads and executes your code line by line directly.
* While Python does internally convert your code into an intermediate format called **bytecode** (often stored in `.pyc` files) for efficiency, this process happens automatically and is managed by the interpreter. As a programmer, you generally don't perform an explicit "compilation" step in the same way you would with a compiled language.
* **Versatile:** Python is used for web development, data analysis, artificial intelligence, scientific computing, automation, and much more.
#### Setting up Your Python Environment
To write and run Python code, you need a Python interpreter installed on your computer and a text editor or an Integrated Development Environment (IDE).
* **Python Installation:** Most modern operating systems might come with Python pre-installed, or you can download it from the official Python website (python.org).
* **Text Editor/IDE:**
* **IDLE:** Python usually comes with its own simple IDE called IDLE, which is great for beginners.
* **Other Editors:** Popular text editors like Visual Studio Code, Sublime Text, or Atom can be configured to write and run Python.
* **Online IDEs:** Websites like Replit or Google Colab allow you to write and run Python code directly in your browser without any installation.
#### Writing Your First Python Program
Python's syntax is quite straightforward. Let's look at some basics:
* **Comments:** Lines starting with a `#` are comments. They are ignored by the interpreter and are used to explain your code to humans.
```python
# This is a single-line comment
print("Hello, World!") # This comment explains the line of code
```
* **`print()` Function:** This function is used to display output on the screen.
```python
print("Hello, Computer Science Students!")
print(123 + 456)
```
* **Variables:** Variables are used to store data. You give them a name, and Python automatically determines their type.
```python
name = "Alice"
age = 15
height = 1.65
is_student = True
print("Name:", name)
print("Age:", age)
```
#### Executing Python Programs
There are two main ways to execute Python code:
* **Interactive Shell (REPL):**
* When you open IDLE or type `python` in your command prompt/terminal, you enter the interactive shell (Read-Eval-Print Loop).
* You can type Python commands directly, and the interpreter will execute them immediately and show the result.
```
>>> print("Hello")
Hello
>>> 5 + 3
8
```
* **Running a Script File (.py):**
* You write your Python code in a text file and save it with a `.py` extension (e.g., `my_program.py`).
* You can run this script from the command prompt/terminal by navigating to the directory where your file is saved and typing: `python my_program.py`.
* In an IDE like IDLE, you typically click a "Run" button or use a menu option to execute the current script.
#### Basic Debugging
Debugging is the process of finding and fixing errors in your code.
* **Syntax Errors:** These occur when you break the rules of Python's grammar (e.g., misspelling `print`, forgetting a quotation mark). The interpreter will stop and tell you where the error is.
```python
prnt("Hello") # SyntaxError: name 'prnt' is not defined
```
* **Runtime Errors:** These errors occur while the program is running, even if the syntax is correct (e.g., trying to divide by zero, or accessing a variable that doesn't exist yet).
* **Using `print()` for Debugging:** A common and simple way to debug is to strategically add `print()` statements to your code to display the values of variables at different points. This helps you understand what your program is doing step-by-step.
### Vocabulary
* **Python:** A popular high-level, interpreted programming language known for its readability.
* **Interpreter:** A program that directly executes instructions written in a programming language, translating them line by line without requiring prior compilation into machine code.
* **IDE (Integrated Development Environment):** A software application that provides comprehensive facilities for programmers, such as a code editor, debugger, and often an interpreter/compiler.
* **Syntax:** The set of rules that defines how a program written in a particular language should be structured.
* **Runtime Error:** An error that occurs while a program is running, often due to unexpected conditions or logical flaws.
* **Syntax Error:** An error that occurs when the rules of the programming language's grammar are not followed, preventing the program from starting.
* **Debugging:** The process of finding and fixing errors (bugs) in computer programs.
* **Variable:** A named storage location in a program that holds a value, which can change during program execution.
* **String:** A sequence of characters, used to represent text (e.g., "Hello").
* **Integer:** A whole number (positive, negative, or zero) without a fractional part (e.g., 5, -10).
* **Float:** A number with a decimal point or fractional part (e.g., 3.14, -0.5).
* **Comment:** Text within a program that is ignored by the interpreter and is used to provide explanations for humans.
### Examples
#### Example 1: Simple Output
```python
# This program displays a greeting
print("Welcome to Python programming!")
print("It's exciting to learn!")
```
#### Example 2: Using Variables and Basic Arithmetic
```python
# This program calculates the sum of two numbers
num1 = 10
num2 = 25
sum_result = num1 + num2
print("The first number is:", num1)
print("The second number is:", num2)
print("Their sum is:", sum_result)
```
#### Example 3: Getting User Input
```python
# This program asks for the user's name and greets them
name = input("What is your name? ")
print("Hello,", name + "! Nice to meet you.")
```
### Exercises
1. **Print Your Favorite:** Write a Python program that prints your full name on one line and your favorite subject on the next line.
2. **Product of Numbers:** Write a Python program that takes two numbers as input (you can hardcode them for now, like `x = 7`, `y = 3`) and calculates and prints their product.
3. **Identify the Error:** Look at the following Python code snippet. Identify the error and explain what type of error it is (syntax or runtime).
```python
message = "Python is fun!
print(message)
```
4. **Area of a Triangle:** Write a Python program that calculates the area of a triangle. Assume the base is 10 and the height is 5. Recall the formula for the area of a triangle: \( A = \frac{1}{2} \times \text{base} \times \text{height} \).
### Assignment
1. **Temperature Converter:** Write a Python program that converts a temperature from Celsius to Fahrenheit. The program should:
* Store a temperature in Celsius (e.g., `celsius = 25`).
* Use the formula: \[ F = C \times 1.8 + 32 \]
* Print the original Celsius temperature and the calculated Fahrenheit temperature in a clear message.
2. **Age in Days:** Write a Python program that asks the user for their age in years (e.g., "How old are you?") and then estimates and prints their age in days. (Assume 365 days in a year for simplicity).
3. **Research IDEs:** Research and list three other common IDEs or code editors (apart from IDLE) that are widely used for Python programming. Briefly describe one feature you find interesting about each.
### Summary
In this lesson, you've taken a significant step into the world of Python programming. We learned that Python is an **interpreted, high-level language** praised for its simplicity. You now understand the basic process of **writing code** using `print()` and variables, and how to **execute** it either through an interactive shell or by running a script file. We also touched upon the basics of **debugging** to help you fix common errors. Python's straightforward nature makes it an excellent tool for implementing the algorithms you design, bringing your computational ideas to life. Keep practicing, and you'll become proficient in no time!
## Write, compile and execute a program 3 (Python)
### Introduction
Welcome to this lesson on implementing algorithms using Python! In the previous lessons, you learned about algorithms and how to represent them. Now, we will take the exciting step of bringing those algorithms to life by writing, saving, and executing programs using Python, one of the most popular and beginner-friendly programming languages.
### Key Concepts
#### Understanding Python
* **What is Python?** Python is a high-level, interpreted programming language. This means it's designed to be easy for humans to read and write (high-level), and it uses an "interpreter" to run code directly, rather than needing a separate "compiler" step like some other languages.
* **Why Python?**
* **Readability:** Python's syntax is very clear and easy to understand, making it great for beginners.
* **Versatility:** It can be used for many types of applications, including web development, data analysis, artificial intelligence, and more.
* **Large Community:** There are many resources and a supportive community to help you learn and solve problems.
#### Writing Python Code
* **Basic Syntax Rules:**
* Unlike some languages, Python usually does not use semicolons (`;`) at the end of each line.
* **Indentation Matters!** This is one of Python's most unique features. Instead of using curly braces `{}` to define blocks of code (like loops or functions), Python uses **indentation** (spaces or tabs). Consistent indentation is crucial for your program to work correctly.
* **Comments:** To add notes to your code that the interpreter will ignore, use the hash symbol (`#`). Anything after `#` on that line is a comment. Example: `# This is a comment`
* **Variables:** Variables are like containers that hold data. You give them a name, and you can store different types of information in them.
* **Declaration and Assignment:** You create a variable and give it a value using the assignment operator (`=`).
```python
name = "Alice" # Stores the text "Alice"
age = 15 # Stores the number 15
is_student = True # Stores a true/false value
```
* **Data Types (Briefly):** Python automatically figures out the type of data you store, such as `string` (text), `integer` (whole numbers), `float` (decimal numbers), or `boolean` (True/False).
* **Outputting Information: The `print()` Function:**
* The `print()` function is used to display output on the console (your screen).
* You can print text, variables, or a combination.
```python
print("Hello, World!")
print(name)
print("My name is", name, "and I am", age, "years old.")
```
#### Saving a Python Program
* When you write Python code, you save it in a file with the **`.py`** extension (e.g., `my_program.py`, `hello.py`).
* Choose meaningful filenames that describe what the program does.
#### Executing a Python Program
Python programs are executed by the Python **interpreter**.
* **The Python Interpreter:** This is a special program that reads your Python code and translates it into instructions that the computer can understand and execute directly, line by line.
* **Interactive Mode (REPL - Read-Eval-Print Loop):**
* You can open the Python interpreter directly from your computer's terminal or command prompt by typing `python` or `python3`.
* In interactive mode, you type Python commands one at a time, and the interpreter executes them immediately and shows you the result.
* This is great for testing small snippets of code or experimenting.
* **Script Mode:**
* This is how you run a complete Python program that you have saved in a `.py` file.
* You open your terminal or command prompt, navigate to the folder where you saved your file, and type: `python your_program_name.py` (e.g., `python hello.py`).
* The interpreter will read the entire file and execute all the commands in sequence.
* **Integrated Development Environments (IDEs):** Tools like IDLE (which often comes with Python), Visual Studio Code, or PyCharm provide a comprehensive environment to write, debug, and run your Python code, simplifying the process.
#### Common Errors
When you write programs, errors are a natural part of the process. Learning to identify and fix them is key.
* **Syntax Errors:** These occur when your code violates the grammatical rules (syntax) of the Python language (e.g., forgetting a closing parenthesis, incorrect indentation). The interpreter usually catches these before running the program and tells you where the error is.
* **Runtime Errors (Exceptions):** These errors occur *while* your program is running. The syntax might be correct, but something unexpected happens during execution (e.g., trying to divide a number by zero, trying to use a variable that hasn't been defined yet).
### Vocabulary
* **Python:** A high-level, interpreted programming language known for its readability and versatility.
* **Interpreter:** A program that directly executes instructions written in a programming language, line by line, without requiring prior compilation.
* **Script:** A file containing a sequence of instructions (code) written in a programming language, intended to be executed by an interpreter.
* **Syntax:** The set of rules that defines how a program written in a programming language must be structured to be valid.
* **Variable:** A named storage location in a computer's memory used to hold data that can change during program execution.
* **`print()` function:** A built-in Python function used to display output (text, numbers, variable values) on the console.
* **Indentation:** The spacing at the beginning of a line of code, which is crucial in Python for defining code blocks.
* **Interactive Mode (REPL):** A mode of the Python interpreter where commands are executed one at a time, providing immediate feedback.
* **Script Mode:** The method of running an entire Python program from a saved `.py` file.
* **Syntax Error:** An error in the structure or grammar of the code, preventing it from being executed.
* **Runtime Error (Exception):** An error that occurs during the execution of a program, even if its syntax is correct.
### Examples
#### Example 1: "Hello World" Program
This program simply prints a greeting to the screen.
1. **Write the code:** Open a text editor (like Notepad, VS Code, or IDLE) and type:
```python
print("Hello, Form Three Students!")
```
2. **Save the file:** Save it as `hello.py` in a folder you can easily find (e.g., `C:\PythonPrograms` or `~/Documents/Python`).
3. **Execute the program:**
* Open your computer's terminal or command prompt.
* Navigate to the folder where you saved `hello.py` (e.g., `cd C:\PythonPrograms` or `cd ~/Documents/Python`).
* Type: `python hello.py`
* You should see: `Hello, Form Three Students!` displayed.
#### Example 2: Using Variables and Basic Arithmetic
This program demonstrates storing values in variables and performing a simple calculation.
1. **Write the code:** Create a new file called `calculations.py` and type:
```python
num1 = 25
num2 = 7
# Perform operations
sum_result = num1 + num2
difference_result = num1 - num2
product_result = num1 * num2
quotient_result = num1 / num2 # Division results in a float
# Print the results
print("First number:", num1)
print("Second number:", num2)
print("Sum:", sum_result)
print("Difference:", difference_result)
print("Product:", product_result)
print("Quotient:", quotient_result)
```
2. **Save the file:** Save it as `calculations.py`.
3. **Execute the program:** Run it from your terminal: `python calculations.py`
* You will see the values of the numbers and the results of the operations printed.
### Exercises
1. **Personal Greeting Program:** Write a Python program that asks for the user's name and then prints a personalized greeting like: "Hello, [Name]! Welcome to Python programming.".
* *(Hint: Use the `input()` function to get user input, e.g., `name = input("What is your name? ")`)*
2. **Error Identification:** Identify and explain the type of error in the following Python code snippets, and then correct them:
* `print("Python is fun"`
* `x = 10`
`y = z + 5`
3. **Mode Comparison:** Explain the main difference between using Python in **interactive mode** and **script mode**. When might you choose to use one over the other?
4. **File Extension Purpose:** What is the significance of using the `.py` file extension for Python programs?
### Assignment
1. **My Profile Program:** Create a Python program named `my_profile.py`. In this program:
* Create variables to store your full name, age, and favorite subject.
* Print all this information in a friendly, formatted sentence. For example: "Hello! My name is [Your Name], I am [Your Age] years old, and my favorite subject is [Your Favorite Subject]."
* Make sure to include comments in your code explaining what each part does.
2. **Interactive Experimentation:** Open the Python interactive shell (by typing `python` in your terminal). Try the following:
* Declare a variable `my_number = 42` and then print its value.
* Perform a simple calculation like `15 * 3` and see the immediate result.
* Try to print a variable that you haven't defined yet (e.g., `print(unknown_var)`) and observe the error message.
3. **Research Python Advantages:** Research and write a short paragraph (3-5 sentences) describing two advantages of using Python for programming, specifically mentioning why it's a good choice for beginners or for specific types of projects.
### Summary
In this lesson, you have learned the fundamental steps to write, save, and execute Python programs. We explored Python's key characteristics as an interpreted, high-level language, and understood its basic syntax, including the importance of indentation and the use of the `print()` function. You now know how to save your code in a `.py` file and run it using the Python interpreter in both interactive and script modes. We also discussed common errors like syntax errors and runtime errors, which are crucial to identify and fix as you develop your programming skills. With these foundational skills, you are well-equipped to start building your own Python programs and bringing your algorithms to life!
## Integration activities
### Introduction
Welcome to our lesson on Integration Activities! In computer science, algorithms are like recipes that tell a computer how to solve a problem. Often, complex problems require multiple steps or even multiple 'mini-recipes' to solve. Integration activities are all about bringing these smaller algorithms or parts of an algorithm together to create a complete, functional program. This skill is crucial for building larger, more efficient, and easier-to-manage software.
### Key Concepts
#### Understanding Algorithm Integration
Integrating algorithms means combining different logical steps or already-defined algorithms into a single, cohesive program. Imagine building a robot: you might have one algorithm for moving forward, another for turning, and another for picking up an object. Integration is the process of putting these together so the robot can perform a sequence of tasks.
* **Why Integrate?**
* **Solve Complex Problems:** Many real-world problems are too big to solve with a single, simple algorithm. Breaking them down and integrating smaller solutions makes them manageable.
* **Modularity:** It allows you to build programs from reusable 'blocks' of code, much like LEGO bricks.
* **Reusability:** A well-designed integrated part can be used in many different programs, saving time and effort.
* **Easier Debugging:** When something goes wrong, it's easier to find the error in a small, self-contained part than in a giant block of code.
#### Modular Programming
Modular programming is a design technique where a program is divided into smaller, independent, and interchangeable units called **modules**. Each module is responsible for a specific function or task.
* **Functions (or Procedures/Methods):** In most programming languages, modules are implemented as functions. A function is a block of code that performs a specific task. You can call this function from different parts of your program.
* **Example (Pseudocode):**
```
FUNCTION greet_user(name):
PRINT "Hello, " + name + "!"
// Main program
START
user_name = INPUT("Enter your name: ")
CALL greet_user(user_name) // Calling the function
END
```
#### Calling Functions and Passing Data
When you integrate algorithms, one common way for them to interact is by calling functions.
* **Calling a Function:** This means executing the code inside that function.
* **Parameters:** These are values you pass into a function. They allow functions to work with different data each time they are called.
* **Return Values:** Functions can also send back a result to the part of the program that called them.
* **Example (Pseudocode for calculating sum):
```
FUNCTION add_numbers(num1, num2): // num1 and num2 are parameters
sum = num1 + num2
RETURN sum // Returning the calculated sum
// Main program
START
x = 10
y = 5
result = CALL add_numbers(x, y) // Calling function, passing x and y
PRINT "The sum is: " + result
END
```
#### Data Flow Between Modules
Understanding how data moves between different parts of your integrated program is vital.
* **Local Variables:** Variables declared inside a function are usually 'local' to that function, meaning they can only be accessed within that function.
* **Global Variables (Briefly):** Variables declared outside of any function are 'global' and can be accessed and modified from anywhere in the program. However, their overuse can make programs harder to debug.
#### Integrating Control Structures
Even when using functions, the fundamental control structures (sequential, selection, iteration) are still essential for controlling the flow of the integrated program.
* **Sequential:** Functions are often called one after another.
* **Selection (IF/ELSE):** You might call different functions based on a condition (e.g., `IF user_choice == 'deposit' THEN CALL deposit_funds()`).
* **Iteration (LOOPS):** You might call a function multiple times within a loop (e.g., `FOR EACH item IN shopping_cart: CALL calculate_item_price(item)`).
#### Debugging Integrated Systems
When multiple functions interact, debugging can become more complex. Strategies include:
* **Print Statements:** Use `PRINT` statements to display the values of variables at different points in your program and inside different functions.
* **Step-by-Step Execution:** Many programming environments allow you to step through your code line by line to see exactly what is happening.
* **Testing Individual Modules:** Ensure each function works correctly on its own before integrating it into a larger system.
### Vocabulary
* **Algorithm Integration:** The process of combining multiple algorithms or distinct parts of an algorithm to create a complete and functional solution.
* **Modular Programming:** A software design technique that involves breaking down a program into smaller, independent, and interchangeable units called modules.
* **Module:** A distinct unit of code (often a function or a set of related functions) that serves a specific purpose within a larger program.
* **Function (Procedure/Method):** A named block of code designed to perform a specific task. It can accept inputs (parameters) and can produce an output (return value).
* **Parameter (Argument):** A value that is passed into a function when it is called, allowing the function to operate on specific data.
* **Return Value:** The result that a function sends back to the part of the program that called it after completing its task.
* **Debugging:** The systematic process of finding and fixing errors (bugs) in a computer program.
* **Local Variable:** A variable declared inside a function, accessible only within that function.
* **Global Variable:** A variable declared outside of any function, accessible from anywhere in the program.
### Examples
#### Example 1: Calculating Student Grade Average
Let's integrate functions to calculate the average grade for a student over several subjects.
```pseudocode
FUNCTION get_score(subject_name):
score = INPUT("Enter score for " + subject_name + ": ")
RETURN score
FUNCTION calculate_average(score1, score2, score3):
total = score1 + score2 + score3
average = total / 3
RETURN average
// Main Program
START
math_score = CALL get_score("Math")
science_score = CALL get_score("Science")
english_score = CALL get_score("English")
student_average = CALL calculate_average(math_score, science_score, english_score)
PRINT "The student's average score is: " + student_average
END
```
**Explanation:**
1. `get_score` is called three times, once for each subject, to get individual scores.
2. These individual scores are then passed as parameters to the `calculate_average` function.
3. `calculate_average` computes the average and returns it.
4. The main program then prints the final average.
#### Example 2: Simple Online Order Processing
Imagine a basic online shopping scenario where a customer adds items and checks out.
```pseudocode
FUNCTION calculate_item_cost(quantity, unit_price):
cost = quantity * unit_price
RETURN cost
FUNCTION apply_discount(total_amount, discount_percentage):
discount_amount = total_amount * (discount_percentage / 100)
final_amount = total_amount - discount_amount
RETURN final_amount
// Main Program
START
num_shirts = 2
shirt_price = 15
num_pants = 1
pants_price = 30
// Calculate cost for each item using a function
shirts_total = CALL calculate_item_cost(num_shirts, shirt_price)
pants_total = CALL calculate_item_cost(num_pants, pants_price)
subtotal = shirts_total + pants_total
PRINT "Subtotal: $" + subtotal
// Apply a discount using another function
discount = 10 // 10% discount
final_bill = CALL apply_discount(subtotal, discount)
PRINT "Final amount after " + discount + "% discount: $" + final_bill
END
```
**Explanation:**
1. The `calculate_item_cost` function is reused for both shirts and pants, demonstrating reusability.
2. The results from these calls are added to get a `subtotal`.
3. This `subtotal` is then passed to the `apply_discount` function to get the `final_bill`.
_Note: This lesson on integrating algorithms does not involve complex mathematical or scientific formulas, so no KaTeX-compatible delimiters are needed for this content._
### Exercises
1. What is modular programming, and why is it considered a good practice in software development?
2. Describe a real-world task (e.g., preparing a meal, cleaning a room) that could be broken down into smaller, interconnected sub-tasks (like functions). Explain how these sub-tasks would be integrated.
3. Write pseudocode for a program that asks the user for two numbers, calculates their product, and then displays the result. Your solution MUST use a function called `multiply_numbers` that takes two parameters and returns their product.
4. Explain the difference between a parameter and a return value in the context of a function call.
### Assignment
**Problem: Simple Calculator Program**
Design an algorithm (using pseudocode or a flowchart) for a simple calculator program that can perform addition, subtraction, multiplication, and division. Your program should be integrated using functions.
Your program should:
* Prompt the user to enter two numbers.
* Prompt the user to choose an operation (e.g., 'add', 'subtract', 'multiply', 'divide').
* Have separate functions for each operation: `add(num1, num2)`, `subtract(num1, num2)`, `multiply(num1, num2)`, `divide(num1, num2)`.
* Call the appropriate function based on the user's choice.
* Display the result.
* Include basic error handling for division by zero (e.g., if the user tries to divide by 0, print an error message instead of calculating).
**Challenge Question:** How would you modify your calculator program to allow the user to perform multiple operations without restarting the program, perhaps by asking if they want to 'continue' after each calculation?
### Summary
Today, we explored the critical concept of integrating algorithms using a programming language. We learned that by breaking down complex problems into smaller, manageable functions (modules) and then combining them, we can build more robust, reusable, and easier-to-debug programs. Understanding how to call functions, pass parameters, and handle return values is fundamental to creating efficient and well-structured software. Mastering integration activities will enable you to tackle more challenging programming tasks and build sophisticated applications.
Quiz du chapitre
16 questions — vérifie chaque réponse pour voir l'explication.