Python Operators and Type Conversion

Selin Yazıcıoğlu
3 min readMay 26, 2022

--

Hi everyone, I will explain to operators and type conversion in this article. I will code on Jupyter Notebook in Python.

Ok, let’s start!

Operators

There are 4 kinds of python which are arithmetic operators, assignment operators, comparison operators, and logical operators.

Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations.

a = 6
b = 4
print(a + b) # addition
print(a - b) # subtraction
print(a * b) # multiplication
print(a / b) # division
print(a % b) # modulus
print(a // b) # floor division
print(a ** b) # exponentiation
Output:
10
2
24
1.5
2
1
1296

Assignment Operators

Assignment operators are used to assigning values to variables.

# " += "
a = 23
a += 5 # a = a + 5
print(a)
# " -= "
a = 23
a -=5 # a = a - 5
print(a)
# " /= "
a = 23
a /=5 # a = a / 5
print(a)
# " *= "
a = 23
a *=5 # a = a * 5
print(a)
# " %= "
a = 23
a %=5 # a = a % 5
print(a)
# " **= "
a = 23
a **=5 # a = a ** 5
print(a)
# " //= "
a = 23
a //=5 # a = a // 5
print(a)
Output:
28
18
4.6
115
3
6436343
4

Comparison Operators

Comparison operators are used to comparing two values.

x = 15
y = 8
print(x == y) # Is x equal to y?
print(x != y) # Isn't x equal to y?
print(x > y) # Is greater than y?
print(x < y) # Is x less than y?
print(x >= y) # Is x greater than or equal to y?
print(x <= y) # Is x less than or equal to y?
Output:
False
True
True
False
True
False

Logical Operators

Logical operators are used to combining conditional statements.

# " and "
# Returns True if both statements are true
print(8 < 10) and (6 > 5)
print(4 < 3) and (7 > 5)
Output:
True
False
# " or "
# Returns True if one of the statements is true
print(5 == 5) or (6 == 5)
Output:
True
False
print(5 == 5) or (5 == 5)
Output:
True
True
# " not "
# Reverse the result, returns False if the result is true
print(not 5 == 5)
Output:
False
x = 4
not(x < 5 and x < 10)
Output:
False

Type Conversion

I want to explain type conversion with a simple example.

number = 9
language = "Python"
result = 100.40
print(number)
print(language)
print(result)
Output:
9
Python
100.4

The number variable is an integer in the example. If we want the integer to convert to float then,

print(float(number)) # int - float
Output:
9.0

The result variable is a float. If we want the float to convert to integer then,

print(int(result)) # float - int
Output:
100

Another example is,

print(int("75"))
Output:
75

If we “75” variable writes as a string (seventy-five), it gives an error.

print(int("seventy five"))
Output:
---------------------------------------------------------------------------

ValueError Traceback (most recent call last)
Input In [28], in <cell line: 1>()
----> 1 print(int("seventy five"))

ValueError: invalid literal for int() with base 10: 'seventy five'

I hope while you’re reading my article you can enjoy it!

See you on another topic :)

--

--