Python Variable Types

0
340
python-variable-types-programming-the data-life

There are 4 main Python variable types:

1. INTEGER

Integer is a Python variable type that is mainly used for counting. They are whole numbers (e.g. 1, 2, 3, 4, 5).  One way to tell if a number is a integer is that it usually doesn’t have a decimal places.

Remember that these variables take up less space or memory compared to other numerical variable which is float.

Example (*in Python 3):

Input:

x = 4
print(x)
type(x)

Output:

2
int

2. FLOAT (LONGS/DOUBLES)

Float  Python variable type are real numbers. Just remember they are number with a decimal point (e.g. 1.2, 2.0, 3.5)

Example (*in Python 3):

Input:

x = 4.0
print(x)
type(x)

Output:

4.0
float

When dividing numbers in Python 2, it is important to use floats. 

Example (*Python 2):

Input: 5/2

Output:2

The output should be 2. 5. But In Python 2 if you just divide without declaring either number as a float it will remove the decimal point. This is known as classic division. So the remedy is to declare either 5 or 2 as a float.

Example (*Python 2):

Input: 5.0/2

Output:2.5 

#the following will also give the same output 5/2.0 or float(5)/2

You don’t need to worry about declaring floats for division in Python 3.

3. STRING

Strings is a variable type that stores  letters, words, numbers and different characters. To simplify think of it as a phrase. The code for a string starts and ends with either ' or "

Example (*Python 3):

Input:

b= 'This is a string %$ 9 7c'

print(b)

type(b)

Output:

This is a string %$ 9 7c

str

4. BOOLEAN (LOGICAL)

Boolean are True or False variables.  Usually these variables are the output of conditional statements. But we can directly declare them as well.

Example 1 (*Python 3):

Input:

c= False

print(c)

type(c)

Output:

False

bool

Example 2 (*Python 3):

Input:

d= 5>4

print(d)

type(d)

Output:

True

bool

For more details visit the official Python documentation:

https://docs.python.org/2/tutorial/introduction.html

Also you may check out a related post on how to perform operations on these different Python variable types.

LEAVE A REPLY

Please enter your comment!
Please enter your name here