Tuesday, May 24, 2011

Variables

Here I’m posting explanations and examples related to the variables used in Python. We all are familiar with variables in C programming language. Python variables are almost similar to that.

The variables are used to store values. Example for values are 1, “Hello World”, 23.67 etc. The basic types for variables are integer, string and floating point.

The print statement also works for integers. If you are not sure what type a value has, the interpreter can tell you. This two are illustrated below.


It explains the 3 basic variable types. You may have noticed in the above picture that the type of values ‘17’ and ‘2.9’ are string. It’s because they are in quotation marks like strings.

Have a look at the below picture.


It’s a surprising output. Isn’t it? It’s nothing but Python interprets 1,000,000 as a comma-separated sequence of integers, which it prints with spaces between.

Now take a look at how we can declare variables by just assigning the values.


The first assigns a string to a new variable named message; the second gives the integer 17 to n; the third assigns the approximate value of π to pi. We can also print the values or type of the variables using the print statement.

Programmers generally choose names for their variables that are meaningful. Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter. The underscore character can appear in a name.


In the above picture, 76trombones is illegal because it does not begin with a letter. more@ is illegal because it contains an illegal character, @. Can you guess why class is an invalid variable name? It’s nothing but class is a keyword. Keywords are the tokens that have specified meaning in that programming language and it cannot be used as a user defined variable name. Python have 31 keywords.

and,del,from,not,while,as,elif,global,or,with,assert,else,if,pass,yield,break,except,import,print,class,exec,in,raise,continue,finally,is,return,def,for,lambda,try.

An interesting example of variable nature in Python will be illustrated to you in the next post.

Thanks

AJAY

No comments:

Post a Comment

Comments with advertisement links will not be published. Thank you.