Hello everyone, in this tutorial you’ll see what’s the difference between = and == in python. Most of new programmers get confused with them.
Python = vs ==
= (assignment operator)
Well, in simple words, ‘=’ is an assignment operator which is used to assign a value (on right side) to a variable (on left side).
Example:
var_name = 10
here var_name is a variable name and 10 is the value to be assigned, we’re using ‘=’ to assign it.
Example Programs:
#example 1 n = 10 print("n = ", n)
Output:
n = 10
#example 2 n1 = 10 n2 = 20 sum = n1 + n2 print("sum = ", sum)
Output:
sum = 30
As in above program, we can also write an expression on the right side of ‘=’ . the result of that expression will be assigned to the variable on left side.
#example 3 n1,n2 = 10,20 print("n1 = " , n1) print("n2 = " , n2)
Output:
n1 = 10
n2 = 20
In python, we can also assign more than one value at once using commas.
#example 4 n = input("please enter your name:") print("name = " + n)
Output:
please enter your name : crazy programmer
name = crazy programmer
The value received by input() function will be assigned to variable ‘n’.
== (equal to operator)
“==” equal to operator is a relational operator just like “!=”, “<=”. It is used to compare the operands on both of its side. It returns a boolean value (true or false), when both operands are equal then it returns ‘true’ otherwise ‘false’. Mostly it is used in conditional statements.
Example Programs:
#example 1 n = 10 print(n == 12)
Output:
False
In above program, the operands on both side of ‘==’ will be compared with each other. If they are equal then program will print “True”, if not then it will print “False”. The output of above program will be ‘False’ because ‘n’ is not equal to ‘12’.
#example 2 name = input("enter your name:") if(name == "xyz"): print("login successful") else: print("login unsuccessful")
Output:
enter your name: xyz
login successful
In this program first user will enter a name then interpreter will check the condition. Inside the if statement we wrote ‘name == “xyz”’. If the name entered by user is ‘xyz’ then it will return ‘True’ otherwise ‘False’. In output window we’re entering ‘xyz’ as name then the ‘if’ will be true and will print “login successful”.
I hope your doubt has been cleared. If you have any problem related with this article then please comment below, we’ll reply as soon as possible.
The post Python = vs == appeared first on The Crazy Programmer.
from The Crazy Programmer https://www.thecrazyprogrammer.com/2018/02/python-equal-vs-double-equal.html
Comments
Post a Comment