From 00405be313f65a842ab27ce2bf1859c45368abeb Mon Sep 17 00:00:00 2001 From: Junior Date: Tue, 25 Jun 2024 11:11:27 -0400 Subject: [PATCH] Add a file showing the use of global variables in functions --- Python/029_scope.py | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Python/029_scope.py diff --git a/Python/029_scope.py b/Python/029_scope.py new file mode 100644 index 0000000..fb8e800 --- /dev/null +++ b/Python/029_scope.py @@ -0,0 +1,61 @@ +# Scope of variables + +# As mentioned before, the "scope" of something is just +# "where can this thing be accessed". + +# More detailed reading about scope: https://realpython.com/python-scope-legb-rule/ + +# Highly Recommended: Details about Mutable vs. Immutable +# https://realpython.com/python-mutable-vs-immutable-types/ + +# Let's declare a couple global variables +MAX_TEACHERS = 30 +MAX_STUDENTS_PER_TEACHER = 25 + +# Let's create a couple functions to get values + +# This function makes use of the MAX_TEACHERS global variable +def get_teacher_count(): + count = 0 + while count == 0: + # Get a value from the user + response = input(f"How many teachers at the school (1-{MAX_TEACHERS})? ") + # If response is just a number + if response.isdigit(): + # Convert to an int + count = int(response) + # If count is out of range, show an error and reset count + if count == 0 or count > MAX_TEACHERS: + print(f" Error: Number of teachers must be greater than zero and no greater than {MAX_TEACHERS}!") + count = 0 + # Otherwise show an error + else: + print(f" Error: Please enter a value between 1 and {MAX_TEACHERS}!") + return count + +# This function makes use of the MAX_STUDENTS_PER_TEACHER global variable +# and is passed the number of teachers obtained from get_teacher_count() +def get_student_count(teacher_count: int): + count = 0 + # Can't have fewer students than teachers + min_students = teacher_count + # Can't have more than MAX_STUDENTS_PER_TEACHER average + max_students = teacher_count * MAX_STUDENTS_PER_TEACHER + while count == 0: + response = input(f"How many students at the school ({min_students}-{max_students})? ") + if response.isdigit(): + count = int(response) + if count < min_students or count > max_students: + print(f" Error: Number of teachers must be between {min_students} and {max_students}!") + count = 0 + else: + print(f" Error: Please enter a value between {min_students} and {max_students}!") + return count + +# Some program logic +teachers = get_teacher_count() +students = get_student_count(teachers) +print() +print(f"Teachers: {teachers}") +print(f"Students: {students}") +print("Average class size: " + str(students // teachers)) \ No newline at end of file