Python Tutorial Series - Variables

In Python, variable names must start with a letter or underscore, are case sensitive and each word should be separated by an underscore. Variable names may only contain letters, numbers and underscores.

Python automatically interprets what type a variable is. A variable declaration is just:

diameter = 13  # An integer
radius = 6.5   # A float
shape = "Circle" # A string
complex_var = 2j  # Complex

Notice, there are not any semi-colons at the end of the declaration as in other programming languages.

Assigning a variable a different value with a different type than it's previous definition, changes the variable's type.

radius = 6  # Radius is now an integer

The type of a variable can be found by:

type(radius)

A variable may be displayed on the screen by using the built in print function:

print(type(radius))

To convert a variable of one type to another type, cast the variable. Examples:

str_cast = str(diameter)
int_cast = int(shape)
float_cast = float(diameter)

  

More Python








Comments