
Python Basics: Numbers and Math
Python has robust support for working with numbers and performing mathematical operations. In this tutorial, we will cover the basics of numbers and math in Python. We will learn about integers, floating-point numbers, arithmetic operations, math functions, number methods, and formatting and displaying numbers as strings.
Integers and Floating-Point Numbers
In Python, you can create both integers and floating-point numbers. Integers are whole numbers, while floating-point numbers have a decimal point in them. Here’s how you can create and work with these types of numbers:
# Integers
x = 10
y = -3
# Floating-point numbers
a = 3.14
b = -0.005Arithmetic Expressions
Python supports various arithmetic operations such as addition, subtraction, multiplication, and division. Here are some examples of using arithmetic expressions:
# Addition
sum_result = 10 + 5 # Output: 15
# Subtraction
difference = 10 - 5 # Output: 5
# Multiplication
product = 10 * 5 # Output: 50
# Division
quotient = 10 / 3 # Output: 3.3333333333333335Math Functions and Number Methods
Python provides built-in math functions and number methods for performing complex mathematical operations. Let’s see how you can use these:
import math
# Using math functions
sqrt_result = math.sqrt(16) # Output: 4.0
power_result = math.pow(2, 3) # Output: 8.0
# Using number methods
absolute_value = abs(-10) # Output: 10Numbers Formatted as Strings
You can format and display numbers as strings in Python using the format() method or f-strings. Here's an example of formatting a number as a string:
# Using the format() method
formatted_string = "Value: {}".format(42) # Output: 'Value: 42'
# Using f-strings (Python 3.6+)
value = 42
formatted_string = f"Value: {value}" # Output: 'Value: 42'Complex Numbers
Python also supports complex numbers and provides built-in functions for working with them. Here’s how you can create and manipulate complex numbers in Python:
# Creating complex numbers
complex_num1 = 2 + 3j
complex_num2 = complex(3, 4)
# Manipulating complex numbers
sum_complex = complex_num1 + complex_num2
product_complex = complex_num1 * complex_num2In this tutorial, we covered the basics of numbers and math in Python. We discussed how to create and work with integers, floating-point numbers, arithmetic expressions, math functions, number methods, and complex numbers. Python’s built-in support for numbers and math operations makes it a powerful tool for mathematical computation.





