 Computer Science

# Values and expressions

Variables reference values. For example:

number = 5

We would say that the variable number references the value 5.

Functions return values. For example:

def say_hello():
return 'hello'

This function always returns the value "hello".

An expression is a recipe for getting a value. If we have the following:

3 + 5

Then 3 + 5 is an expression, which Python calculates to be equal to 8.

When a value is needed but an expression is provided, the expression is evaluated to get a value. For example:

number = 3 + 5

Here, Python needs a value to assign to the variable called number. It adds 3 + 5 to get the value 8, and now is able to assign the value 8 to number.

Here is another example:

def add(a, b):
return a + b

number = add(3, 5)

Here, Python needs to call the add() function to figure out what value to assign number. It evaluates a + b to get the value to return, in this case calculating 8. Once it encounters the return statement, it is able to return 8 and then set number = 8.

## Example

Let’s write a script with multiple functions in it:


return number + 7

def is_big(number):
return number > 10

def make_smaller(number):
if is_big(number):
return number - 10
else:
return number - 1

def main(number):
number = make_smaller(number)
print(number)

number = 7
main(number)

We define four functions, each that does some calculation on a number. We then set number = 7 and call the main() function, passing it number as its parameter.

The main() function calls the add_seven() function, which returns 7 + 7, or 14, so number is temporarily set to 14.

Next, the main() function calls make_smaller(), giving it number, which is now 14. The make_smaller() function calls is_big() to determine if the number is considered “big” (it is larger than 10). Since it is big, the make_smaller() function will subtract 10 and return the value 4. This causes main() to change the value of number from 14 to 4.

Finally, main() prints the value of number, so it prints 4`.