Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics Functions and Looping Returning Values

Abdullah Jassim
Abdullah Jassim
4,551 Points

I figured out the answer but I dont know why my previous answer was wrong and the latest one is correct. Guidance?

The below is my code. I get the error cost_per_person

def split_check(invoice, no_of_people):
    cost_per_person = invoice / no_of_people
    return cost_per_person


invoice = int(input("Whats the bill total? "))
no_of_people = int(input("How many people were at dinner? "))
split_check(invoice, no_of_people)
print("Each one owes ", cost_per_person)

Correct answer:

def split_check(invoice, no_of_people):
    cost_per_person = invoice / no_of_people
    return cost_per_person

bill = int(input("Whats the bill total? "))
people = int(input("How many people were at dinner? "))
per_person = split_check(bill, people)
print("Each one owes ", per_person)

2 Answers

Viraj Deshaval
Viraj Deshaval
4,874 Points

The analogy works as below: When you call a function, you will pass arguments once you pass arguments you can process stuff passed within the function parameters and then return something whatever is processed.

Once you return anything using function it will return anything to the Caller means if variable is calling a function then return value is assigned to the variable and if you simply call it using nothing then function will return value to the console but don't do anything.

So coming to your code you returned value and tried to access the variable inside the function which you can't as the scope of the variable is limited to the function only and because of which it showed you error.

Hope this helps.

JEFF CHAI
JEFF CHAI
7,564 Points
split_check(invoice, no_of_people)

This line is calling on split_check function which the function have a return value. You need to assign the return value into a variable or use it in another function

cost_per_person=split_check(invoice, no_of_people)

or

print("Each one owes ", split_check(invoice, no_of_people))