Chapter 2 Using Python as a Calculator

2.3 Type conversion functions

Sometimes it is necessary to convert values from one type to another. Python provides a few simple functions that do that. The functions int, float and str will (attempt to) convert their arguments into types int, float and str respectively. These are called type conversion functions.

The int function can take a floating point number or a string, and turn it into an int. For floating point numbers, it discards the decimal portion of the number - a process called truncation towards zero on the number line. Let’s see this in action:

The last case shows that a string has to be a syntactically legal number, otherwise you’ll get one of those pesky runtime errors. Modify the example by deleting the bottles and rerun the program. You should see the integer 23.

The type converter float can turn an integer, a float, or a syntactically legal string into a float.

The type converter str turns its argument into a string. Remember that when we print a string, the quotes are removed. However, if we print the type, it is shown as <class ‘str’>

Check your understanding

© Copyright 2024 GS Ng.

Next Section - 2.4 Simple Arithmetics