This is how integers and floats work in Python(2023)

If you’re new to Python or programming in general, understanding how numbers work in Python is an essential first step. In this blog post, we’ll explore the basics of working with integers and floats in Python.

Integers

Integers are whole numbers that can be positive, negative, or zero. In Python, you can define an integer by assigning a number to a variable, like this:

my_integer = 42

You can also perform various mathematical operations on integers in Python, such as addition, subtraction, multiplication, and division.

x = 10
y = 5
z = x + y  # addition
a = x - y  # subtraction
b = x * y  # multiplication
c = x / y  # division

One thing to note is that when you perform division with integers, the result will always be a float, even if the division yields a whole number.

x = 10
y = 5
z = x / y
print(z)  # Output: 2.0

Floats

Floats are decimal numbers in Python. You can define a float by assigning a decimal number to a variable.

pythonCopy codemy_float = 3.14

You can perform the same mathematical operations on floats as you would with integers.

x = 3.14
y = 2.0
z = x + y  # addition
a = x - y  # subtraction
b = x * y  # multiplication
c = x / y  # division

One thing to note is that when you perform operations with both integers and floats, the result will always be a float.

x = 10
y = 3.14
z = x + y
print(z)  # Output: 13.14

Conclusion

In summary, integers and floats are the building blocks of numerical operations in Python. With this basic knowledge, you’re well on your way to learning more advanced topics in Python.

Leave a Comment