2009/07/03

Variables - Python

Variables. Variables are only names or you can say boxes having value in them, for example X = 1, where X is a variable having the value 1, X = 10, X is a variable having value 10, another thing variables do not change but their value can change, for example X = 1+2 will change the value of X to 3 and X will become X = 3.

So here we will learn how to work with variables in miss Python programming.

How to make a variable and assign them value, for example I want to make X with value 10, then I will do the following work in python shell.(python shell, where we type commands and get output instantly after typing commands)
command is X a space then equal to symbol then a space and the value.

>>>  x = 10  <-- press enter after typing this, and It will save 10 into variable X. Then you can use X anywhere in maths programming.
Now our X has the value of 10 then we can use the X by following ways
>>> X + 5  <-- Our input (input is our/user instruction given to the computer), will add X into 5, actually will do nothing with X but with the value of X.
15             <-- output

Lets use power(exponent) thing here, X exponent 3 give us output of 10 exponent 3, because the value of our X was 10.
>>> X*3
30

Remember that our variables are case sensitive, I mean capital X and small x are different and can be used at a same time in same program.  
>>> x = 5

>>> x + X  <-- it will do addition with the stored values of small x which was 5 and with capital X which was 10.
15

We can store more than one variable same time.
>>>
y = 50

>>> y + x
55

We can also take the values of variables from the user using input function,

>>> a = input ("Enter the value of a: ")
Enter the value of a: 
>>> b = input ("type the value of b: ")
type the value of b: 

We can also get value of variable from user without any message
>>> c = input ()
                          <-- this empty space as output will come, it is because we did not include any message like Enter your number, Type the value of c etc. but it will also save value of c even without message.
>>> c = input ("Type the value of c: ")
Type the value of c: 

Practice makes a man perfect :) try more different variables play with variables in your python now for your practice.

1 comment:

Share post using share buttons or leave a comment