Python Numeric Types
In Python, numbers are used to represent numerical data and support various mathematical operations. There are three main numeric types in Python:
1. int (Integer): Integers represent whole numbers without any fractional part. They can be positive or negative.
2. float (Floating-point): Floating-point numbers represent real numbers with a decimal point or exponential notation.
3. complex: Complex numbers represent numbers in the form (a + bi), where (a) and (b) are real numbers, and (i) is the imaginary unit.
Here’s a brief overview and examples of each numeric type:
1. int (Integer):
“`python
# Examples of integers
num1 = 10
num2 = -20
num3 = 0
“`
2. float (Floating-point):
“`python
# Examples of floating-point numbers
float_num1 = 3.14
float_num2 = -0.001
float_num3 = 2.0e3 # Scientific notation (2.0 x 10^3)
“`
3. complex:
“`python
# Examples of complex numbers
complex_num1 = 3 + 4j
complex_num2 = -2j
“`
Mathematical Operations:
Python supports various arithmetic operations on numbers, including addition, subtraction, multiplication, division, exponentiation, and modulus.
“`python
# Mathematical operations
a = 10
b = 3
# Addition
print(a + b) # Output: 13
# Subtraction
print(a – b) # Output: 7
# Multiplication
print(a * b) # Output: 30
# Division
print(a / b) # Output: 3.3333333333333335 (float result)
# Integer Division (floor division)
print(a // b) # Output: 3 (integer result)
# Exponentiation
print(a b) # Output: 1000
# Modulus (remainder)
print(a % b) # Output: 1
“`
Python provides rich functionality and flexibility when working with numbers, allowing you to perform complex calculations and manipulations with ease. Understanding numeric types and their operations is essential for various programming tasks, including scientific computing, data analysis, and algorithmic implementations.
Â
Â
EXERCISES
1. Simple Interest Calculator:
Write a program that calculates the simple interest on a loan or investment. Prompt the user to input the principal amount, interest rate (as a percentage), and the duration of the investment in years. Calculate the simple interest using the formula interest=principal×rate×time100interest=100principal×rate×time​ and display the result.
2. Exponent Calculator:
Write a program that computes the result of raising a number to an exponent. Prompt the user to input the base and the exponent as integers, and calculate the result using exponentiation. Display the result of the exponentiation operation.
Â