Exercício Python #007 - Média Aritmética
Table of Contents
Introduction
In this tutorial, we will develop a Python program that reads two grades from a student, calculates the average, and displays the result. This exercise will help you practice basic input/output operations and arithmetic calculations in Python.
Step 1: Set Up Your Python Environment
Before you begin coding, ensure you have a Python environment set up. You can use any IDE or text editor, such as:
- PyCharm
- Visual Studio Code
- Jupyter Notebook
- IDLE (comes with Python installation)
Practical Tips
- Make sure you have Python installed on your system. You can download it from python.org.
Step 2: Create the Python Script
Open your IDE and create a new Python file, for example, media_aritmetica.py
.
Code to Read Input
Start by writing the code to read the two grades from the user. Use the input()
function to get user input.
# Read the first grade
nota1 = float(input("Digite a primeira nota: "))
# Read the second grade
nota2 = float(input("Digite a segunda nota: "))
Common Pitfalls
- Ensure you convert the input to
float
to handle decimal values correctly. - Validate that the input is a number to avoid runtime errors.
Step 3: Calculate the Average
Next, you will calculate the average of the two grades.
Code for Calculation
Add the following code to compute the average:
# Calculate the average
media = (nota1 + nota2) / 2
Step 4: Display the Result
Now, you will display the calculated average to the user. Use the print()
function for this purpose.
Code to Print the Average
Include the following code to show the result:
# Display the result
print(f"A média do aluno é: {media:.2f}")
Explanation
- The
:.2f
format specifier limits the output to two decimal places for better readability.
Conclusion
You have successfully created a Python program that calculates the average of two student grades. Here’s a summary of what we did:
- Set up the Python environment.
- Created a script to read two grades.
- Calculated the average of the grades.
- Displayed the result to the user.
Next Steps
- Consider adding input validation to ensure grades are within valid ranges (0-10).
- Explore how to extend this program to calculate averages for multiple students or handle more complex grading systems.