X Tutup

Write a Simple Python Program

PythonBeginner
Practice Now

Introduction

In this lab, you will embark on your journey into Python programming by creating and running your very first program. You will gain hands-on experience using the VS Code editor within the LabEx environment to write and execute Python scripts.

Building upon this foundation, you will further practice writing Python programs, focusing on utilizing the print() function to display output. The lab will then guide you through identifying and understanding common Python errors, equipping you with the knowledge to recognize and troubleshoot issues. Finally, you will learn practical debugging techniques to effectively resolve errors and ensure your Python programs function correctly.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 96% completion rate. It has received a 100% positive review rate from learners.

Create and Run Your First Python Program

In this step, we will create and run our first Python program using the VS Code editor in the LabEx environment.

In previous sections, we learned about the two ways to run Python and explored some development tools. Now, let's put that knowledge into practice by writing a simple program.

We will use the VS Code editor, which is available in the LabEx environment, to create our Python file. The default working directory in the terminal is ~/project.

First, let's create a new file named hello.py in the ~/project directory. You can do this by right-clicking in the file explorer pane in VS Code and selecting "New File", or by using the terminal.

Let's use the terminal for practice. Open the terminal in VS Code (Terminal -> New Terminal) and navigate to the ~/project directory if you are not already there.

cd ~/project

Now, create the file using the touch command:

touch hello.py

You should see the hello.py file appear in the file explorer pane.

Now, open the hello.py file in the VS Code editor by clicking on it in the file explorer.

Enter the following Python code into the editor:

print("Hello, LabEx!")

This simple program uses the built-in print() function to display the string "Hello, LabEx!" on the console.

Save the file (File -> Save or press Ctrl + S).

Now, let's run this program from the terminal. Make sure you are still in the ~/project directory in the terminal.

Execute the Python script using the python command:

python hello.py

You should see the output:

Hello, LabEx!

Congratulations! You have successfully created and run your first Python program.

Practice Writing a Python Program

In this step, we will continue practicing writing Python programs using the print() function. We will create a new file and write a program that prints a simple pattern.

In the previous step, we created and ran a basic "Hello, World!" program. Now, let's try something slightly more complex to get more comfortable with writing code in VS Code and running it from the terminal.

We will create a new file named pattern.py in the ~/project directory. You can create this file using the same methods as before: either by right-clicking in the file explorer or using the touch command in the terminal.

Let's use the file explorer this time. In the VS Code file explorer pane, right-click on the ~/project directory and select "New File". Type pattern.py and press Enter.

Now, open the pattern.py file in the editor and enter the following Python code:

print("* * * *")
print("*     *")
print("*     *")
print("* * * *")

This program uses four separate print() statements to print lines of asterisks and spaces, forming a simple rectangular pattern.

Remember to save the file (Ctrl + S).

Now, open the terminal in VS Code and make sure you are in the ~/project directory.

Run the pattern.py script using the python command:

python pattern.py

You should see the following output in the terminal:

* * * *
*     *
*     *
* * * *

This demonstrates how you can use multiple print() statements to control the output and create more complex text-based patterns.

Feel free to experiment with different characters and arrangements within the print() statements to create your own patterns.

Identify and Understand Common Python Errors

In this step, we will explore some common errors you might encounter when writing Python code and learn how to identify and understand the error messages. Encountering errors is a normal part of programming, and learning to read and interpret error messages is a crucial skill.

We will intentionally introduce some errors into our code to see how Python responds. Let's start by modifying the hello.py file we created in the first step.

Open the hello.py file in the VS Code editor.

First, let's introduce a spelling mistake in the print() function. Change the line to:

prunt("Hello, LabEx!")

Save the file (Ctrl + S).

Now, run the modified hello.py file from the terminal:

python hello.py

You should see an error message similar to this:

Traceback (most recent call last):
  File "/home/labex/project/hello.py", line 1, in <module>
    prunt("Hello, LabEx!")
NameError: name 'prunt' is not defined

This is a NameError. It tells us that the name prunt is not recognized by Python. This is because the correct function name is print. The error message also points to the file name (hello.py), the line number (line 1), and the specific code that caused the error.

Now, let's correct the spelling of print and introduce a missing quote. Change the line back to print, but remove the closing double quote:

print("Hello, LabEx!)

Save the file and run it again:

python hello.py

You should see a different error message, likely a SyntaxError:

  File "/home/labex/project/hello.py", line 1
    print("Hello, LabEx!)
                         ^
SyntaxError: unterminated string literal (missing '"')

This SyntaxError indicates that there is an issue with the structure of your code. The message "unterminated string literal (missing '"')" clearly tells us that a string started with a double quote but did not end with one.

Finally, let's correct the quotes and introduce a non-English character for the parentheses. Change the line to:

print("Hello, LabEx!")

Note that the parentheses here are full-width Chinese characters, not the half-width English characters required by Python.

Save the file and run it:

python hello.py

You will likely see a SyntaxError related to invalid characters:

  File "/home/labex/project/hello.py", line 1
    print("Hello, LabEx!")
          ^
SyntaxError: invalid character '(' (U+FF08)

This error message points to the invalid character and its Unicode representation. Python expects standard English half-width characters for syntax elements like parentheses.

By intentionally creating these errors and observing the error messages, you can start to understand what different types of errors mean and how to locate the source of the problem in your code. In the next step, we will learn how to debug these errors.

Debug Your Python Program

In this step, we will practice debugging the errors we encountered in the previous step. Debugging is the process of finding and fixing errors in your code. By understanding the error messages, we can effectively debug our programs.

We will work with the hello.py file again, which currently contains an error from the previous step.

Open the hello.py file in the VS Code editor.

Let's start with the SyntaxError caused by the invalid character. The error message pointed to the line and the character causing the issue.

print("Hello, LabEx!")

The error message SyntaxError: invalid character '(' (U+FF08) indicates that the opening parenthesis is incorrect. Delete the full-width parenthesis and replace it with the correct English half-width parenthesis (. Do the same for the closing parenthesis , replacing it with ).

The corrected line should look like this:

print("Hello, LabEx!")

Save the file (Ctrl + S).

Now, run the hello.py file from the terminal:

python hello.py

If you had the invalid character error, it should now be resolved, and you should see the output:

Hello, LabEx!

If you still have other errors from the previous step, let's address them.

If you had the SyntaxError: unterminated string literal (missing '"'), it means you were missing a closing quote. Look at the line indicated in the error message and add the missing double quote.

For example, if your line was print("Hello, LabEx!), change it to print("Hello, LabEx!").

If you had the NameError: name 'prunt' is not defined, it means you misspelled the function name. Change prunt back to print.

After fixing any remaining errors, save the file and run it again using python hello.py. Your program should now run without errors and print "Hello, LabEx!".

Debugging is an iterative process. You might fix one error only to find another. The key is to read the error messages carefully, understand what they are telling you, and systematically fix the issues in your code.

Summary

In this lab, we began our journey into Python programming by creating and running our very first program, hello.py, using the VS Code editor within the LabEx environment. We learned how to create a Python file, write a simple print() statement to display output, and execute the script from the terminal using the python command. This foundational step solidified our understanding of the basic workflow for writing and running Python code.

Building upon this, we further practiced writing Python programs by creating a new file and implementing a program that prints a simple pattern using the print() function. This exercise reinforced our ability to use the print() function for various outputs and provided hands-on experience with structuring basic Python code.

X Tutup