Variables

Like other programming languages, there's no need to declare your variables first. In Python, just think of any name to give your variable and assign it a value. You can use that variable in your program. So, in Python, you can declare variables whenever you need them.

In Python, the value of a variable may change during the program execution, as well as the type. In the following line of code, we assign the value 100 to a variable:

n = 100
Here are assigning 100 to the variable n. Now, we are going to increase the value of n by 1:
>>> n = n + 1
>>> print(n)
101
>>>

The following is an example of a type of variable that can change during execution:

a = 50 # data type is implicitly set to integer
a = 50 + 9.50 # data type is changed to float
a = "Seventy" # and now it will be a string

Python takes care of the representation for the different data types; that is, each type of value gets stored in different memory locations. A variable will be a name to which we're going to assign a value:

>>> msg = 'And now for something completely different'
>>> a = 20
>>> pi = 3.1415926535897932

This example makes three assignments. The first assignment is a string assignment to the variable named msg. The second assignment is an integer assignment to the variable named a and the last assignment is a pi value assignment.

The type of a variable is the type of the value it refers to. Look at the following code:

>>> type(msg)
<type 'str'>
>>> type(a)
<type 'int'>
>>> type(pi)
<type 'float'>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset