Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions days_in_month.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"""
This module provides a function to determine the number of days in a given month.
"""


def days_in_month(month):
"""
Returns the number of days in a given month.

Args:
month: int (1-12) or str (month name in Spanish or English)

Returns:
int: number of days in the month
"""

months_days = {
1: 31, 'enero': 31, 'january': 31,
2: 28, 'febrero': 28, 'february': 28,
3: 31, 'marzo': 31, 'march': 31,
4: 30, 'abril': 30, 'april': 30,
5: 31, 'mayo': 31, 'may': 31,
6: 30, 'junio': 30, 'june': 30,
7: 31, 'julio': 31, 'july': 31,
8: 31, 'agosto': 31, 'august': 31,
9: 30, 'septiembre': 30, 'september': 30,
10: 31, 'octubre': 31, 'october': 31,
11: 30, 'noviembre': 30, 'november': 30,
12: 31, 'diciembre': 31, 'december': 31
}

if isinstance(month, str):
month = month.lower()

if month in months_days:
return months_days[month]
else:
return "Invalid month. Use a number (1-12) or month name."


def main():
"""Main interactive function."""
print("=" * 60)
print("📅 DAYS IN MONTH CALCULATOR 📅")
print("=" * 60)
print("\nYou can enter a month as:")
print(" • Number (1-12)")
print(" • Month name in Spanish (enero, febrero, etc.)")
print(" • Month name in English (January, February, etc.)\n")

while True:
try:
# Get user input
user_input = input("Enter a month (or type 'exit' to quit): ").strip()

# Check if user wants to exit
if user_input.lower() == 'exit':
print("\n👋 Thank you for using the Days in Month Calculator! Goodbye!")
break

# Try to convert to integer
try:
month_num = int(user_input)
result = days_in_month(month_num)
except ValueError:
# If not a number, treat as month name
result = days_in_month(user_input)

# Display result
if isinstance(result, int):
print(f"\n✅ Result: {result} days\n")
print("=" * 60 + "\n")
else:
print(f"\n❌ {result}\n")
print("Examples: 1, January, Enero, 6, June, Junio")
print("=" * 60 + "\n")

except Exception as e:
print(f"\n❌ Error: {e}")
print("Please try again.\n")


if __name__ == "__main__":
main()
85 changes: 85 additions & 0 deletions euclidean_distance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
"""
This program calculates the Euclidean distance between two points in a Cartesian plane.
For more information about Euclidean distance, you can visit: https://en.wikipedia.org/wiki/Euclidean_distance
"""

# Import the module to perform mathematical operations (Square root)
import math


def euclidean_distance(x1, y1, x2, y2):
"""
Calculates the Euclidean distance between two points (x1, y1) and (x2, y2).

Parameters:
x1, y1: coordinates of the first point
x2, y2: coordinates of the second point

Returns:
The Euclidean distance between the two points.
"""

return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)


def main():
print("=" * 55)
print("📍 EUCLIDEAN DISTANCE CALCULATOR 📍")
print("=" * 55)
print("\nCalculates the distance between two points in a Cartesian plane.\n")

while True:
try:
print("\n--- Enter the coordinates of the FIRST POINT ---")
while True:
try:
x1 = float(input("x1: "))
y1 = float(input("y1: "))

if x1 < 0 or y1 < 0:
print("❌ Error: Numbers cannot be negative. Please enter positive values.")
continue
break
except ValueError:
print("❌ Error: Please enter valid numbers.")
continue

print("\n--- Enter the coordinates of the SECOND POINT ---")
while True:
try:
x2 = float(input("x2: "))
y2 = float(input("y2: "))

if x2 < 0 or y2 < 0:
print("❌ Error: Numbers cannot be negative. Please enter positive values.")
continue
break
except ValueError:
print("❌ Error: Please enter valid numbers.")
continue

distance = euclidean_distance(x1, y1, x2, y2)

print("\n" + "=" * 55)
print(f"✅ RESULT:")
print(f" Point 1: P1({x1}, {y1})")
print(f" Point 2: P2({x2}, {y2})")
print(f" Euclidean distance: {distance:.4f} units")
print("=" * 55)

while True:
continuar = input("\nDo you want to calculate another distance? (y/n): ").strip().lower()
if continuar in ["y", "n"]:
break
print("❌ Please enter 'y' or 'n'.")

if continuar == "n":
print("\n👋 Thank you for using the Euclidean Distance Calculator!")
break

except Exception as e:
print(f"❌ Unexpected error: {e}")


if __name__ == "__main__":
main()
167 changes: 167 additions & 0 deletions pythagorean_theorem.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@

"""
This module allows solving any problem about the Pythagorean theorem, it also verifies if three numbers meet the relationship a² + b² = c².
For more information about the Pythagorean theorem, you can visit: https://en.wikipedia.org/wiki/Pythagorean_theorem

"""

# Import the module to perform mathematical operations (Square root)
import math

def pythagorean_theorem(a=None, b=None, c=None):
"""
Solves the Pythagorean theorem: a² + b² = c²

Parameters:
a: side a (or None if you want to calculate it)
b: side b (or None if you want to calculate it)
c: hypotenuse (or None if you want to calculate it)

Returns:
Tuple with the values (a, b, c)
"""
if a is None:
if b is not None and c is not None:
a = math.sqrt(c**2 - b**2)
else:
raise ValueError("At least two values are needed")
elif b is None:
if a is not None and c is not None:
b = math.sqrt(c**2 - a**2)
else:
raise ValueError("At least two values are needed")
elif c is None:
if a is not None and b is not None:
c = math.sqrt(a**2 + b**2)
else:
raise ValueError("At least two values are needed")

return (a, b, c)


def verify_pythagorean(a, b, c):
"""
Verifies if three numbers satisfy the Pythagorean theorem.
They are normally called Pythagorean triples.
parameters:
a: side a
b: side b
c: hypotenuse
Returns:
True if they satisfy the theorem, False otherwise.
"""
return abs(a**2 + b**2 - c**2) < 1e-10


if __name__ == "__main__":
print("=" * 50)
print("🔺 PYTHAGOREAN THEOREM CALCULATOR 🔺")
print("=" * 50)
print("\nPythagorean Theorem: a² + b² = c²\n")

while True:
print("\nWhat would you like to do?")
print("1. Calculate the hypotenuse (c) knowing the legs (a, b)")
print("2. Calculate a leg knowing the other and the hypotenuse")
print("3. Verify if three numbers form a right triangle")
print("4. Exit")

opcion = input("\nSelect an option (1-4): ").strip()

if opcion == "1":
print("\n--- Calculate Hypotenuse ---")
try:
a = float(input("Enter the value of leg a: "))
b = float(input("Enter the value of leg b: "))

if a <= 0 or b <= 0:
print("\u274c Values must be greater than 0")
continue

a, b, c = pythagorean_theorem(a=a, b=b)
print(f"\n✅ Results:")
print(f" Leg a: {a:.2f}")
print(f" Leg b: {b:.2f}")
print(f" Hypotenuse c: {c:.2f}")
print(f" Verification: a² + b² = c² → {a**2:.2f} + {b**2:.2f} = {c**2:.2f} ✓")
except ValueError as e:
print(f"\u274c Error: {e}")
except Exception as e:
print(f"\u274c Invalid input. Please enter valid numbers.")

elif opcion == "2":
print("\n--- Calculate a Leg ---")
print("Which leg do you want to calculate?")
print("a) Calculate leg a")
print("b) Calculate leg b")

cateto_opcion = input("Select (a/b): ").strip().lower()

try:
if cateto_opcion == "a":
b = float(input("Enter the value of leg b: "))
c = float(input("Enter the value of hypotenuse c: "))

if b <= 0 or c <= 0 or b >= c:
print("\u274c Invalid values. The hypotenuse must be greater than the leg.")
continue

a, b, c = pythagorean_theorem(b=b, c=c)
print(f"\n✅ Results:")
print(f" Leg a: {a:.2f}")
print(f" Leg b: {b:.2f}")
print(f" Hypotenuse c: {c:.2f}")
print(f" Verification: a² + b² = c² → {a**2:.2f} + {b**2:.2f} = {c**2:.2f} ✓")

elif cateto_opcion == "b":
a = float(input("Enter the value of leg a: "))
c = float(input("Enter the value of hypotenuse c: "))

if a <= 0 or c <= 0 or a >= c:
print("\u274c Invalid values. The hypotenuse must be greater than the leg.")
continue

a, b, c = pythagorean_theorem(a=a, c=c)
print(f"\n✅ Results:")
print(f" Leg a: {a:.2f}")
print(f" Leg b: {b:.2f}")
print(f" Hypotenuse c: {c:.2f}")
print(f" Verification: a² + b² = c² → {a**2:.2f} + {b**2:.2f} = {c**2:.2f} ✓")
else:
print("\u274c Invalid option")
except ValueError:
print("\u274c Invalid input. Please enter valid numbers.")
except Exception as e:
print(f"❌ Error: {e}")

elif opcion == "3":
print("\n--- Verify Right Triangle ---")
try:
a = float(input("Enter the value of a: "))
b = float(input("Enter the value of b: "))
c = float(input("Enter the value of c (hypotenuse): "))

if a <= 0 or b <= 0 or c <= 0:
print("\u274c Values must be greater than 0")
continue

es_rectangulo = verify_pythagorean(a, b, c)

print(f"\n✅ Analysis:")
print(f" a² + b² = {a**2:.2f} + {b**2:.2f} = {(a**2 + b**2):.2f}")
print(f" c² = {c**2:.2f}")

if es_rectangulo:
print(f" ✓ YES, it is a right triangle (Pythagorean triple)!")
else:
diferencia = abs(a**2 + b**2 - c**2)
print(f" ✗ NO, it is not a right triangle (difference: {diferencia:.2f})")
except ValueError:
print("\u274c Invalid input. Please enter valid numbers.")

elif opcion == "4":
print("\n👋 Thank you for using the Pythagorean Calculator! See you soon!")
break

else:
print("\u274c Invalid option. Please select 1, 2, 3, or 4.")
56 changes: 56 additions & 0 deletions slope_straight_line.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""
Interactive program to calculate the slope of a straight line
Formula: m = (y2 - y1) / (x2 - x1)
"""

def calcular_pendiente():
"""Calculates the slope between two points."""
print("=" * 50)
print("Slope Calculator for a Straight Line")
print("=" * 50)

try:
# Get coordinates of the first point
print("\nEnter the coordinates of the first point (x1, y1):")
x1 = float(input("x1: "))
y1 = float(input("y1: "))

# Get coordinates of the second point
print("\nEnter the coordinates of the second point (x2, y2):")
x2 = float(input("x2: "))
y2 = float(input("y2: "))

# Validate that x1 and x2 are different
if x1 == x2:
print("\n❌ Error: x1 and x2 cannot be equal (vertical line).")
return

# Calculate slope
pendiente = (y2 - y1) / (x2 - x1)

# Display results
print("\n" + "=" * 50)
print("RESULTS:")
print("=" * 50)
print(f"Point 1: ({x1}, {y1})")
print(f"Point 2: ({x2}, {y2})")
print(f"\nSlope (m) = ({y2} - {y1}) / ({x2} - {x1})")
print(f"Slope (m) = {pendiente:.4f}")
print("=" * 50)

except ValueError:
print("\n❌ Error: Please enter valid numeric values.")

def main():
"""Main function."""
while True:
calcular_pendiente()

# Ask if you want to calculate another slope
respuesta = input("\nDo you want to calculate another slope? (y/n): ").lower().strip()
if respuesta != 'y':
print("\nThank you for using the slope calculator!")
break

if __name__ == "__main__":
main()