Odin May |
This is a short description for the post which introduces it
In Python, Operators are special characters used to perform operations on objects. You can use all of the standard mathematics operators on int and float types such as multiplication( * ) division( / ) addition( + ) and subtraction( - ). There are more operators that I will discuss later in this post as well.
Common Operators
+ Addition
- Subtraction
/ Division
* Multiplication
** Exponent
< Less Than
> Greater Than
= Assignment Operator
== Equal to
<= Less than or equal to
>= Greater than or equal to
!= Not equal to
is Identity
in Containment
Operators are useful and versatile, for instance, you can use operators on strings as well as other objects, this can range from combining strings by adding them together to more clever uses like subtracting one date from another. Lets go over some operators you will be using frequently and how they operate on objects of different types. How an object will interact with an operator is defined by the object not the operator. This means adding a number and adding a string work differently, as does adding a list to another list. Later on when you are making your own objects this will be useful.
A library that leverages modifying operators is the datetime library which is a built in library in Python, meaning you don’t have to install anything else to use it. This library gives us Date and Time objects which can be added or subtracted to make for easy time handling in your code. Datetime will be covered in more depth in another post, here.
Now lets go over some of the operators and their interactions with different object types. To start we will look at the addition operator ( + ).
# Integers and floats will add with expected results
print(10 + 42)
print(10.5 + 2.5)
# Strings 'Concatenate' and create a new string
print('Hello ' + 'Friend!')
print('123' + '456') # Note: these are strings not ints
# Adding two lists will add the elements together to a new list
print(['Item1', 'Item2'] + ['Item3', 'Item4'])
# This is a more practical example
users = ['Kyle', 'Joe', 'Bobby']
new_users = ['Ellis', 'Jacob']
# Create a new variable using the result of the operation
all_users = users + new_users
print(all_users)
Subtraction ( - )
Subtraction in Python works like you would expect for numbers and you will often be using for just that, subtracting ints and floats. Strings, and Lists don’t utilize the subtraction operator, usually if you want to remove something from a list you will usually be using list methods like pop or statements like del.
print(10 - 5)
print(2.5 - 0.5)
Multiplication works as you would expect in Math but you can also use this operator for lists and strings as well. You may not use this functionality much but being familiar with it will expand your problem-solving tool belt.
# A list can be multiplied by an integer
print([1, 2, 3] * 2) # Notice the list is repeated the number of times its multiplied
print(['Hello'] * 10)
# Strings will repeat when multiplied and a new string will be returned
print(‘wow’ * 4)
# ints and floats will multiply as expected
print(10 * 5)
Exponents are pretty straightforward and deal with ints and floats. The exponent operator is just a double asterisk.
print(10 ** 3) # 10 to the power of 3 (10 * 10 * 10)
print(12 ** 2) # 12 to the power of 2 (12 * 12)
Division in Python does have a few nuances to be aware of. The / operator performs a floor division, which returns the largest integer that is less than or equal to the result. You can read more about floor division here, but I will show some examples
# Standard division will return a float or int
print(5 / 2.5)
# This will perform 'floor' division returning
the quotient rounded down to the next whole integer
print(5 // 2)
# Modulo returns the remainder of the division
print(5 % 2)
# Is 10 'less than' 20
print(10 < 20)
# Is 10 'greater than' 20
print(10 > 20)
# Two equal signs is 'equal to'
# One equal is the assignment operator.
print(10 == 10)
# You can also test if something is less than or
equal to by just adding the equal sign
print(10 <= 10)
# Otherwise 10 < 10 will evaluate to false
print(10 < 10)
You can test if something is 'not' equal by prepending an '!'. Think of '!' as NOT. So != would be ' Not Equal. This can save time in some instances and it can be used on strings, ints, floats, lists, and dictionaries.
# Returns True if it is not equal
print(10 != 11)
# This can be used on strings too
print('Hello' != 'Hello)
The identity operator will return True if both objects are the exact same objects. This is different than '==' because they have to share a memory address meaning they are actually the same object. If you set a variable equal to an object they will then be the same object in Pythons eyes.
first_name = 'Kyle'
user = first_name
# Setting a variable called user equal to another object
will set its value to the same location in memory, so now
user will be a reference to the first name object, and is
essentially setting it to the exact object
# This evaluates to True because it is the same object
print(user is first_name)
The containment operator 'in' can be used to check if an object is contained within an iterable. If an object is in an iterable the operation will return True, otherwise it will return False. If you have a list of users and would like to check if a name is in that list you can do so with the in operator.
users = ['Raul', 'Mark', 'Ben', 'John']
if 'Steve' in users:
print('Steve is already a user.')
else:
print('User not found.')
You can check containment in most iterables. Strings are iterables so you can check if letters are contained in a string.
username = "AtlasCloud215"
if "A" in username:
print("The letter 'A' is contained in the variable username.")
else:
print("The variable username does not have an 'A' in it.)
There is a full list of operators in the documentation for Python and I would recommend bookmarking it and referencing as you need, or as you get curious about what else is out there.
Also another good website that may be more digestible to beginners is W3Schools, a great website for at a glance reference.