Type conversion in Python

An important part of any programming language are data types. In this situation, it does not matter whether you are designing a global project or write a small web application. Knowledge of data types, and the ability to work with them is mandatory for successful writing code. After reading this article you will learn how to convert the data types in the Python programming language.

The three basic data types in Python are a number of - int, string - str, real numbers - float. Often, you want to convert one data type to another. Suppose that you need to add two numbers, but they are stored only in the form of lines, as entered from the keyboard. To convert the type and getting the result as a number, you can use the built-in function float ( "string / integer"). Conversion types represented in the following examples:

int ( "3") - row transformation "3" to an integer;

float (2) - convert an integer to a real number;

int ( "7") + int ( "5") - conversion of strings to integers, followed by addition.

The examples clearly show the syntax for built-in functions. It is important to keep track of exactly what you want to convert. String int ( "gfdfd") can cause the error as the function argument is not a number.

It was previously presented only general examples. Now it is necessary to consider the data type conversion in real programs. Suppose you're an ordinary calculator. What needs to be done to realize the addition of two numbers. First we need to allow the user to enter two numbers from the keyboard. To do this, conveniently suitable built-in function input. The syntax of the input function the following: input ( "Offer to enter a number or a string", variable (can be omitted) variable). The important point is that the input information will be provided in the form of string. What we need to convert the string to a number:

float (input ( "Please enter your number")

It now remains only to add the operation of addition:

float (input ( "Enter the first number to add:") + float (input ( "Input your second number:")

We can only deduce the result of addition (or another arithmetic operation program) on the screen via the print function.


3 March 2017

You may be interested in

17 October 2023
Installing MikroTik RouterOS on a VPS-N server running ...
RouterOS is the operating system on which MikroTik equipment runs. RouterOS can also be installed on ...
27 September 2023
Your own VPN Outline? Easily!
We are sharing the easiest way to install VPN Outline using ubuntu 20.04 as an example.