Lab 4
Lab 4
Arithmetic Operators:
Operator Description Example (a = 10, b = 3) Result
+ Addition a + b 13
- Subtraction a - b 7
* Multiplication a * b 30
/ Division a / b 3.33
// Floor Division a // b 3
% Modulus (Remainder) a % b 1
** Exponentiation a ** b 1000
Example 1:
x = 15
y = 4
print("Addition:", x + y) # Output: 19
print("Subtraction:", x - y) # Output: 11
print("Multiplication:", x * y) # Output: 60
print("Division:", x / y) # Output: 3.75
print("Floor Division:", x // y) # Output: 3
print("Modulus:", x % y) # Output: 3
print("Exponentiation:", x ** y) # Output: 50625
Output:
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625
Operator Description
** Exponentiation Operator
%, *, /, // Modulos, Multiplication, Division, and Floor Division
+, – Addition and Subtraction operators
Arithmetic operators in Python follow the standard mathematical order of operations, also known
as BODMAS/BIDMAS rules:
1. Brackets
2. Orders (exponentiation, **)
3. Division and Multiplication (/, *, //, %)
4. Addition and Subtraction (+, -)
Example 2:
Python automatically assigns a data type to each value based on what we write.
For today we will look into first four types. Others will be explained later in advanced sessions.
Python provides the type() function to check the data type of a variable.
# int
a = 9
print(type(a))
# float
b = 5.4
print(type(b))
# complex
c = 3 + 9j
print(type(c))
#string
x = "Hello World"
print(type(x))
y= " "
print(type (y))
# bool
print(type(True))
print(type(False))
Output:
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'str'>
<class 'str'>
<class 'bool'>
<class 'bool'>
a = 9
print(a,type(a))
# float
a = "9"
print(a,type(a))
b = 5.4
print(b,type(b))
b = "5.4"
print(b,type(b))
# complex
c = 3 + 9j
print(c, type(c))
c = "3 + 9j"
print(c, type(c))
# bool
d=True
print(d, type(d))
d="True"
print(d, type(d))
Output:
9 <class 'int'>
9 <class 'str'>
3 + 9j <class 'str'>
The type of the returned object from input() will always be <class ‘str’>. We will need to change the
type of input in order to manipulate it.
Example 5:
Output:
a = "100" # String
b = int(a) # Convert string to integer
print(b)
print(type(b))
Output:
100
<class 'int'>
x = 5.8
y = int(x) # Convert float to integer
print(y) # Output: 5
Output:
Example 8:
num = 100
text = "The number is " + str(num)
print(text) # Output: The number is 100
Output:
Python automatically converts smaller types into larger types when needed.
Example 9:
pi = 3.14
whole_number = int(pi)
print(whole_number) # Output: 3
Output:
Example 10:
Output:
Enter a number: 1
Sum: 3
Comparison Operators:
Operator Meaning Example (a = 5, b = 3) Result
== Equal to a == b False
!= Not equal to a != b True
> Greater than a > b True
< Less than a < b False
>= Greater than or equal a >= b True
<= Less than or equal a <= b False
Example 11:
x = 10
y = 20
print(x > y)
print(x == 10)
print(y != x)
Output:
False
True
True
Output:
Output:
Conclusion