A school timetable is displayed as a 2D table consisting of 5 rows (for each day of the week) and 5 columns (number of lessons in a day).
Such a table can be stored in a computer program using a 2-dimensional array (2d Array). In python, this is done by creating a list of lists.
Each value of a 2D array can then be accessed by proving two indices: the row number and the column number as displayed on the picture below:
Python Challenges
The following 3 tabs contain 3 different challenges, all based on accessing information from the 2D array called timetable.
What Lesson?Today's Lessons?How Many Lessons?
Write a program that:
- Asks the user to input a day of the week (e.g. Tuesday)
- Asks the user to input a period of the day (between 1 and 5) (e.g. 2)
- Retrieves and outputs the lesson on that day and period (e.g. Spanish)
Write a program that:
- Asks the user to input a day of the week (e.g. Tuesday)
- Displays all five lessons for that day
Write a program that:
- Asks the user to input a subject (e.g. Maths)
- Counts and outputs the number of lessons for that subject throughout the week. (e.g. “You have 3 Maths lesson this week.”)
Python Code
Use the following code to complete all three challenges mentioned above:
Help?
The following lines of code will help you solve each of the three challenges.
What Lesson?Today's Lessons?How Many Lessons?
#INPUT day = input("Day of the week?").title() period = int(input("Lesson number (1 to 5):")) while period<1 or period>5: period = int(input("Lesson number (1 to 5):")) #PROCESS lesson="" if day=="Monday": lesson = timetable[0][period-1] elif day=="Tuesday": lesson = timetable[1][period-1] elif day=="Wednesday": lesson = timetable[2][period-1] elif day=="Thursday": lesson = timetable[3][period-1] elif day=="Friday": lesson = timetable[4][period-1] else: print("Not a valid week day!") #OUTPUT if lesson!="": print("On " + day + ", lesson " + str(period) + " you have " + lesson + ".")
#INPUT day = input("Day of the week?").title() #PROCESS lessons=[] if day=="Monday": lessons = timetable[0] elif day=="Tuesday": lessons = timetable[1] elif day=="Wednesday": lessons = timetable[2] elif day=="Thursday": lessons = timetable[3] elif day=="Friday": lessons = timetable[4] else: print("Not a valid week day!") #OUTPUT print("Your lessons on this day:") for lesson in lessons: print(lesson)
#INPUT subject= input("Enter Subject:") #PROCESS count=0 for day in range(0,5): for period in range(0,5): if timetable[day][period] == subject: count+=1 #OUTPUT if count>1: print("You have " + str(count) + " " + subject + " lessons per week.") else: print("You have " + str(count) + " " + subject + " lesson per week.")
Extension Task
Create three different functions for each of the three challenges and add a menu structure to your code to let the user decide what information to retrieve from their timetable.
Solution...
The solution for this challenge is available to full members!Find out how to become a member:
➤ Members' Area