Skip to content
Closed
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
21 changes: 21 additions & 0 deletions graph.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# importing the required module
import matplotlib.pyplot as plt

# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]

# plotting the points
plt.plot(x, y)

# naming the x axis
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')

# giving a title to my graph
plt.title('My first graph!')

# function to show the plot
plt.show()
Comment on lines +1 to +21

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The script's code is at the top level of the module. It's a standard Python best practice to encapsulate the script's logic in a function (e.g., main) and call it under a if __name__ == "__main__": block. This has several benefits:

  • Reusability: It allows you to import this file as a module in other scripts without executing the plotting code automatically.
  • Testability: Functions are easier to test in isolation.
  • Clarity: It clearly separates the main logic from function/class definitions.
# importing the required module
import matplotlib.pyplot as plt

def main():
    """Creates and displays a simple line graph."""
    # x axis values
    x = [1,2,3]
    # corresponding y axis values
    y = [2,4,1]

    # plotting the points 
    plt.plot(x, y)

    # naming the x axis
    plt.xlabel('x - axis')
    # naming the y axis
    plt.ylabel('y - axis')

    # giving a title to my graph
    plt.title('My first graph!')

    # function to show the plot
    plt.show()

if __name__ == "__main__":
    main()