Python - Numbers: Your Gateway to the World of Numerical Programming
Hello there, future Python wizards! I'm thrilled to be your guide on this exciting journey into the realm of Python numbers. As someone who's been teaching programming for years, I can tell you that understanding numbers in Python is like learning the alphabet before writing a novel - it's essential! So, let's dive in and make numbers our new best friends.
Python - Number Types
In Python, numbers are like the different flavors of ice cream - each type has its own unique characteristics and uses. Let's explore the main types:
Python − Integer Numbers
Integers, or 'int' for short, are whole numbers without any decimal points. They're like the sturdy bricks we use to build our numerical castle.
age = 25
number_of_pets = 3
negative_number = -10
print(f"I am {age} years old and have {number_of_pets} pets.")
print(f"The temperature dropped by {abs(negative_number)} degrees.")
In this example, age
, number_of_pets
, and negative_number
are all integers. Notice how we can use them in calculations and even apply functions like abs()
to get the absolute value.
Python − Floating Point Numbers
Floats are numbers with decimal points. They're the precision tools in our numerical toolbox.
pi = 3.14159
height = 1.75
small_number = 1.23e-4 # Scientific notation
print(f"The value of pi to 5 decimal places is {pi}")
print(f"I am {height} meters tall.")
print(f"A very small number: {small_number}")
Here, pi
, height
, and small_number
are floats. Note how we can use scientific notation for very small (or large) numbers.
Python − Complex Numbers
Complex numbers are the superheroes of the number world, with both real and imaginary parts.
complex_num = 3 + 4j
print(f"A complex number: {complex_num}")
print(f"Real part: {complex_num.real}, Imaginary part: {complex_num.imag}")
Don't worry if complex numbers seem, well, complex! They're not used as often in everyday programming but are crucial in specific scientific and engineering applications.
Number Type Conversion
Sometimes, we need to change the type of a number, like turning a float into an int. Python makes this easy:
x = 10.6
y = "20"
int_x = int(x) # Converts float to int (rounds down)
float_y = float(y) # Converts string to float
complex_x = complex(x) # Converts to complex number
print(f"{x} as an integer: {int_x}")
print(f"{y} as a float: {float_y}")
print(f"{x} as a complex number: {complex_x}")
Remember, when converting float to int, Python always rounds down. It's like cutting off the decimal part with scissors!
Theoretic and Representation Functions
Python provides several functions to help us understand and represent numbers better:
Function | Description | Example |
---|---|---|
abs(x) | Returns absolute value of x | abs(-5) = 5 |
ceil(x) | Returns smallest integer greater than or equal to x | ceil(4.2) = 5 |
floor(x) | Returns largest integer less than or equal to x | floor(4.2) = 4 |
round(x, n) | Rounds x to n decimal places | round(3.14159, 2) = 3.14 |
import math
x = -4.7
print(f"Absolute value of {x}: {abs(x)}")
print(f"Ceiling of {x}: {math.ceil(x)}")
print(f"Floor of {x}: {math.floor(x)}")
print(f"{x} rounded to 1 decimal place: {round(x, 1)}")
Power and Logarithmic Functions
These functions are like the heavyweight champions of mathematical operations:
Function | Description | Example |
---|---|---|
pow(x, y) | Returns x raised to power y | pow(2, 3) = 8 |
sqrt(x) | Returns square root of x | sqrt(16) = 4 |
log(x) | Returns natural logarithm of x | log(2.71828) ≈ 1 |
log10(x) | Returns base-10 logarithm of x | log10(100) = 2 |
import math
base = 2
exponent = 3
print(f"{base} raised to the power of {exponent}: {pow(base, exponent)}")
print(f"Square root of 16: {math.sqrt(16)}")
print(f"Natural log of e: {math.log(math.e)}")
print(f"Log base 10 of 100: {math.log10(100)}")
Trigonometric Functions
Trigonometry might sound scary, but these functions are just tools to work with angles and triangles:
Function | Description |
---|---|
sin(x) | Sine of x (x in radians) |
cos(x) | Cosine of x (x in radians) |
tan(x) | Tangent of x (x in radians) |
import math
angle = math.pi / 4 # 45 degrees in radians
print(f"Sine of 45°: {math.sin(angle):.4f}")
print(f"Cosine of 45°: {math.cos(angle):.4f}")
print(f"Tangent of 45°: {math.tan(angle):.4f}")
Angular Conversion Functions
These functions help us switch between degrees and radians:
Function | Description |
---|---|
degrees(x) | Converts angle x from radians to degrees |
radians(x) | Converts angle x from degrees to radians |
import math
angle_rad = math.pi / 2
angle_deg = 180
print(f"{angle_rad} radians is equal to {math.degrees(angle_rad)} degrees")
print(f"{angle_deg} degrees is equal to {math.radians(angle_deg)} radians")
Mathematical Constants
Python's math module provides some commonly used mathematical constants:
import math
print(f"Pi: {math.pi}")
print(f"Euler's number (e): {math.e}")
print(f"Tau (2*pi): {math.tau}")
These constants are like the celebrity numbers of the math world - famous and widely used!
Random Number Functions
Sometimes, we need a touch of unpredictability in our programs. That's where random numbers come in:
import random
print(f"A random float between 0 and 1: {random.random()}")
print(f"A random integer between 1 and 10: {random.randint(1, 10)}")
print(f"A random choice from a list: {random.choice(['apple', 'banana', 'cherry'])}")
Random numbers are like the spice in your programming dish - they add that extra kick of excitement!
Built-in Mathematical Functions
Python provides some handy built-in functions for common mathematical operations:
Function | Description | Example |
---|---|---|
max(x, y, ...) | Returns the largest argument | max(5, 10, 15) = 15 |
min(x, y, ...) | Returns the smallest argument | min(5, 10, 15) = 5 |
sum(iterable) | Returns the sum of all items in an iterable | sum([1, 2, 3, 4]) = 10 |
numbers = [1, 2, 3, 4, 5]
print(f"The largest number is: {max(numbers)}")
print(f"The smallest number is: {min(numbers)}")
print(f"The sum of all numbers is: {sum(numbers)}")
And there you have it, my dear students! We've journeyed through the land of Python numbers, from the humble integers to the mighty trigonometric functions. Remember, practice makes perfect, so don't be afraid to experiment with these concepts in your own code.
As I always tell my students, programming is like learning to ride a bike - it might seem wobbly at first, but with practice, you'll be zooming along in no time. So keep coding, keep exploring, and most importantly, keep having fun with Python numbers!
Credits: Image by storyset