Integers are whole numbers that can be positive, negative, or zero, such as -3, 0, 5, etc.
In Python, you can store integers in variables just like any other data type. For example:
num1 = 10 num2 = -5 num3 = 0
You can perform operations directly on integer variables and store the results in a new variable. For example:
result = num1 + num2 print(result) # Output: 5
Python provides the + operator to add two integers. For example:
print(3 + 5)
The - operator is used for subtracting one integer from another. For example:
print(10 - 6)
For multiplication, Python uses the * operator. For example:
x = 4 * 5
print(x)
Python has two division operators. The / operator performs normal division and returns a float. For example:
print(10 / 3) # outputs a floating point value 3.3333
The // operator performs floor division and returns the quotient as an integer. For example:
print(10 // 3) # Outputs a integer value 3
The % operator is used for finding the remainder of division between two integers. For example:
remainder = 10 % 3
print(remainder) #outputs 1
Modulo is used widely within computer science, in everything from encryption to library book verification.
What is the product of 7 * 4?
Sometimes, you may need to convert an integer into a string or vice versa. Python allows you to easily convert between these data types using the str() and int() functions. For example, to convert the integer 10 into a string, you can use the str(10) function, which will give you the string "10".
x = 6
x = str(x) # x is now '6', not 6
print(x*2) # Outputs '66', not 12
When you convert a number to a string the mathematical operators no longer work like before.
'5' + '4' # '54'
'4' * 3 # 444
'5' + 4 #Error
6 / '2' #Error
What is the result of '5' * 4?
What is the result of '42 + '18'?