Game on! Let’s create the list of students.Due to the fact that we will make use of each student’s name a lot of time, we will first declare all students as variables before putting them in a list.
jake = "Jake" gerald = "Gerald" nat = "Nat" pius = "Pius" wendy = "Wendy" bill = "Bill" vanessa = "Vanessa" freda = "Freda" joan = "Joan" sandy = "Sandy" #student list STUDENTS = [jake, gerald, nat, pius, wendy, bill, vanessa, freda, joan, sandy]
Now create a function
display_students() that when called, will print out all students in a nice format. Use as little lines of code as possible. Do this before scrolling down. Don’t cheat yourself 😀 Try it before continuing!!
Okay here it is.
def display_students(): print "----STUDENTS----" print "''''''''''''''''" for student in STUDENTS: print studenta
Don’t worry if you did something different. As long as it prints all the students nicely, you’re good to go.
If a user inquires about a student that is not in our class (list), we should be able to tell easily. No need to keep writing code each time we want to do this validation. Create a function
is_student() that checks whether or not a student is in our class. The function should return
True if student exists and
False if not. As usual, don’t scroll down till you’re done writing yours!
Here you are 🙂
def is_student(student): return student in STUDENTS
I know this seems extremely simple and yet difficult to understand. (Especially if you’re indeed a newbie). Let’s talk about the
in keyword in python. As you may have already guessed, we use it to check whether or not an item is in a list or a character is in a string. E.g.
if 1 in [1,2,3,4]: print "it is there..." if "s" in "test": print "s is in test"
So now you know what
in does. In our
is_student() function, we accept an argument student (the student you’re checking) and return the result of the expression
student in STUDENT which is either True or False.
Now we can call that function and use it in conditions. Example:
if is_student('Pius'): do something… You get it right? Good! Let me know if you don’t by commenting 🙂
In our next lesson, we will create our subject list, create a few more functions and give marks to our students for the first trimester.
- create a dictionary called database
- the dictionary should have three key : value pairs. Each key is a string, the name of a person. Each value is a list of
Floats representing the marks they got in a test.
- print out the names and the marks for each student nicely.