Chapitre 10
Writing of source code
Lecture : 41 minQuiz de 16 questions
# Writing of source code
## Introduction to coding (Python)
### Introduction
Welcome to the exciting world of computer programming! In this lesson, we will begin our journey into writing source code, specifically using Python. Coding is like giving instructions to a computer in a language it understands. These instructions tell the computer exactly what to do, step by step. Python is an excellent language for beginners because of its simple syntax and wide range of applications, from web development to artificial intelligence.
### Key Concepts
#### What is Coding?
Coding, also known as programming, is the process of creating a set of instructions that computers follow to perform specific tasks. These instructions are written in a specific programming language, which is then translated into a form the computer can understand and execute.
#### Why Python?
Python is one of the most popular programming languages today. Here's why it's a great choice for beginners:
* **Simple Syntax:** Python's structure is very similar to English, making it easier to read and write compared to other languages.
* **Versatile:** It's used in many fields, including web development, data science, artificial intelligence, scientific computing, and more.
* **Large Community:** There's a vast community of Python users, meaning lots of resources, libraries, and support available.
* **Cross-platform:** Python code can run on different operating systems (Windows, macOS, Linux) without significant changes.
#### Basic Python Syntax
##### 1. Printing Output
The `print()` function is used to display text or variable values on the console.
* **Syntax:** `print("Hello, World!")` or `print(variable_name)`
* **Example:** `print("Welcome to Python!")`
##### 2. Variables
Variables are containers for storing data values. You can think of them as labels you give to data.
* **Naming Rules:**
* Must start with a letter or an underscore (`_`).
* Cannot start with a number.
* Can only contain alpha-numeric characters and underscores (A-z, 0-9, and _).
* Case-sensitive (`age` is different from `Age`).
* Cannot be Python keywords (like `if`, `else`, `while`).
* **Assignment:** Use the `=` operator to assign a value to a variable.
* **Data Types:** Python automatically determines the data type.
* `int`: Whole numbers (e.g., `10`, `-5`)
* `float`: Decimal numbers (e.g., `3.14`, `-0.5`)
* `str`: Text, enclosed in single or double quotes (e.g., `'hello'`, `"Python"`)
* `bool`: Boolean values, either `True` or `False`
* **Example:**
```python
name = "Alice"
age = 16
height = 1.75
is_student = True
```
##### 3. Comments
Comments are notes in your code that are ignored by the Python interpreter. They are used to explain the code and make it more readable for humans.
* **Syntax:** Start with a `#` symbol.
* **Example:** `# This is a single-line comment`
##### 4. Input from User
The `input()` function allows your program to receive data from the user.
* **Syntax:** `variable = input("Prompt for user: ")`
* **Note:** The `input()` function always returns a string. If you need a number, you'll have to convert it (e.g., `int(input("Enter a number: "))`).
* **Example:** `student_name = input("What is your name? ")`
##### 5. Operators
Operators are symbols that perform operations on values and variables.
* **Arithmetic Operators:** `+` (addition), `-` (subtraction), `*` (multiplication), `/` (division), `%` (modulo - remainder), `**` (exponentiation), `//` (floor division).
* **Comparison Operators:** `==` (equal to), `!=` (not equal to), `>` (greater than), `<` (less than), `>=` (greater than or equal to), `<=` (less than or equal to).
* **Logical Operators:** `and`, `or`, `not` (used to combine conditional statements).
##### 6. Conditional Statements (`if`, `elif`, `else`)
These statements allow your program to make decisions and execute different blocks of code based on whether a condition is `True` or `False`.
* **Syntax:**
```python
if condition1:
# code to execute if condition1 is True
elif condition2: # optional
# code to execute if condition1 is False and condition2 is True
else: # optional
# code to execute if all previous conditions are False
```
* **Important:** Python uses **indentation** (spaces or tabs at the beginning of a line) to define code blocks. All lines within the same block must have the same level of indentation.
##### 7. Loops (`for`, `while`)
Loops are used to execute a block of code repeatedly.
* **`for` loop:** Used for iterating over a sequence (like a list, tuple, string, or range).
* **Syntax:**
```python
for item in sequence:
# code to execute for each item
```
* **Example:** `for i in range(5): # range(5) generates numbers 0, 1, 2, 3, 4`
* **`while` loop:** Executes a block of code as long as a condition is `True`.
* **Syntax:**
```python
while condition:
# code to execute repeatedly
# Make sure the condition eventually becomes False to avoid infinite loop
```
### Vocabulary
* **Code/Source Code:** A set of instructions written in a programming language.
* **Syntax:** The set of rules that defines the combinations of symbols that are considered to be correctly structured statements in that language.
* **Variable:** A named storage location in a computer's memory that holds a value.
* **Data Type:** A classification that specifies which type of value a variable has (e.g., integer, string, boolean).
* **Operator:** A symbol or keyword that performs an operation on one or more values or variables.
* **Conditional Statement:** A programming construct that allows code to be executed only if a certain condition is met.
* **Loop:** A programming construct that repeatedly executes a block of code until a certain condition is met or for each item in a sequence.
* **Interpreter:** A program that directly executes instructions written in a programming language, without previously compiling them into a machine-language program.
* **Indentation:** The amount of space at the beginning of a line of code, used in Python to define code blocks.
### Examples
#### Example 1: Basic Output and Variables
```python
# This program greets a user and displays their age
user_name = "Sarah"
user_age = 17
print("Hello, " + user_name + "!")
print("You are " + str(user_age) + " years old.") # Convert int to string for concatenation
print(f"Next year, you will be {user_age + 1} years old.") # F-string for easier formatting
```
#### Example 2: Getting User Input and Simple Calculation
```python
# This program takes two numbers from the user and calculates their sum
num1_str = input("Enter the first number: ")
num2_str = input("Enter the second number: ")
# Convert input strings to integers for calculation
num1 = int(num1_str)
num2 = int(num2_str)
sum_result = num1 + num2
print("The sum of " + str(num1) + " and " + str(num2) + " is: " + str(sum_result))
```
#### Example 3: Conditional Statement (`if-else`)
```python
# This program checks if a student passed or failed based on a score
score = int(input("Enter your test score: "))
if score >= 50:
print("Congratulations! You passed the test.")
else:
print("Sorry, you did not pass. Please try again.")
```
#### Example 4: `for` Loop
```python
# This program prints numbers from 1 to 5 using a for loop
print("Counting from 1 to 5:")
for i in range(1, 6): # range(start, stop) - stop is exclusive
print(i)
```
#### Example 5: `while` Loop
```python
# This program counts down from 3 to 1 using a while loop
count = 3
while count > 0:
print(count)
count = count - 1 # Decrement the count
print("Lift off!")
```
### Exercises
1. **Greetings Program:** Write a Python program that asks the user for their name and then prints a personalized greeting, e.g., "Hello, [Name]! Welcome to Python programming."
2. **Age Calculator:** Ask the user for their birth year and the current year. Calculate and print their current age.
3. **Basic Arithmetic:** Ask the user to enter two numbers. Then, print their product and their difference.
4. **Even or Odd:** Write a program that takes an integer as input and prints whether the number is "Even" or "Odd".
5. **Repeated Message:** Use a `for` loop to print the message "Python is fun!" five times.
### Assignment
1. **Student Grade Calculator:**
Write a Python program that asks for a student's name and three test scores (out of 100). Calculate the average score and then print the student's name and their average score. Additionally, use an `if-elif-else` statement to assign a grade:
* Average >= 80: "A"
* Average >= 70: "B"
* Average >= 60: "C"
* Average >= 50: "D"
* Average < 50: "F"
2. **Temperature Converter:**
Write a program that converts a temperature from Celsius to Fahrenheit. The program should:
* Ask the user to input a temperature in Celsius.
* Apply the conversion formula: \[ F = C \times 1.8 + 32 \]
* Print the result in Fahrenheit.
3. **Password Attempt Counter:**
Write a program that uses a `while` loop to simulate a simple password entry. The program should ask the user to enter a password. If the password is not "secret", it should print "Incorrect password, try again." and ask again. It should allow a maximum of 3 attempts. If the user fails 3 times, print "Account locked.". If they enter the correct password, print "Access granted!" and exit the loop.
### Summary
In this lesson, we've taken our first steps into the world of writing source code using Python. We learned that coding is about giving instructions to computers, and Python's straightforward syntax makes it ideal for beginners. We covered essential concepts such as printing output, storing data in variables with different data types, adding comments, taking input from users, and using various operators. Crucially, we explored how to control the flow of our programs using conditional `if-elif-else` statements and how to repeat actions using `for` and `while` loops. Remember the importance of **indentation** in Python for defining code blocks. With these fundamental building blocks, you're now ready to start creating your own simple Python programs! Keep practicing and experimenting. Happy coding!"
## Coding 1 (Python)
### Introduction
Welcome to your first lesson in Python programming! In this lesson, we will begin our journey into the exciting world of coding using Python, a versatile and beginner-friendly programming language. You will learn the fundamental concepts of writing simple programs, handling data, and making your programs interactive. By the end of this lesson, you will be able to write basic Python scripts to perform calculations and interact with users.
### Key Concepts
#### What is Python?
Python is a high-level, interpreted, general-purpose programming language. It was created by Guido van Rossum and first released in 1991. Python is known for its clear syntax and readability, which makes it an excellent choice for beginners.
#### Why Python?
* **Readability**: Python's syntax is designed to be very readable, similar to English, making it easier to learn and understand.
* **Versatility**: It is used in many different fields, including web development, artificial intelligence, data science, scientific computing, automation, and game development.
* **Large Community**: Python has a huge and active community, which means lots of resources, tutorials, and libraries are available.
* **Cross-platform**: Python programs can run on various operating systems like Windows, macOS, and Linux without needing to be rewritten.
#### Your First Python Program: "Hello, World!"
The traditional first program in any language is "Hello, World!". In Python, it's very simple.
To display text on the screen, we use the `print()` function.
```python
print("Hello, World!")
```
#### Variables and Data Types
##### Variables
A variable is a named storage location used to hold data. Think of it as a container where you can store different types of information. You can change the value stored in a variable during the program's execution.
**Rules for naming variables:**
* Must start with a letter or an underscore (`_`).
* Cannot start with a number.
* Can only contain alpha-numeric characters and underscores (`a-z`, `A-Z`, `0-9`, `_`).
* Variable names are case-sensitive (`age` is different from `Age`).
* Cannot be a Python keyword (e.g., `if`, `else`, `print`).
**Assigning a value to a variable:**
```python
name = "Alice"
score = 100
is_student = True
```
##### Data Types
Python handles different kinds of data. These are called **data types**.
* **`int` (Integer)**: Whole numbers, positive or negative, without decimals. E.g., `5`, `-10`, `0`.
* **`float` (Floating-point Number)**: Numbers with a decimal point. E.g., `3.14`, `-0.5`, `2.0`.
* **`str` (String)**: A sequence of characters, typically used for text. Enclosed in single or double quotes. E.g., `"Hello"`, `'Python is fun'`.
* **`bool` (Boolean)**: Represents one of two values: `True` or `False`. Used for logical operations.
```python
student_name = "John Doe" # String
student_age = 16 # Integer
student_grade = 95.5 # Float
is_enrolled = True # Boolean
print(student_name)
print(student_age)
```
#### Input and Output
##### Output (`print()` function)
We've already seen `print()` to display text. You can also print variables and combine multiple items.
```python
name = "Charlie"
age = 15
print("My name is", name, "and I am", age, "years old.")
# Output: My name is Charlie and I am 15 years old.
print(f"My name is {name} and I am {age} years old.") # f-string for formatted output
# Output: My name is Charlie and I am 15 years old.
```
##### Input (`input()` function)
To make programs interactive, we often need to get information from the user. The `input()` function does this.
**Important**: The `input()` function always reads input as a **string**, even if the user types a number. If you need a number, you must convert it using `int()` or `float()`.
```python
user_name = input("What is your name? ")
print("Hello, " + user_name + "!")
user_age_str = input("How old are you? ")
user_age_int = int(user_age_str) # Convert string to integer
print(f"You are {user_age_int} years old.")
```
#### Comments
Comments are notes in your code that are ignored by the Python interpreter. They are used to explain what the code does, making it easier for you and others to understand.
* **Single-line comments**: Start with a hash symbol (`#`).
```python
# This is a single-line comment
print("Learning Python") # This comment explains the line
```
#### Operators
Operators are special symbols that perform operations on values and variables.
##### Arithmetic Operators
Used for mathematical calculations:
* `+` : Addition (e.g., `5 + 2` is `7`)
* `-` : Subtraction (e.g., `5 - 2` is `3`)
* `*` : Multiplication (e.g., `5 * 2` is `10`)
* `/` : Division (e.g., `5 / 2` is `2.5` - always returns a float)
* `%` : Modulus (remainder of division) (e.g., `5 % 2` is `1`)
* `**` : Exponentiation (power) (e.g., `5 ** 2` is `25`)
* `//` : Floor Division (integer division, discards remainder) (e.g., `5 // 2` is `2`)
```python
a = 10
b = 3
print(f"a + b = {a + b}") # 13
print(f"a / b = {a / b}") # 3.333...
print(f"a % b = {a % b}") # 1
```
##### Comparison Operators
Used to compare two values; they always return a `True` or `False` (Boolean) result.
* `==` : Equal to (e.g., `5 == 5` is `True`)
* `!=` : Not equal to (e.g., `5 != 3` is `True`)
* `>` : Greater than (e.g., `5 > 3` is `True`)
* `<` : Less than (e.g., `5 < 3` is `False`)
* `>=` : Greater than or equal to (e.g., `5 >= 5` is `True`)
* `<=` : Less than or equal to (e.g., `5 <= 3` is `False`)
```python
x = 7
y = 10
print(f"x == y is {x == y}") # False
print(f"x < y is {x < y}") # True
```
##### Logical Operators
Used to combine conditional statements.
* `and` : Returns `True` if both statements are `True`.
* `or` : Returns `True` if at least one statement is `True`.
* `not` : Reverses the result; returns `False` if the result is `True`.
```python
condition1 = (10 > 5) # True
condition2 = (10 < 3) # False
print(f"condition1 and condition2 is {condition1 and condition2}") # False
print(f"condition1 or condition2 is {condition1 or condition2}") # True
print(f"not condition1 is {not condition1}") # False
```
#### Basic Control Flow: Conditional Statements (`if`, `elif`, `else`)
Conditional statements allow your program to make decisions and execute different blocks of code based on whether certain conditions are `True` or `False`. Indentation is crucial in Python to define code blocks.
##### `if` statement
Executes a block of code if a condition is `True`.
```python
number = 10
if number > 0:
print("The number is positive.")
```
##### `if-else` statement
Executes one block of code if the condition is `True`, and another if it's `False`.
```python
score = 45
if score >= 50:
print("You passed the exam!")
else:
print("You failed the exam.")
```
##### `if-elif-else` statement
Used for multiple conditions. `elif` (short for 'else if') checks another condition if the previous `if` or `elif` conditions were `False`.
```python
grade = 75
if grade >= 90:
print("Excellent!")
elif grade >= 70:
print("Good job!")
elif grade >= 50:
print("You passed.")
else:
print("Needs improvement.")
```
### Vocabulary
* **Variable**: A named storage location that holds a value. E.g., `age = 16`.
* **Data Type**: Classification of data that tells the interpreter how the programmer intends to use the data. E.g., `int`, `float`, `str`, `bool`.
* **String (`str`)**: A sequence of characters, usually text, enclosed in quotes. E.g., `"Hello"`.
* **Integer (`int`)**: A whole number (positive, negative, or zero). E.g., `10`.
* **Float (`float`)**: A number with a decimal point. E.g., `3.14`.
* **Boolean (`bool`)**: A data type with only two possible values: `True` or `False`.
* **Operator**: A symbol that tells the interpreter to perform a specific mathematical or logical manipulation. E.g., `+`, `==`, `and`.
* **Comment**: Text within a program that is ignored by the interpreter and is used to explain the code. Denoted by `#`.
* **Input**: Data received by a program from an external source (e.g., user keyboard) using the `input()` function.
* **Output**: Data displayed or sent by a program to an external destination (e.g., screen) using the `print()` function.
* **Indentation**: The use of white space (spaces or tabs) at the beginning of a line to define code blocks (e.g., within `if` statements) in Python.
* **Conditional Statement**: A programming construct that allows code to execute different actions based on a condition (`if`, `elif`, `else`).
### Examples
#### Example 1: Personalized Greeting
```python
# Ask the user for their name
user_name = input("Please enter your name: ")
# Ask for their favourite hobby
hobby = input("What is your favourite hobby? ")
# Print a personalized message
print(f"Hello, {user_name}! It's great to know you enjoy {hobby}.")
```
#### Example 2: Simple Calculator
```python
# Get two numbers from the user
num1_str = input("Enter the first number: ")
num2_str = input("Enter the second number: ")
# Convert inputs to float for calculations
num1 = float(num1_str)
num2 = float(num2_str)
# Perform arithmetic operations
sum_result = num1 + num2
diff_result = num1 - num2
prod_result = num1 * num2
# Check for division by zero before dividing
if num2 != 0:
div_result = num1 / num2
print(f"Sum: {sum_result}")
print(f"Difference: {diff_result}")
print(f"Product: {prod_result}")
print(f"Division: {div_result}")
else:
print("Cannot divide by zero!")
```
#### Example 3: Check if a number is even or odd
```python
# Get a number from the user
number_str = input("Enter an integer: ")
number = int(number_str)
# Check if the number is even or odd using the modulus operator
if number % 2 == 0:
print(f"The number {number} is even.")
else:
print(f"The number {number} is odd.")
```
### Exercises
1. **Favorite Song**: Write a Python program that asks you for your favorite song and the artist who performs it, then prints a message like: `"My favorite song is [Song Title] by [Artist Name]."`
2. **Age in Dog Years**: Write a program that asks the user for their age in human years and then calculates and prints their age in "dog years" (assume 1 human year = 7 dog years).
3. **Area of a Rectangle**: Write a program that takes the length and width of a rectangle as input from the user (as floats), calculates its area, and prints the result. The formula for the area of a rectangle is \[ Area = length \times width \].
4. **Positive, Negative, or Zero**: Write a program that asks the user to enter a number. Your program should then print whether the number is positive, negative, or zero.
### Assignment
1. **Body Mass Index (BMI) Calculator**: Write a Python program that calculates the Body Mass Index (BMI).
* Ask the user for their weight in kilograms and height in meters.
* Calculate BMI using the formula: \[ BMI = \frac{weight}{height^2} \]
* Print the calculated BMI.
* Add an `if-elif-else` statement to classify the BMI:
* Underweight: `BMI < 18.5`
* Normal weight: `18.5 <= BMI < 25`
* Overweight: `25 <= BMI < 30`
* Obese: `BMI >= 30`
2. **Simple Login Simulation**: Write a program that simulates a simple login. Define a correct `username` (e.g., "admin") and `password` (e.g., "password123") as variables in your code. Ask the user to enter a username and password. If both match the predefined values, print "Login Successful!". Otherwise, print "Invalid Username or Password."
### Summary
In this first lesson on Python coding, you've learned the fundamental building blocks of programming. We covered what Python is and why it's popular, how to write your very first "Hello, World!" program, and how to use variables to store different types of data like numbers and text. You now know how to get input from the user and display output, use comments to explain your code, and perform calculations with various operators. Most importantly, you've been introduced to conditional statements (`if`, `elif`, `else`), which allow your programs to make decisions and respond differently based on conditions. Keep practicing these concepts, as they are the foundation for more complex programming!
## Coding 2 (Python)
### Introduction
Welcome to Coding 2! In this lesson, we will continue our journey into the world of programming with Python. Building on the basics, we will dive deeper into how programs make decisions, repeat actions, and organize code into reusable blocks. Understanding these concepts is crucial for writing more complex and efficient programs.
### Key Concepts
#### Review of Python Basics
Before we introduce new concepts, let's quickly recap some fundamental Python elements:
* **Variables and Data Types**: Variables are used to store data. Common data types include:
* `int`: Whole numbers (e.g., `5`, `-10`).
* `float`: Decimal numbers (e.g., `3.14`, `-0.5`).
* `str`: Text, enclosed in single or double quotes (e.g., `'hello'`, `"Python"`).
* `bool`: Boolean values, either `True` or `False`.
* **Input/Output**:
* `print()`: Displays output to the console.
* `input()`: Reads input from the user.
* **Operators**: Symbols that perform operations on values and variables.
* **Arithmetic Operators**: `+`, `-`, `*`, `/`, `%` (modulo), `**` (exponentiation), `//` (floor division).
* **Comparison Operators**: `==` (equal to), `!=` (not equal to), `<` (less than), `>` (greater than), `<=` (less than or equal to), `>=` (greater than or equal to).
* **Logical Operators**: `and`, `or`, `not`.
#### Conditional Statements: `if`, `elif`, `else`
Conditional statements allow your program to make decisions and execute different blocks of code based on whether a condition is `True` or `False`.
* **`if` statement**: Executes a block of code if its condition is `True`.
* **`elif` (else if) statement**: Used to check another condition if the preceding `if` or `elif` conditions were `False`.
* **`else` statement**: Executes a block of code if all preceding `if` and `elif` conditions were `False`.
* **Indentation**: Python uses indentation (usually 4 spaces) to define code blocks. This is critical for the correct execution of conditional statements and loops.
```python
age = 18
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
```
#### Looping Constructs
Loops allow you to repeat a block of code multiple times.
##### `for` loop
The `for` loop is used for iterating over a sequence (like a list, tuple, string, or range).
```python
# Iterating through a range of numbers
for i in range(5): # range(5) generates numbers 0, 1, 2, 3, 4
print(i)
# Iterating through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
```
##### `while` loop
The `while` loop executes a block of code as long as a condition is `True`. You must ensure that the condition eventually becomes `False` to avoid an infinite loop.
```python
count = 0
while count < 3:
print("Count is:", count)
count += 1 # Increment count to eventually make the condition False
```
##### `break` and `continue` statements
* **`break`**: Terminates the loop entirely and transfers control to the statement immediately following the loop.
* **`continue`**: Skips the rest of the current iteration of the loop and proceeds to the next iteration.
#### Functions
Functions are blocks of organized, reusable code that perform a single, related action. They help to make your code more modular, readable, and efficient.
* **Defining a Function**: Use the `def` keyword, followed by the function name, parentheses `()`, and a colon `:`. Parameters (inputs) can be placed inside the parentheses.
* **Parameters and Arguments**: Parameters are variables listed inside the parentheses in the function definition. Arguments are the actual values passed to the function when it is called.
* **`return` statement**: A function can return a value using the `return` keyword. If no `return` statement is used, the function implicitly returns `None`.
* **Calling a Function**: To execute a function, simply type its name followed by parentheses, passing any required arguments.
```python
def greet(name): # 'name' is a parameter
"""This function greets the person passed in as a parameter."""
return "Hello, " + name + "!"
message = greet("Alice") # 'Alice' is an argument
print(message)
def add_numbers(a, b):
return a + b
sum_result = add_numbers(5, 3)
print("The sum is:", sum_result)
```
### Vocabulary
* **Variable**: A named location in memory used to store data.
* **Data Type**: A classification of data that tells the computer how the data should be interpreted (e.g., integer, string, boolean).
* **Operator**: A symbol that performs an operation on one or more values (operands).
* **Conditional Statement**: A programming construct (`if`, `elif`, `else`) that allows a program to execute different code blocks based on whether a condition is true or false.
* **Loop**: A control flow statement that allows code to be executed repeatedly based on a condition or a sequence of items.
* **Function**: A self-contained block of code designed to perform a specific task, which can be reused multiple times throughout a program.
* **Indentation**: The whitespace at the beginning of a line of code, used in Python to define the scope and hierarchy of code blocks.
* **Argument**: The actual value that is passed to a function when it is called.
* **Parameter**: A variable defined in the function's signature that acts as a placeholder for the arguments the function will receive.
* **Return Value**: The data that a function sends back to the part of the program that called it.
### Examples
#### Example 1: Simple User Interaction with Conditions
```python
name = input("What is your name? ")
age_str = input("How old are you? ")
age = int(age_str)
if age < 0:
print("Age cannot be negative.")
elif age < 18:
print(f"Hello {name}, you are a minor.")
elif age < 65:
print(f"Hello {name}, you are an adult.")
else:
print(f"Hello {name}, you are a senior.")
```
#### Example 2: Sum of Numbers using a `for` loop
```python
numbers = [10, 20, 30, 40, 50]
total = 0
for num in numbers:
total += num # Same as: total = total + num
print("The sum of numbers is:", total)
```
#### Example 3: Guessing Game using a `while` loop
```python
import random
secret_number = random.randint(1, 10)
guess = 0
attempts = 0
print("I'm thinking of a number between 1 and 10. Can you guess it?")
while guess != secret_number:
try:
guess = int(input("Enter your guess: "))
attempts += 1
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print(f"Congratulations! You guessed the number {secret_number} in {attempts} attempts.")
except ValueError:
print("Invalid input. Please enter a whole number.")
```
#### Example 4: Function to calculate factorial
The factorial of a non-negative integer \(n\), denoted by \(n!\), is the product of all positive integers less than or equal to \(n\).
\[ n! = n imes (n-1) imes (n-2) imes ext{...} imes 1 \]
For example, \(5! = 5 imes 4 imes 3 imes 2 imes 1 = 120\).
```python
def calculate_factorial(n):
if n < 0:
return "Factorial is not defined for negative numbers"
elif n == 0:
return 1
else:
factorial = 1
for i in range(1, n + 1):
factorial *= i
return factorial
num = 5
print(f"The factorial of {num} is: {calculate_factorial(num)}")
num = 0
print(f"The factorial of {num} is: {calculate_factorial(num)}")
```
### Exercises
1. **Even or Odd Checker**: Write a Python program that asks the user for a number and prints whether it is an even or an odd number using an `if-else` statement.
2. **Counting Multiples**: Write a program that uses a `for` loop to count and print how many numbers between 1 and 20 (inclusive) are multiples of 3.
3. **Password Validator**: Create a simple program that continuously asks the user to enter a password. Use a `while` loop to keep asking until the user enters "secret123". Once correct, print "Access Granted!".
4. **Area Calculator Function**: Define a function called `calculate_area` that takes two arguments, `length` and `width`, and returns the area of a rectangle. Then call this function with sample values and print the result.
### Assignment
1. **FizzBuzz**: Write a Python program that prints the numbers from 1 to 50. For multiples of three, print "Fizz" instead of the number. For multiples of five, print "Buzz". For numbers that are multiples of both three and five, print "FizzBuzz".
2. **Temperature Converter Function**: Create a function named `convert_celsius_to_fahrenheit` that takes a temperature in Celsius as an argument and returns the temperature in Fahrenheit. The formula is: \( F = C imes 1.8 + 32 \).
3. **Simple Calculator**: Design a menu-driven program that allows the user to perform basic arithmetic operations (addition, subtraction, multiplication, division). The program should:
* Display a menu (e.g., 1. Add, 2. Subtract, 3. Multiply, 4. Divide, 5. Exit).
* Take user input for their choice.
* If an operation is chosen, ask for two numbers, perform the operation, and print the result.
* Continue displaying the menu until the user chooses to exit.
* Handle invalid menu choices.
* Handle division by zero errors.
### Summary
In this lesson, we have explored fundamental control structures in Python: conditional statements (`if`, `elif`, `else`) for decision-making and looping constructs (`for`, `while`) for repetition. We also learned how to define and use functions to organize code, promote reusability, and improve program readability. Mastering these concepts is essential for building more sophisticated and robust Python applications. Remember the importance of correct indentation in Python to define code blocks.
## Coding 3 (Python)
### Introduction
Welcome to Coding 3! In this lesson, we will continue our journey into the world of programming using Python. We will build upon your existing knowledge by exploring fundamental programming concepts such as taking input from users, making decisions with conditional statements, repeating actions with loops, and organizing your code with functions. By the end of this lesson, you will be able to write more interactive and powerful Python programs.
### Key Concepts
#### 1. Variables and Data Types (Review)
Recall that a **variable** is a named storage location in a computer's memory used to hold data. A **data type** classifies what kind of value a variable can hold.
Python automatically determines the data type of a variable based on the value assigned to it. Some common data types you've encountered include:
* **Integers (`int`):** Whole numbers (e.g., `5`, `-10`).
* **Floating-point numbers (`float`):** Numbers with decimal points (e.g., `3.14`, `-0.5`).
* **Strings (`str`):** Sequences of characters enclosed in single or double quotes (e.g., `'hello'`, `"world"`).
* **Booleans (`bool`):** Represent truth values, either `True` or `False`.
#### 2. Input and Output
To make our programs interactive, we need ways for them to communicate with the user. This involves taking **input** from the user and displaying **output** to them.
* **Output: The `print()` Function**
The `print()` function is used to display information on the console. You can print strings, numbers, variables, or combinations of these.
```python
print("Hello, Form Four!")
name = "Alice"
age = 16
print("My name is", name, "and I am", age, "years old.")
```
* **Input: The `input()` Function**
The `input()` function allows your program to receive data from the user. It displays a prompt (optional) and then waits for the user to type something and press Enter. The value entered by the user is always returned as a **string**.
```python
user_name = input("What is your name? ")
print("Nice to meet you,", user_name)
# Remember to convert input to the correct type if needed
num_str = input("Enter a number: ")
num_int = int(num_str) # Convert string to integer
print("You entered:", num_int)
```
#### 3. Conditional Statements (Decisions)
Conditional statements allow your program to make decisions and execute different blocks of code based on whether certain conditions are `True` or `False`.
* **`if` statement**
Executes a block of code if a condition is `True`.
```python
score = 75
if score >= 50:
print("You passed!")
```
* **`if-else` statement**
Executes one block of code if the condition is `True` and another if it's `False`.
```python
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
```
* **`if-elif-else` statement**
Allows you to check multiple conditions sequentially.
```python
grade = 85
if grade >= 90:
print("Excellent!")
elif grade >= 80:
print("Very Good!")
elif grade >= 70:
print("Good!")
else:
print("Keep trying!")
```
#### 4. Loops (Repetition)
Loops allow your program to repeat a block of code multiple times. This is very useful for automating repetitive tasks.
* **`for` loop**
Used for iterating over a sequence (like a list, string, or range of numbers).
```python
# Looping through a range of numbers
for i in range(5): # i will be 0, 1, 2, 3, 4
print("Count:", i)
# Looping through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
```
* **`while` loop**
Repeats a block of code as long as a condition remains `True`.
```python
count = 0
while count < 3:
print("Hello")
count = count + 1 # or count += 1
# An infinite loop example (be careful!)
# while True:
# print("This will print forever!")
```
#### 5. Functions
Functions are blocks of organized, reusable code that perform a specific task. They help make your programs modular, readable, and easier to maintain.
* **Defining a function**
You define a function using the `def` keyword, followed by the function name, parentheses `()` for parameters, and a colon `:`. The code block inside the function is indented.
```python
def greet():
print("Welcome to Python functions!")
def add_numbers(a, b):
sum = a + b
return sum # 'return' sends a value back from the function
```
* **Calling a function**
To use a function, you simply call it by its name followed by parentheses, providing any required arguments.
```python
greet() # Calls the greet function
result = add_numbers(10, 5) # Calls add_numbers with arguments 10 and 5
print("The sum is:", result) # Output: The sum is: 15
```
### Vocabulary
* **Variable:** A named storage location for data in a program.
* **Data Type:** A classification of what kind of value a variable can hold (e.g., integer, string, float).
* **Input:** Data received by a program, typically from a user.
* **Output:** Information displayed or produced by a program.
* **Conditional Statement:** A programming construct (`if`, `elif`, `else`) that allows different code blocks to be executed based on conditions.
* **Loop:** A programming construct (`for`, `while`) that allows a block of code to be repeated multiple times.
* **Function:** A reusable block of code designed to perform a specific task.
* **Argument:** A value passed to a function when it is called.
* **Parameter:** A variable listed inside the parentheses in the function definition.
* **`range()`:** A built-in Python function that generates a sequence of numbers.
### Examples
#### Example 1: Simple Calculator using `input()`, `if-elif-else`
```python
print("--- Simple Calculator ---")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
operation = input("Enter an operation (+, -, *, /): ")
if operation == '+':
result = num1 + num2
print(f"{num1} + {num2} = {result}")
elif operation == '-':
result = num1 - num2
print(f"{num1} - {num2} = {result}")
elif operation == '*':
result = num1 * num2
print(f"{num1} * {num2} = {result}")
elif operation == '/':
if num2 != 0:
result = num1 / num2
print(f"{num1} / {num2} = {result}")
else:
print("Error: Division by zero is not allowed.")
else:
print("Invalid operation. Please use +, -, *, or /.")
```
#### Example 2: Counting with a `for` loop and a function
```python
def count_up_to(limit):
print(f"Counting from 1 to {limit}:")
for i in range(1, limit + 1):
print(i)
# Call the function
user_limit = int(input("Enter a number to count up to: "))
count_up_to(user_limit)
```
#### Example 3: Guessing Game with a `while` loop
```python
import random
def guessing_game():
secret_number = random.randint(1, 10)
guess = 0
attempts = 0
print("I'm thinking of a number between 1 and 10. Can you guess it?")
while guess != secret_number:
try:
guess = int(input("Enter your guess: "))
attempts += 1
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print(f"Congratulations! You guessed the number {secret_number} in {attempts} attempts!")
except ValueError:
print("Invalid input. Please enter a whole number.")
guessing_game()
```
### Exercises
1. **Greeting Program:** Write a Python program that asks the user for their name and then prints a personalized greeting like "Hello, [Name]! Welcome to Python programming."
2. **Even or Odd:** Write a program that asks the user for an integer and then tells them if the number is even or odd.
*Hint: Use the modulo operator (`%`). A number is even if `number % 2 == 0`.*
3. **Sum of Numbers:** Write a program that asks the user for a positive integer `n` and then uses a `for` loop to calculate the sum of all integers from 1 to `n`.
4. **Multiplication Table:** Create a function `print_multiplication_table(number)` that takes an integer `number` as an argument and prints its multiplication table up to 10. For example, `print_multiplication_table(5)` should print:
```
5 x 1 = 5
5 x 2 = 10
...
5 x 10 = 50
```
Call this function for the number 7.
### Assignment
1. **Grade Classifier:** Write a Python program that asks the user to enter a student's score (out of 100). Use `if-elif-else` statements to assign and print a letter grade based on the following criteria:
* 90-100: A
* 80-89: B
* 70-79: C
* 60-69: D
* Below 60: F
2. **Countdown Timer:** Write a program that asks the user for a starting positive integer. Use a `while` loop to count down from that number to 1, printing each number. After reaching 1, print "Blast off!". Ensure your program handles non-positive input gracefully.
3. **Password Validator Function:** Create a Python function called `validate_password(password)` that takes a string `password` as an argument. The function should check if the password meets the following criteria and return `True` if it does, `False` otherwise:
* At least 8 characters long.
* Contains at least one uppercase letter.
* Contains at least one lowercase letter.
* Contains at least one digit.
*Hint: Python string methods like `len()`, `isupper()`, `islower()`, `isdigit()` and looping through the string will be useful.*
Test your function with a few example passwords and print whether they are valid or not.
### Summary
In this lesson, you have learned essential Python programming constructs that make your programs more dynamic and structured. We reviewed variables and data types, and then dived into interactive input/output using `input()` and `print()`. You mastered decision-making with `if`, `elif`, and `else` statements, allowing your programs to respond to different conditions. We also explored `for` and `while` loops for repeating tasks efficiently. Finally, you learned how to define and call functions, a powerful way to organize and reuse your code. These skills are fundamental to building more complex and robust applications in Python.
## Integration activities
### Introduction
Welcome, Form Four Computer Science students! In our previous lessons, we've focused on writing individual pieces of source code, like functions or small programs. However, real-world software is often very complex, made up of many different parts developed by different people, or even different teams. For these parts to work together seamlessly and create a functional system, they must be combined and tested. This process is called **integration**, and it's a crucial stage in software development. In this lesson, we will explore what integration activities involve, why they are important, and how they are performed.
### Key Concepts
#### What is Software Integration?
Software integration is the process of combining different software modules or components into a single, cohesive system. Each module might handle a specific task, and integration ensures that these modules communicate correctly and function as a unified whole.
#### Why is Integration Important?
Integration is vital for several reasons:
* **Ensures Compatibility:** It verifies that different parts of the system can communicate and exchange data correctly.
* **Early Bug Detection:** Integration often reveals interface errors or miscommunications between modules that individual unit tests might miss.
* **Improved System Reliability:** By identifying and fixing integration issues early, the overall stability and reliability of the software increase.
* **Facilitates Teamwork:** When multiple developers work on different parts of a system, integration provides a structured way to combine their efforts.
#### Types of Integration Approaches
There are several strategies for integrating software modules:
##### 1. Big-Bang Integration
* All modules are developed independently and then combined and tested all at once.
* **Advantages:** Simple to implement for very small projects.
* **Disadvantages:** Difficult to pinpoint errors as there are too many variables. Debugging can be a nightmare, making it unsuitable for large or complex projects.
##### 2. Incremental Integration
This approach involves integrating modules one by one or in small groups. It allows for easier error detection and isolation.
###### a. Bottom-Up Integration
* Integration starts with the lowest-level modules (modules that don't depend on other modules) and progressively moves upwards.
* **Process:** Lower-level modules are tested first, then integrated with the next level up. Special programs called **drivers** are often used to simulate the higher-level modules during testing.
* **Advantages:** Critical low-level modules are tested thoroughly early.
* **Disadvantages:** High-level system architecture issues might only be discovered late.
###### b. Top-Down Integration
* Integration starts with the highest-level modules (the main control modules) and progressively moves downwards.
* **Process:** High-level modules are tested first, using **stubs** (dummy modules that simulate the behavior of lower-level modules yet to be developed) for their dependencies.
* **Advantages:** Major interface errors and design flaws are detected early.
* **Disadvantages:** Lower-level modules, which might contain complex logic, are tested later.
###### c. Sandwich Integration (Hybrid)
* Combines both top-down and bottom-up approaches.
* Critical high-level modules are integrated top-down, critical low-level modules are integrated bottom-up, and integration meets in the middle.
##### 3. Continuous Integration (CI)
* A development practice where developers frequently merge their code changes into a central repository, often multiple times a day.
* Each merge is then verified by an automated build and automated tests.
* **Advantages:** Reduces integration problems, finds bugs earlier, improves code quality, and allows for faster releases.
* **Tools:** Jenkins, Travis CI, GitLab CI, GitHub Actions are popular CI tools.
#### Challenges in Software Integration
* **Interface Mismatches:** When modules expect different data formats or communication protocols.
* **Data Incompatibility:** Data types or structures don't align between modules.
* **Performance Issues:** Integrated system performs slower than expected.
* **Error Handling:** Inconsistent ways of handling errors across different modules.
* **Version Control Conflicts:** When multiple developers modify the same code concurrently.
#### Integration Testing
Integration testing is a type of software testing that verifies the interfaces between components against a software design. It ensures that data flow and control flow between components work as intended.
* **Purpose:** To expose faults in the interaction between integrated units.
* **Phases:**
1. **Planning:** Define the scope of integration, modules to be integrated, and strategy.
2. **Designing Test Cases:** Create specific tests to check interactions between modules.
3. **Execution:** Run the integration tests.
4. **Reporting:** Document results, report bugs, and track fixes.
#### Tools and Techniques for Integration
* **Version Control Systems (VCS):** Tools like Git manage changes to source code, allowing multiple developers to work on the same project without overwriting each other's work. They are essential for merging code.
* **Automated Build Tools:** Tools like Maven or Gradle automate the compilation, packaging, and dependency management of code.
* **Automated Testing Frameworks:** Tools like JUnit (for Java) or Pytest (for Python) allow for the creation and execution of automated integration tests.
### Vocabulary
* **Module:** A distinct, self-contained component of a larger program or system.
* **Component:** Similar to a module; a part of a software system with a defined function.
* **Integration:** The process of combining different software modules or components into a single system.
* **Integration Testing:** A type of software testing that verifies the interfaces and interactions between combined modules.
* **Continuous Integration (CI):** A development practice where code changes are frequently merged, built, and tested automatically.
* **Driver:** A program used in bottom-up integration to simulate the behavior of a higher-level module.
* **Stub:** A dummy program or module used in top-down integration to simulate the behavior of a lower-level module.
* **Version Control System (VCS):** Software that helps developers manage changes to source code over time, e.g., Git.
* **Repository:** A central location where code and its history are stored in a VCS.
### Examples
#### Example 1: E-commerce Website
Imagine an e-commerce website. It typically has several components:
* **User Interface (UI) Module:** Handles how users interact with the site (browsing, adding to cart).
* **Product Catalog Module:** Manages product information (descriptions, prices, stock).
* **Payment Gateway Module:** Handles secure transactions with banks.
* **Order Management Module:** Processes orders and updates inventory.
* **Database Module:** Stores all product, user, and order data.
Each module is developed separately. During integration, we ensure:
* When a user clicks 'Add to Cart' (UI), the Product Catalog module correctly updates the cart.
* When a user makes a payment (UI), the Payment Gateway module correctly communicates with the bank, and upon success, the Order Management module creates a new order, and the Database module records it.
* Data like product prices or user details are consistent across all modules.
#### Example 2: Calculator Application
Consider a simple calculator application with functions for addition, subtraction, multiplication, and division. Each function can be a separate module. Integration involves:
* Making sure the main display module correctly calls the `add()` function when the '+' button is pressed.
* Ensuring the `add()` function receives the correct numbers from the display and returns the correct result.
* Checking that all functions handle invalid inputs (e.g., division by zero) consistently.
### Exercises
1. Explain in your own words what software integration is and why it's a critical step in software development.
2. You are developing a new social media application. Would you recommend using Big-Bang integration? Justify your answer.
3. Differentiate between a 'driver' and a 'stub' in the context of incremental integration.
4. List three advantages of using Continuous Integration (CI) in a software project.
5. Consider a school management system with modules for student records, staff payroll, and timetable management. Describe a potential integration challenge you might face when combining the student records module with the timetable management module.
### Assignment
1. Research and describe one popular Continuous Integration (CI) tool (e.g., Jenkins, Travis CI, GitLab CI, GitHub Actions). Explain its main features and how it helps in the integration process.
2. You are tasked with building a simple weather application that has two main modules: one to fetch weather data from an online API and another to display the weather data to the user. Design an incremental integration strategy (either top-down or bottom-up) for this application. Describe the steps you would take and how you would use stubs or drivers if necessary.
3. Write a short paragraph explaining how a Version Control System (like Git) aids in the integration of code from multiple developers working on the same project.
### Summary
Today, we've learned that writing source code isn't just about individual components; it's also about making them work together harmoniously. Software integration is the crucial process of combining these components into a unified system. We explored different integration approaches, including Big-Bang, Bottom-Up, Top-Down, and the highly effective Continuous Integration. We also discussed the common challenges faced during integration and how integration testing helps ensure everything functions correctly. Understanding and implementing proper integration activities are key skills for any aspiring computer scientist, as they lead to more reliable, robust, and maintainable software systems. Keep practicing and exploring these concepts!
Quiz du chapitre
16 questions — vérifie chaque réponse pour voir l'explication.