Python int
Created By: chatGPT
In Python, the
int
type represents integers, which are whole numbers without a decimal point. Integers can be positive, negative, or zero. They are immutable and can handle large values, restricted only by system memory. You can perform various operations with integers, such as addition, subtraction, multiplication, and division.a = 5
b = 10
# Addition
result = a + b
print('Addition:', result) # Output: 15
# Subtraction
result = a - b
print('Subtraction:', result) # Output: -5
# Multiplication
result = a * b
print('Multiplication:', result) # Output: 50
# Division
result = b / a
print('Division:', result) # Output: 2.0
To convert a string or a float to an integer, you can use the
int()
function. However, if you convert a string that does not represent a valid integer, it will raise a ValueError
. Similarly, converting a float will truncate the decimal part.string_num = '42'
float_num = 42.8
# String to int
int_from_string = int(string_num)
print('Integer from string:', int_from_string) # Output: 42
# Float to int
int_from_float = int(float_num)
print('Integer from float:', int_from_float) # Output: 42
You can also perform type checking on integers using the
isinstance()
function to ensure that a variable is indeed an integer.number = 10
# Type checking
if isinstance(number, int):
print('This is an integer') # Output: This is an integer