Python Variables and Data Types

Python is not statically typed, it is a complete OOP (Object Oriented Programming) language. Every variable in python is considered as an object. There is no need to declare variables or their data type before using them. This tutorials covers some basic types of variables.

Data Types in Python

  1. Numeric
  2. Strings
  3. Complex

Numeric

Numeric data type in python is used to hold numeric values like integer, a floating point number and complex number.

How to define an integer?

Syntax:

num = 7
print(num)

Output:

7

How to define a floating point number?

For defining a floating point number use the following syntax

Syntax:

floating_number = 10.00
floating_number = float(10)
print(floating_number)

Output:

10.00

Strings

Strings is a sequence of characters. Generally a string is represented in single or double quotes. Python supports unicode characters.

How to define a string?

To define a string use the following syntax

Syntax:

helloString = 'Halo'
helloString1 = "Halo"
print(helloString)
print(helloString1)

Output:

Halo
Halo
Both ways of defining string outputs the same thing but the advantage of using double quotes is that we can include apostrophes in the string whereas this would terminate the string if we use single quotes.
helloString = "I am Master Chief. Don't worry about apostrophes."
print(helloString)

Output:

I am Master Chief. Don't worry about apostrophes.

Complex

Python also provides support for defining complex numbers along with real numbers. To use complex numbers we have to include cmath module in our program.

A complex number is represented in the form a + bi. We can convert two real numbers into complex number by using complex(a,b) which takes two arguments a and b. To access the real and imaginary parts in the complex number real() and imag() functions are used respectively.
# Aim: To denote the working of complex(), real() and imag() functions.

# importing cmath module to use complex numbers

import cmath

# defining two integer variables
a=2
b=3

# creating a complex number
C=complex(a,b)


print("Complex number is " + str(C))
print("Real part of complex number is " + str(C.real))
print("Imaginary part of complex number is " + str(C.imag))

Output:

Complex number is (2+3j)
Real part of complex number is 2.0
Imaginary part of complex number is 3.0