A Python function gives a repeated task a name. You send values in through parameters, calculate inside the function, and send one result back with return. This lesson builds a small student grade summary and explains why a variable inside a function does not change a variable with the same name outside it.
Name + marks → describe_student() → Average + result
Write and run the program
Save the complete code below as grade_students.py. Run it with python grade_students.py (or py grade_students.py on Windows). It uses only the Python standard library.
def describe_student(
name: str, marks: list[int], pass_mark: float = 40
) -> str:
if not marks:
raise ValueError("Add at least one mark")
average = sum(marks) / len(marks)
status = "Pass" if average >= pass_mark else "Practice again"
return f"{name}: {average:.1f} - {status}"
average = 100
print(describe_student("Asha", [62, 76, 79]))
print(describe_student("Ravi", [22, 38, 40]))
print(describe_student("Mina", [45, 55], pass_mark=50))
print(f"Outside average: {average}")
Expected output
Asha: 72.3 - Pass
Ravi: 33.3 - Practice again
Mina: 50.0 - Pass
Outside average: 100
Understand parameters, defaults and return
nameandmarksare required parameters. Each call supplies a student and a list of marks.pass_mark=40is a default. Mina's call uses the keyword argumentpass_mark=50to choose a different threshold.returnsends the formatted text back toprint(). The function does not print it by itself.- The empty-list check avoids dividing by zero and tells the caller what to fix.
Why is the outside average still 100?
The assignment to average inside describe_student() creates a local name for that function call. The separate average = 100 outside the function is a module-level name. The local assignment does not reassign the outside name. Each call computes its own average.
Beginner tip: Pass data as arguments and return the result. This keeps the function easier to test than changing global variables. Type hints such as list[int] explain the expected input, but Python does not automatically reject the wrong type at runtime.
Practice
- Add a fourth student and predict the result before running the program.
- Change the default pass mark to 50. Which students change status?
- Call the function with an empty list. Read the error, then explain why the guard is useful.
Next: Try a list comprehension to select passing students, then save their summaries to a text file. Find related lessons in the Python tutorial path. For Python's rules, read the official function guide and scope guide.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.