Python for beginner - GPA Calculator Sample
Bài đăng này đã không được cập nhật trong 3 năm
Why learn Python?
Python is a general-purpose, versatile and popular programming language. It's great as a first language because it is concise and easy to read, and it is also a good language to have in any programmer's stack as it can be used for everything from web development to software development and scientific applications.
Learn by sample code
Beside self-training the basic concept on Python such as: variable, class, data type, ... To give you guys the first look on what Python look like. I wanna show you a traditional sample code which help student calculate their GPA, take a look!
Show me the code!
A. Create dictionaries
- Create three dictionaries:
lloyd
,alice
, andtyler
. - Give each dictionary the keys "name", "homework", "quizzes", and "tests".
- Now fill out your
lloyd
,alice
andtyler
dictionary with the appropriate scores.
- Create a list called students that contains
lloyd
,alice
, andtyler
. - For each
student
in yourstudents
list, print out thatstudent
's data, as follows:
B. Create function average
- Define a function called
average
that has one argument,numbers
. - Inside that function, call the built-in
sum()
function with thenumbers
list as a parameter. Store the result in a variable calledtotal
. - Use
float()
to converttotal
and store the result intotal
. - Divide
total
by the length of thenumbers
list. Use the built-inlen()
function to calculate that. - Return that result.
C. Create function get_average
- Define a function called
get_average
that takes one argument calledstudent
. - Make a variable
homework
that stores theaverage()
ofstudent["homework"]
. - Repeat step 2 for "quizzes" and "tests".
- Multiply the 3 averages by their weights and return the sum of those three. Homework is 10%, quizzes are 30% and tests are 60%.
D. Create function get_letter_grade
-
Define a new function called get_letter_grade that has one argument called score. Expect score to be a number.
-
Inside your function, test score using a chain of if: / elif: / else: statements, like so:
- If score is 90 or above: return "A" - Else if score is 80 or above: return "B" - Else if score is 70 or above: return "C" - Else if score is 60 or above: return "D" - Otherwise: return "F"
E. Create function get_class_average
- Define a function called
get_class_average
that has one argumentstudents
. You can expectstudents
to be a list containing your three students. - First, make an empty list called
results
. - For each
student
item in theclass
list, calculateget_average(student)
and then callresults.append()
with that result. - Finally, return the result of calling
average()
with results. - Finally,
print
out the result of callingget_class_average
with yourstudents
list. Yourstudents
should be[lloyd, alice, tyler]
. - Then, print the result of
get_letter_grade
for the class's average.
And the result
All rights reserved