Hello, I am confused with my code, how can I return the last result of my for loop. Thank you
# Write your first_three_multiples function here
def first_three_multiples(num):
for i in range(1,4):
result = num * i
print(result)
return result
first_three_multiples(10)
# should print 10, 20, 30, and return 30
first_three_multiples(0)
# should print 0, 0, 0, and return 0
You are returning the last result of the loop. Once the loop finishes, the variable result will still have the last value assigned to it. You are returning that result.
If you want to print the returned value, you can amend your function calls to:
print(first_three_multiples(10))
# Output:
10 #
20 # These will be printed by the loop in the function
30 #
30 # <- This will be printed by the print statement outside the function.
Thank you for your explanation. I have a question. Is it possible to not change the function call (keep the original code, without the “print”) and instead modify the code within the function definition. Thank you.
The real question is: What do you want to happen within the function?
If you want to print the first three multiples and return the final multiple, then your function in the original post already accomplishes this.
If you want to print the final value again, then you could do:
def first_three_multiples(num):
for i in range(1,4):
result = num * i
print(result)
print(result)
return result
first_three_multiples(10)
If you are trying to complete an exercise/challenge, then you need to meet the specifications in the instructions exactly. If the instructions specify that the first three multiples are to be printed with the final multiple being returned, then you have already met the specs in the function you wrote in the original post. If the instructions want something else, then you need to mention what you are trying to accomplish. That will dictate how your function should be written.