Tuesday, September 25, 2018

Simple data types and variables in Python 2

The Assignment Operator

Like other programming languages the '=' sign has a different meaning from the = sign we learned in Math. In programming, the = sign is known as an assignment operator. It means we are assigning the value on the right side of the = sign to the variable on the left. 

So what does user_id = 1001 means? It means the variable user_id has been assigned a value of 1001.
Now again if I write user_id = 1002, the variable has been assigned a new value of 1002.

The following program would make it easier for us to understand.


user_id = 1001

print (user_id)


user_id = 1002

print (user_id)

run this program and see the output. 


We assigned two values to the variable user_id and last print function printed the latest assignment 1002 there by over writing the first value 1001.

Now try to guess the output of this program-

a = 3
b = 6
a = b
print ("a = ", a)
print ("b = ", b)

The output should be -

a = 6
b = 6

what if in the program I change the assignment a = b to b = a. Now you should get this right.

Try to do multiple assignment, say a=b=c= 20 , any guess what will be the output?


Basic operators in Python

We can also perform the usual mathematical operations on variables  with the help of basic operators in Python. These are +, -, *, /, //, % and ** which represent addition, subtraction, multiplication, division, floor division, modulus and exponent respectively.

Example:

Suppose a = 5, b = 2

1. Addition:

a + b = 7

2. Subtraction:

a - b = 3

3. Multiplication:

a * b= 10

4. Division:

a / b= 2.5 

5. Floor Division:

a // b = 2 (rounds down the answer to the nearest whole number)

6. Modulus:

a % b = 1 (gives the remainder when 5 is divided by 2)

7. Exponent:

a ** b = 25 (5 to the power of 2)

Additional Assignment Operators

Here are a few more assignment operators in Python like most programming languages. These include operators like +=, -= and *=.

Now let's see their functioning. Suppose we have the variable v, with an initial value of 10. If we want to increment v by 2, we can write v = v + 2

The program will first evaluate the expression on the right (v + 2) and assign the answer to the left. So eventually the statement above becomes x = 12.

Instead of writing v = v + 2, we can also write v += 2 to express the same meaning. The += sign is actually a shorthand that combines the assignment sign with the addition operator. Hence, v += 2 simply means v = v + 2.

Similarly, if we want to do a subtraction, we can write v = v - 2 or v -= 2. 

The same works for all the 7 operators mentioned in the section above.

Try to implement these operators in a program and see if you get the desired results. The main utility of these operators will be seen later when we'll study about conditional statements.


Share:

0 comments:

Post a Comment