Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to specify a variable type in Python

Onyejiaku Theophilus Chidalu

Overview

In this shot, we’ll learn how to convert a variable value from one data type to another.

Python casting

We can convert a variable value from one data type to another data type by casting. Python, being an object-oriented programming language, uses classes to define data types. Casting can be done in Python with constructor functions. The table below shows a list of some constructor functions in Python.

Constructor function Description Example
str() String data type constructor that helps construct a string from various data types that can include float literals, integer literals, strings, etc. string(2)will become '2'
int() Integer data type constructor that helps construct an integer from various data types including float literals, string literals, and integer literals. int(3.2) will become 3
float() Float data type constructor that helps construct float numbers from string literals, integer literals, and float literals. float(3) will become 3.0

Let’s see some examples of how to specify the data type of a variable value.

Example 1

Let’s look at how to specify a string type.

# creating the variables and specifying the data type we want as a value
x = str(2)   
y = str(5.8) 
z = str("3") 

# returning our output
print("The value of str(2) is: ", x)
print("The value of str(5.8) is: ", y)
print('''The value of str("3") is:''', z) 
Using the str() constructor

Example 2

Let’s look at how to specify an integer type.

# creating the variables and specifying the data type we want as a value
x = int(2)   
y = int(5.8) 
z = int("3") 

# returning our output
print("The value of int(2) is: ", x)
print("The value of int(5.8) is: ", y)
print('''The value of int("3") is:''', z)
Using the int() constructor

Example 3

Let’s look at how to specify a float type.

# creating the variables and specifying the data type we want as a value
x = float(2)   
y = float(5.8) 
z = float("3") 

# returning our output
print("The value of float(2) is: ", x)
print("The value of float(5.8) is: ", y)
print('''The value of float("3") is:''', z)
Using the float() constructor

Summary

To change or convert the variable value of any data type to another data type, we must use the int(), float() or str() constructor functions.

RELATED TAGS

python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring