06.09.2021 Views

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

24 Functions<br />

3.2 Type conversion<br />

<strong>Python</strong> provides a collection of built-in functions that convert values from one<br />

type <strong>to</strong> another. The int function takes any value and converts it <strong>to</strong> an integer,<br />

if possible, or complains otherwise:<br />

>>> int("32")<br />

32<br />

>>> int("Hello")<br />

ValueError: invalid literal for int(): Hello<br />

int can also convert floating-point values <strong>to</strong> integers, but remember that it truncates<br />

the fractional part:<br />

>>> int(3.99999)<br />

3<br />

>>> int(-2.3)<br />

-2<br />

The float function converts integers and strings <strong>to</strong> floating-point numbers:<br />

>>> float(32)<br />

32.0<br />

>>> float("3.14159")<br />

3.14159<br />

Finally, the str function converts <strong>to</strong> type string:<br />

>>> str(32)<br />

’32’<br />

>>> str(3.14149)<br />

’3.14149’<br />

It may seem odd that <strong>Python</strong> distinguishes the integer value 1 from the floatingpoint<br />

value 1.0. They may represent the same number, but they belong <strong>to</strong> different<br />

types. The reason is that they are represented differently inside the computer.<br />

3.3 Type coercion<br />

Now that we can convert between types, we have another way <strong>to</strong> deal <strong>with</strong> integer<br />

division. Returning <strong>to</strong> the example from the previous chapter, suppose we want <strong>to</strong><br />

calculate the fraction of an hour that has elapsed. The most obvious expression,<br />

minute / 60, does integer arithmetic, so the result is always 0, even at 59 minutes<br />

past the hour.<br />

One solution is <strong>to</strong> convert minute <strong>to</strong> floating-point and do floating-point division:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!