Py01: Variable

Variable gives the program the ability to remember data and use them later in the program process. The value of a variable can change when the program is running. Variables are used in operations such as arithmetic and also pass as argument to functions to be processed.

Introduction

A variable is a memory location to store data. Data type reserves memory for the variable to store data. Standard data types supported in python programming are number, string, list, tuple, set, and dictionary.

Declaring Variable

Declaring a variable is the first step in using a variable. It gives name for the variable and type of data. In python, Data types are determined by the value assigned to the variable. The variable is declared the moment value is assigned to it and there is no declaration statement like Java.

var1 = 3
print(var1)

In the example above, var1 is an integer because the assigned value 3 is an integer. In java, we have to write int var1 = 3; and so on, python don't have to.

Naming the variable

Variable names can only contain letters, number, and underscore. Some rules to remember:

  • They cannot start with numbers. 
  • A variable name can contain space. 
  • Keywords or built-in function names cannot be used as a variable name.

It encouraged to give the variable name that are self-descriptive and concise. A variable name containing two or more words is separated with an underscore or uses a camel case. For example

annual_income = 300000  # using underscore
annualIncome = 350000   # using camel case

Changing variable type

The value of a variable can change during program execution. In python, the same variable can change its data type when a new value from a different data type is assigned. For example,

var1 = 3
var1 = "Hello"
print(var1)

In the first line, the data type var1 is an integer. In the second line, the data type changes to string type when a string literal is assigned to it.

The reference to the variable can be deleted using the del statement.

del var1

Constants

Constant is memory location similar to variables to store data, but their value won’t change during program execution. 

Python does not support the constant.  To avoid confusion and to help us treat it as a constant name the variable using all caps, for example:

PI_VALUE = 3.142

The interpreter does not prevent accidental value changes, the programmer uses the all-caps name as a guide to preventing value modification when writing code.

A post by Cuber

Comments

Popular posts from this blog

Drawing Simple Pie Chart

VB.net connecting to SQL Server

VB.net