Python Tutorial 3: Basic Operation
1. Quick Math
Remember first learning about Maths in primary school? It is similar in Python.
Commonly used operators:
Symbol | Meaning |
---|---|
+ | Addition |
– | Subtraction |
* | Multiplication |
/ | Division |
** | Exponential |
% | Modulus (returns the remainder) |
a = 2
b = 2
sumofAB = a+b
print(sumofAB)
c = 1
minusC = sumofAB - c
print(minusC)
multiplyAB = a * b
print(multiplyAB)
divide = a / b
print(divide)
exponential = a ** b
print(exponential)
WhatIsTheReminder = b % a
print(WhatIsTheReminder)
2. String Operations
The ‘+’ operator behaves differently when it comes to strings. Instead of ‘addition’, we call this ‘concatenation’.
c = "2"
d = "3"
print(c + d)
x = "Hello"
y = "World!"
print(x + " " + y)
If we had concatenated x and y without adding the white space in between the following will be the result:
print(x + y)
Concatenating strings with integers
We cannot concatenate strings with integers. To do so we need to convert the integer to a string, using the function str().
e = 23
print(c + d + str(e))
Similarly, in order to add a string (which is a number) to an integer, we can also convert the string to an integer using int().
print(int(c) + int(d) + e)
Try it out!
Assign 100 to principal, 1.05 to rate and calculate the product. Then, concatenate the output with “At the end of the year, I would have $” and print the result.
principal = 100
rate = 1.05
print("At the end of the year, I would have $" + str(principal*rate))
3. Logical operators
In the previous chapter we covered some of the commonly used logical operators, which will return either True or False.
Here are more logical operators.
Equal to? Not Equal to?
‘!=’ is the opposite of ‘==’. It means not equal to.
x = 6
print(x != 6)
print(x != 8)
Is something inside a string?
We can find out whether a substring is present in another string using the ‘in’ operator. While this may sound redundant for now, it is useful to find whether a certain element is present in a list. You will more about lists in the next chapter.
a = 'at'
b = 'bat'
c = 'bath'
print(a in b)
print(b in c)
print(c in a)
Putting ‘not’ in the boolean expression will return the opposite output.
print(a not in b)
print(b not in c)
print(c not in a)