livepython.net

138. Fix the NameError in a Python Function

EasyScope

Overview

A variable made inside a function is local: return it to use it outside.

Problem Statement

The program in the editor should add up three prices and print the total with two decimals. Instead, it stops with:

NameError: name 'total' is not defined

Fix it so the function returns the total, and the main program stores and prints it. Keep the function cart_total(a, b, c).

The program uses input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Input

One value per line: three prices, maybe with decimals. Example:

10
20.5
4.25

Output

The output for that example:

Total: 34.75

The tests try 3 different inputs.

Learn this firstChapter 15 · Python Variable Scope, Docstrings and Good Habits
solution.py
def cart_total(a, b, c):
    total = a + b + c


price1 = float(input())
price2 = float(input())
price3 = float(input())
cart_total(price1, price2, price3)
print(f"Total: {total:.2f}")

EXPECTED OUTPUT

1Total: 34.75

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.