Add a file showing the use of global variables in functions

This commit is contained in:
Junior 2024-06-25 11:11:27 -04:00
parent 9009000e53
commit 00405be313

61
Python/029_scope.py Normal file
View File

@ -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))