Type Conversion in Python

This tutorial will teach you about type conversion in Python as well as some useful type conversion functions.

The input() function is used to obtain user input. As an example:

value = input('Enter a value:')

When you run this code, the Terminal will prompt you for the following input:

Enter a value:

If you enter a value, such as a number, the programme will display that value back to you:

Enter a value:100

The input() function, on the other hand, returns a string rather than an integer.

The example below prompts you to enter two input values: net price and tax rate. Following that, it computes the net price and displays the outcome on the screen:

price = input('Enter the price ($):')
tax = input('Enter the tax rate (%):')

net_price = price * tax / 100

print(f'The net price is ${net_price}')

When you run the program and enter the following numbers:

Enter the price ($):100
Enter the tax rate (%):10

you will receive the following error:

Traceback (most recent call last):
  File "app.py", line 4, in <module>
    net_price = price * tax / 100
TypeError: can't multiply sequence by non-int of type 'str'

The arithmetic operator (+) can’t be used on the input values because they’re strings.

Before completing calculations, you must convert the strings to numbers.

The int() function is used to convert strings to numbers. The int() function, more specifically, converts a text to an integer.

The int() function is used to transform texts into numbers in the following example:

price = input('Enter the price ($):')
tax = input('Enter the tax rate (%):')

net_price = int(price) * int(tax) / 100
print(f'The net price is ${net_price}')

You can verify that the software works by running it and entering some values:

Enter the price ($):100
Enter the tax rate (%):10
The net price is $ 10.0

Other functions for type conversion

Other type conversion functions are supported by Python in addition to the int(str) procedures. For the time being, the most important ones are as follows:

Convert a string to a floating-point number with float(str).
bool(val) – returns a boolean value of True or False.
Return the string representation of a value with str(val).

Getting the type of a value

The type(value) function is used to determine the type of a value. For instance:

>>> type(100)
<class 'int'>
>>> type(2.0)
<class 'float'>
>>> type('Hello')
<class 'str'>
>>> type(True)
<class 'bool'>

As the output clearly demonstrates:

The type of number 100 is int.
Float is the kind of number 2.0.
The type of the string ‘Hello’ is str.
The type of the True value is bool.
The class keyword appears in front of each type. For the time being, it is unimportant. Later on, you’ll find out more about the class.

%d bloggers like this: