Python Lessons – 1.8 Type conversion

Python Lessons - 1.8 Type conversion

Type Conversion

It often happens (much more than we realize) that in the lines of code to perform operations between values ​​of different types.

You have already seen this between integers and floats. In fact the whole numbers were implicitly converted into float by the interpreter and then carried out the operation. In this case we speak of implicit conversions.

In reality it is advisable (as long as we can realize this) to always specify type conversions, so as to avoid sometimes unwanted results.

A very useful case is for example that of converting strings that report numbers in integers or float. This will be possible as long as the string is a number suitable for conversion.

To convert a string to integers, use the int () function, passing the string to be converted as a function argument. While using the float () function to convert a string to float.

You have seen some interesting operations on the strings. You combine both cases (operation on strings and numbers) to get really interesting cases.

>>> int( "3" * 3 ) - 100
233
>>> float( "3" + "." + "14" ) * 2
6.28

Numerical conversion in the input of values

The greatest utility of the numeric conversion of strings into numbers is precisely when we use the function input () within programs.

In fact, every time we enter a value following the input call () this will always be and univocally a string regardless if we have entered characters or numbers. So if we need a numeric value to be entered to perform, for example, a calculation, it will be necessary to perform the type conversion.

>>> a = input (" In che anno siamo? ")
In che anno siamo? 2016
>>> n = int(a) - 10
>>> print ("Dieci anni fa era il", n, "!")
Dieci anni fa era il 2006!

This simple program summarizes everything we’ve done so far. Furthermore there is another interesting case within the print function.

We used three arguments instead of one only. This means that the print function is able to make a string concatency. Also there was an implicit conversion of n from integer to string.

⇐ Go to Python Lesson 1.7 – Operations on Strings

Go to Python Lesson 1.9 – Variables ⇒

Leave a Reply