Sitemap
N K

N K

Graphing with code

2 min readApr 26, 2026

A Python-based program designed to calculate and visualize trigonometric functions such as sine, cosine, and tangent. The code likely asks the user to choose a function, enter a range of angles, and then computes the values by converting degrees into radians using Python’s math library. It then displays the results in a clear table format, helping users understand how trigonometric values change at different angles.

Using this formula, the user can input which of the three trigonometry functions and what starting angles to create a graph. A key feature of the project is graph plotting, usually done with the matplotlib library.

This is the code:

import math
import matplotlib.pyplot as plt

def calculate_trig(func, start, end, step):
angles = []
values = []

for angle in range(start, end + 1, step):
rad = math.radians(angle)

try:
if func == "sin":
value = math.sin(rad)
elif func == "cos":
value = math.cos(rad)
elif func == "tan":
# Prevent undefined values like tan(90°)
if abs(math.cos(rad)) < 1e-10:
value = None
else:
value = math.tan(rad)
else:
return None, None

angles.append(angle)
values.append(value)

except:
angles.append(angle)
values.append(None)

return angles, values


def display_results(func, angles, values):
print(f"\nAngle (deg) | {func}(x)")
print("-----------------------")
for a, v in zip(angles, values):
if v is None:
print(f"{a:<12} | undefined")
else:
print(f"{a:<12} | {v:.4f}")


def plot_graph(func, angles, values):
# Remove undefined values for plotting
valid_angles = []
valid_values = []

for a, v in zip(angles, values):
if v is not None:
valid_angles.append(a)
valid_values.append(v)

plt.plot(valid_angles, valid_values)
plt.title(f"{func}(x) graph")
plt.xlabel("Angle (degrees)")
plt.ylabel(f"{func}(x)")
plt.grid()
plt.show()


def main():
while True:
func = input("Choose function (sin/cos/tan): ").lower()

if func not in ["sin", "cos", "tan"]:
print("Invalid function. Try again.")
continue

try:
start = int(input("Enter start angle: "))
end = int(input("Enter end angle: "))
step = int(input("Enter step: "))
except:
print("Invalid number input. Try again.")
continue

angles, values = calculate_trig(func, start, end, step)

display_results(func, angles, values)

show_graph = input("Show graph? (yes/no): ").lower()

if show_graph == "yes":
plot_graph(func, angles, values)

again = input("\nDo you want to continue? (yes/no): ").lower()
if again != "yes":
print("Program ended.")
break


if __name__ == "__main__":
main()

The link to test this out:

Get N K’s stories in your inbox

Join Medium for free to get updates from this writer.

https://github.com/NeKo2801/graphing

--

--