
Python Basics First Program
Python is an efficient and versatile programming language. In this tutorial, you will learn how to write your first Python program, handle errors, declare variables, inspect variable values, and add comments to your code.
Writing Your First Python Program
Let’s start by writing a simple “Hello, World!” program. Open a text editor and create a new file, then type the following code:
print("Hello, World!")Save the file with a .py extension, for example, hello.py. To run the program, open a terminal or command prompt, navigate to the directory where the file is saved, and type:
python hello.pyYou should see “Hello, World!” printed to the console.
Handling Errors
Mistakes happen when writing code. Let’s intentionally introduce an error in our program to see how Python handles it. Update the code in hello.py to the following:
print("Hello, World")The missing exclamation mark will cause a syntax error. When you run the program again, Python will display an error message indicating the issue with the code.
Declaring and Inspecting Variables
You can declare variables in Python using a simple assignment. Create a new file called variables.py and add the following code:
x = 10
y = "Hello"
print(x)
print(y)Running this program will display the values of x and y.
Adding Comments to Your Code
Comments are essential for explaining the purpose of your code. Create a new file called comments.py and add the following code:
# This is a comment
print("Hello, World!") # This is also a commentWhen you run this program, you’ll see that the comments are ignored, and only “Hello, World!” is printed.
Congratulations! You’ve successfully written your first Python program, handled errors, declared variables, and added comments to your code. As you continue your Python journey, remember that practice is key to mastering the language. Happy coding!
