When working with numbers in Python, you may sometimes encounter negative values. Knowing how to write and use these numbers is an essential skill in programming. In this tutorial, we will learn how to write negative numbers in Python and practice basic operations with them.
Step 1: Writing negative numbers in Python
In Python, a negative number is simply preceded by a minus sign (-). For example, the number -5 is written as follows:
1 |
number = -5 |
You can perform the same mathematical operations with negative numbers as with positive numbers (addition, subtraction, multiplication, or division).
Step 2: Performing Operations with Negative Numbers
Let’s see how to perform basic mathematical operations on negative numbers in Python.
1. Addition
1 2 3 4 |
num1 = -5 num2 = 3 addition_result = num1 + num2 print(addition_result) |
2. Subtraction
1 2 3 4 |
num1 = 7 num2 = -3 subtraction_result = num1 - num2 print(subtraction_result) |
3. Multiplication
1 2 3 4 |
num1 = -7 num2 = 4 multiplication_result = num1 * num2 print(multiplication_result) |
4. Division
1 2 3 4 |
num1 = -12 num2 = 4 division_result = num1 / num2 print(division_result) |
These codes above will work for both positive and negative numbers.
Python Code Outputs
Addition result: -2 Subtraction result: 10 Multiplication result: -28 Division result: -3.0
Step 3: Using negative numbers with built-in functions and modules
Python has various built-in functions that you can use with negative numbers.
1. Absolute Value
The abs() function returns the absolute value of a number. For example:
1 2 |
num = -9 print(abs(num)) |
2. Round
The round() function will round a floating-point number to the nearest integer. It can also be used with negative numbers.
1 2 |
num = -3.7 print(round(num)) |
You can also use the math module in Python to perform more advanced operations on negative numbers or work with trigonometric and logarithmic functions.
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
num1 = -5 num2 = 3 addition_result = num1 + num2 print("Addition result:", addition_result) num1 = 7 num2 = -3 subtraction_result = num1 - num2 print("Subtraction result:", subtraction_result) num1 = -7 num2 = 4 multiplication_result = num1 * num2 print("Multiplication result:", multiplication_result) num1 = -12 num2 = 4 division_result = num1 / num2 print("Division result:", division_result) num = -9 print("Absolute value of -9:", abs(num)) num = -3.7 print("Rounded value of -3.7:", round(num)) |
Conclusion
In this tutorial, we have learned how to write negative numbers in Python, perform basic operations with them, and use built-in functions to manipulate and work with them. Now you can handle negative numbers in your Python programming with ease.