python logo

Tag: casting

python cast

Python determines the datatype automatically, to illustrate:

x = 3
y = "text"

It finds x is of type integer and y of type string.

Functions accept a certain datatype. For example, print only accepts the string datatype.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Datatypes casting

If you want to print numbers you will often need casting.

In this example below we want to print two numbers, one whole number (integer) and one floating point number.

x = 3
y = 2.15315315313532

print("We have defined two numbers,")
print("x = " + str(x))
print("y = " + str(y))

We cast the variable x (integer) and the variable y (float) to a string using the str() function.

What if we have text that we want to store as number? We will have to cast again.

a = "135.31421"
b = "133.1112223"

c = float(a) + float(b)

In the example above we cast two variables with the datatype string to the datatype float.

Conversion functions

To convert between datatypes you can use:

Download Python Exercises

Copyright © 2015 - 2023 - Pythonspot.  | Cookie policy | Terms of use | Privacy policy
Function Description
int(x) Converts x to an integer
long(x) Converts x to a long integer
float(x) Converts x to a floating point number
str(x) Converts x to an string. x can be of the type float. integer or long.
hex(x) Converts x integer to a hexadecimal string
chr(x) Converts x integer to a character
ord(x) Converts character x to an integer