Integers are whole numbers that can be positive, negative, or zero, such as -3, 0, 5, etc.
Storing Integers in Python
In Python, you can store integers in variables just like any other data type. For example:
num1 = 10
num2 = -5
num3 = 0
Working with Integer Variables
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 integer operations
Addition:
Python provides the + operator to add two integers. For example:
print(3 + 5)
Subtraction:
The - operator is used for subtracting one integer from another. For example:
print(10 - 6)
Multiplication:
For multiplication, Python uses the * operator. For example:
x = 4 * 5 print(x)
Division:
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
Modulo:
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?
Converting between Integers and Strings
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.