Print those grades!


#1


https://www.codecademy.com/en/courses/python-intermediate-en-7mgOa/0/2?curriculum_id=4f89dab3d788890003000096

This is my code, which does work. But I'm wondering what does the "print_grades(grades)" do exactly? I thought by ending the loop with "print i" it would already print the list in a vertical format. Why do I have to call the function again?

Thanks for answering!

def print_grades(grades):
    for grade in grades: 
        print i 
    print_grades(grades)

#2

The indentation is actually correct! I'm not sure why it shows up like this after posting it.


#3

If you click the button to edit your code you will see that it is now between the code fences that the template supplied -- that is how you format code in these forums.

Do you really have print_grades(grades) indented like that -- that places it inside the function instead of after it.

There are two things going on with functions.
- First, you define them, they just sit there doing nothing.
- Then you call them, that's when their code runs.

This is defining the function:

def print_grades(grades):
    for grade in grades: 
        print i

This is calling the function:

print_grades(grades)

#4

Oh thank you! When do I need to call it? What is the difference with just typing the function name and adding a "return?" Also, the earlier exercises did not have to call the functions in this way. What are the cases that I need to call the function this way?

Thank you !


#5

Anytime that you want to run the code in the function you must call it. If you never call it then it never runs.

If you give me the link to a past exercise where you did not have to call the function I will have a look at that.


#6

In the earlier exercises, I believed I called the function using "return." What is the difference between using"return" and by typing the function name (like typing grades(average) without the "return")?
Thanks for answering my questions!


#7

Typing a function name runs the function.

A return statement exits the function and sends you back to where you called the function from.


#8

Thanks so much! I understand now :slight_smile:


#9

That code runs? You are iterating over grade in grades, but then printing I. I is undefined.

I would think it would require.

for grade in grades
-print grades

or

for i in grades
-print i


#10

Yes sorry. I actually wrote "for i in grades print i." Made a mistake in the post. Thanks for pointing it out.


#12