Written by:
Javier Leyva Seiglie
In Python the double equal sign is used to compare two values. You can use it to check if two values are equal, as you can see in the following example:
1x = 5 2y= '5' 3z = 5 4 5print(x==y) 6#output -> false 7 8print(x==z) 9#output -> true
==
)To compare if two values are equal, you can use the Double equal sign, here is a quick example of how it works:
1x = 5 2y = '5' 3z = 5 4 5print(x==y) 6#output -> False 7 8print(x==z) 9#output -> True
In the example we have three different variables which values seems to be the same, but one of them y
has a different type (It's a string) so we can say it's different. When comparing if x
is equal to y
it returns False
because even though the value is the same, but the data type isn't. Then when comparing if x
is equal to z
, it returns True
as both have the same value and data type.
=
)The equal sign =
in Python (Only one equal sign), as in many other programming languages is used to assign a value, most commonly used to assign a value to a variable.
1# creating a variable and assigning a value with the = symbol 2x = "4Geeks!" 3print(x) #Output-> 4Geeks!
In the previous example, the equal sign =
is being used to assign "4Geeks!"
to the variable x
. Then when printing the value of x
we are confirming that we assigned it correctly.
The double equal sign operator can be used in conditions to check if two values are equal, here is an example:
name = input("What is your name?")
if name == "Rigoberto":
print("Hello Rigoberto welcome to your office at 4Geeks!")
else:
print("Only Rigoberto has access to this office.")
In the previous example, we are asking the user for its name and if it is equal to Rigoberto, we allow them to access the office with a good welcoming message.
Double equal sign (==
) can be used in for loops to check for a specific value in a list. On this example we will loop through a list of names and if the name we're looking for is found, we will print it.
1names = ["James", "Willy", "Jane", "Barbara", "Pete", "Julia"] 2favorite_name = "Jane" 3 4for x in range(len(arr)): 5 if arr[x] == favorite_name: 6 print(arr[x] + " at position " + str(x)) 7 #Output-> Jane at position 2
This time we'll be checking if we have something to eat (fruits, vegetables, etc...) in the fridge using a while loop!
1fridge_items = ['apple', 'banana', 'cherry', 'date'] 2food = 'banana' 3found = False 4position = 0 5 6while position < len(fridge_items): 7 if fridge_items[position] == food: 8 found = True 9 print("We have " + food + " in the fridge. Enjoy!") 10 break 11 position++
On this example we have a list of fridge_items and a food we are looking for in the list. If the food is found, then we print a message and break the while loop.
Visit 4Geeks to learn about Python and solutions to your possible errors. Hope you enjoy the reading and keep on the Geek side!