Sign up for a school club.
Select the button below to open the Python program in a new window. Run the program and read the lines of code to see if you can understand how it works. It will be helpful to arrange your display so that you can have this browser window on one side of the screen and the code on the other.
Watch this video to learn about the new concepts shown in the program:
Questions to think about with this program to check your understanding:
What is the purpose of the iteration in line 18?
for student in file:
To read in the students line by line from the beginning to the end of the file.
Why is `”a”` used instead of `”w”` in line 9 to open the file?
file = open(programming + “.txt”, “a”)
New students need to be added to the file. Using “a” means that new data is appended (added to the end) and does not over-write existing data in the file.
Change the program so that it:
1. Sign up
2. Show students
Enter choice: 1
Clubs available: programming, football or drama
Enter the name of the club: programming
Enter your name to sign up for the club: Craig
You have been signed up Craig
1. Sign up
2. Show students
Enter choice: 1
Clubs available: programming, football or drama
Enter the name of the club: football
Enter your name to sign up for the club: Dave
You have been signed up Dave
1. Sign up
2. Show students
Enter choice: 2
Clubs available: programming, football or drama
Enter the name of the club: football
Students that signed up for the football club:
Dave
Sam
Mo
Use these resources to learn about new commands for this level and to help you meet the success criteria.
x = y.readline()
x is assigned to be a single line read from file pointer y. This will include the end of line character code.
for x in y
Can be used to iterate through file pointer y a line at time. The variable x will contain a single line of data read from the file in each iteration. Note there is no need to use the readline method with this approach.
Data in text files is often stored in comma separated value (CSV) format. E.g.
“red”,255,0,0
“green”,0,255,0
“blue”,0,0,255
A single line is one record with each field of the record separated with a comma. Using the data above and the following code:
record = file.readline()
record = record.strip()
fields = record.split(“,”)
Would result in:
fields[0] is “red”
fields[1] is 255
fields[2] is 0
fields[3] is 0
Check your program works by running it several times, adding students to each club and outputting the results.
Note, the program will crash if you attempt to output a club that has no students. You will learn how to stop this happening in the next program.