Editor

Prices in Cents

Advanced · Stretch · from Python Variables and Data Types: A Practical Introduction

From the lesson: Python Variables and Data Types: A Practical Introduction

Imagine you're shipping a package. You fill out a label that asks for the weight. You write "heavy" instead of a number. The shipping system crashes - it can't calculate a price from the word "heavy."

Read the lesson

Shops keep money as whole cents, because a decimal number is not always stored exactly (remember 0.1 + 0.2). Write a function to_cents(price_text) that takes a price written as text and returns the number of cents as an int.

to_cents("12.34")   # 1234
to_cents("5")       # 500
to_cents("-2.50")   # -250 (a refund)

The text may have spaces around it. The def line is written for you: put your code under it, indented four spaces, and end with return and your answer. Check calls to_cents() with its own prices, some of them hidden. (Functions get their own lesson later.)

def to_cents(price_text):
pass
Solution unlocks after your first Check

What Check runs

Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.

RunsExpected output
to_cents("12.34")1234
to_cents("5")500

More Variables and Data Types exercises

All Python exercises · 50 practice problems · Python Fundamentals quiz