Run a Small Program

Intermediate

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn to take your first steps in Python programming. First, you'll verify that Python is correctly installed on your system. Then, you'll learn how to use the Python interactive interpreter.

Next, you'll edit and run a simple Python program. The file you'll create during this process is art.py.

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 82% completion rate. It has received a 99% positive review rate from learners.

Verify Python Installation and Use the Interactive Interpreter

The Python interactive interpreter is a very useful tool. It lets you run Python code one line at a time and see the results right away. This is great for beginners because you can test small pieces of code without having to write a whole program. Before we start writing full - fledged programs, we need to make sure Python is installed correctly on your system. Then, we'll learn how to use this interpreter to execute Python code.

Launch the Python Interpreter

  1. First, we need to open a terminal in the WebIDE. The terminal is like a command - center where you can type in commands to interact with your computer. You'll find a terminal tab at the bottom of the screen. Once you open it, you're ready to start typing commands.

  2. In the terminal, we're going to check if Python is installed and which version you have. Type the following command and then press Enter:

    python3 --version

    This command asks your system to show you the version of Python that is currently installed. If Python is installed correctly, you'll see output similar to:

    Python 3.10.x

    The x here represents a specific patch number, which can vary depending on your installation.

  3. Now that we know Python is installed, let's start the Python interactive interpreter. Type the following command in the terminal and press Enter:

    python3

    After you press Enter, you'll see some information about the Python version and other details. The output will look something like this:

    Python 3.10.x (default, ...)
    [GCC x.x.x] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>>

    The >>> prompt is a signal that the Python interpreter is up and running and is waiting for you to enter Python commands.

Try Simple Python Commands

Now that the Python interpreter is running, let's try out some basic Python commands. These commands will help you understand how Python works and how to use the interpreter.

  1. At the >>> prompt, type the following command and press Enter:

    >>> print('Hello World')

    The print function in Python is used to display text on the screen. When you run this command, you'll see the following output:

    Hello World
    >>>

    This shows that the print function has successfully displayed the text 'Hello World'.

  2. Let's try a simple math calculation. At the prompt, type:

    >>> 2 + 3

    Python will automatically evaluate this expression and show you the result. You'll see:

    5
    >>>

    This demonstrates that Python can perform basic arithmetic operations.

  3. Next, we'll create a variable and use it. Variables in Python are used to store data. Type the following commands at the prompt:

    >>> message = "Learning Python"
    >>> print(message)

    In the first line, we're creating a variable named message and storing the string "Learning Python" in it. In the second line, we're using the print function to display the value stored in the message variable. The output will be:

    Learning Python
    >>>

    The Python interpreter executes each line of code as soon as you enter it. This makes it a great tool for quickly testing ideas and learning Python concepts.

Exit the Interpreter

When you're done experimenting with the Python interpreter, you can exit it using one of the following methods:

  1. You can type the following command at the >>> prompt and press Enter:

    >>> exit()

    Or you can use this alternative command:

    >>> quit()

    Both of these commands tell the Python interpreter to stop running and return you to the regular terminal.

  2. Another way to exit is by pressing Ctrl+D on your keyboard. This is a shortcut that also stops the Python interpreter.

After you exit the interpreter, you'll return to the regular terminal prompt, where you can run other commands on your system.

Create a Simple Python Program

Now that we have confirmed Python is working correctly, it's time to create our first Python program file. For beginners, it's always a good idea to start with something simple before moving on to more complex programs. This way, you can gradually understand the basic concepts and syntax of Python.

Create Your First Python File

First, we'll create a new Python file. Here's how you can do it:

  1. In the WebIDE, you'll notice a panel on the left side of the screen called the Explorer panel. This panel helps you navigate through different files and directories in your project. Locate this panel.

  2. Once you've found the Explorer panel, you need to navigate to the /home/labex/project directory. This is where we'll store our Python program.

  3. Right-click anywhere in the Explorer panel. A menu will appear. From this menu, select "New File". This action will create a new, empty file.

  4. After creating the new file, you need to give it a name. Name the file hello.py. In Python, files usually have the .py extension, which indicates that they contain Python code.

  5. Now, open the newly created hello.py file in the editor. In the editor, type the following code:

    ## This is a simple Python program
    
    name = input("Enter your name: ")
    print(f"Hello, {name}! Welcome to Python programming.")

    Let's break down this code. The line starting with # is a comment. Comments are used to explain what the code does and are ignored by the Python interpreter. The input() function is used to get user input. It displays the message "Enter your name: " and waits for the user to type something. The value entered by the user is then stored in the variable name. The print() function is used to display output on the screen. The f"Hello, {name}!" is an f-string, which is a convenient way to format strings in Python. It allows you to insert the value of a variable directly into a string.

  6. After typing the code, you need to save the file. You can do this by pressing Ctrl+S on your keyboard or by selecting File > Save from the menu. Saving the file ensures that your changes are preserved.

Run Your First Python Program

Now that you've created and saved your Python program, it's time to run it. Here's how:

  1. Open a terminal in the WebIDE if it's not already open. The terminal allows you to execute commands and run programs.

  2. Before running the Python program, you need to make sure you're in the correct directory. Type the following command in the terminal:

    cd ~/project

    This command changes the current working directory to the project directory in your home directory.

  3. Once you're in the correct directory, you can run your Python program. Type the following command in the terminal:

    python3 hello.py

    This command tells the Python interpreter to run the hello.py file.

  4. When the program runs, it will prompt you to enter your name. Type your name and press Enter.

  5. After you press Enter, you should see output similar to:

    Enter your name: John
    Hello, John! Welcome to Python programming.

    The actual output will show the name you entered instead of "John".

This simple program demonstrates several important concepts in Python:

  • Creating a Python file: You learned how to create a new Python file in the WebIDE.
  • Adding comments: Comments are used to explain the code and make it more understandable.
  • Getting user input with the input() function: This function allows your program to interact with the user.
  • Using variables to store data: Variables are used to store values that can be used later in the program.
  • Displaying output with the print() function: This function is used to show information on the screen.
  • Using f-strings for string formatting: F-strings provide a convenient way to insert variables into strings.

Create a More Advanced Python Program

Now that you have grasped the basics of Python, it's time to take the next step and create a more advanced Python program. This program will generate ASCII art patterns, which are simple yet visually interesting designs made up of text characters. By working on this program, you'll get to learn and apply several important Python concepts, such as importing modules, defining functions, and handling command - line arguments.

Create the ASCII Art Program

  1. First, we need to open the art.py file in the WebIDE. This file was created during the setup process. You can find it in the /home/labex/project directory. Opening this file is the starting point for writing our ASCII art program.

  2. Once the file is open, you'll notice that it might have some existing content. We need to clear that out because we're going to write our own code from scratch. So, delete any existing content in the file. Then, copy the following code into the art.py file. This code is the core of our ASCII art generator.

    ## art.py - A program to generate ASCII art patterns
    
    import sys
    import random
    
    ## Characters used for the art pattern
    chars = '\|/'
    
    def draw(rows, columns):
        """
        Generate and print an ASCII art pattern with the specified dimensions.
    
        Args:
            rows: Number of rows in the pattern
            columns: Number of columns in the pattern
        """
        for r in range(rows):
            ## For each row, create a string of random characters
            line = ''.join(random.choice(chars) for _ in range(columns))
            print(line)
    
    ## This code only runs when the script is executed directly
    if __name__ == '__main__':
        ## Check if the correct number of arguments was provided
        if len(sys.argv) != 3:
            print("Error: Incorrect number of arguments")
            print("Usage: python3 art.py rows columns")
            print("Example: python3 art.py 10 20")
            sys.exit(1)
    
        try:
            ## Convert the arguments to integers
            rows = int(sys.argv[1])
            columns = int(sys.argv[2])
    
            ## Call the draw function with the specified dimensions
            draw(rows, columns)
        except ValueError:
            print("Error: Both arguments must be integers")
            sys.exit(1)
  3. After you've copied the code into the file, it's important to save your work. You can do this by pressing Ctrl + S on your keyboard. Alternatively, you can go to the menu and select File > Save. Saving the file ensures that your code is stored and ready to be run.

Understanding the Code

Let's take a closer look at what this program does. Understanding the code is crucial for you to be able to modify and expand it in the future.

  • Import Statements: The lines import sys and import random are used to bring in Python's built - in modules. The sys module provides access to some variables used or maintained by the Python interpreter and to functions that interact strongly with the interpreter. The random module allows us to generate random numbers, which we'll use to create random ASCII art patterns.
  • Character Set: The line chars = '\|/' defines the set of characters that will be used to create our ASCII art. These characters will be randomly selected to form the patterns.
  • The draw() Function: This function is responsible for creating the ASCII art patterns. It takes two arguments, rows and columns, which specify the dimensions of the pattern. Inside the function, it uses a loop to create each row of the pattern by randomly selecting characters from the chars set.
  • Main Block: The if __name__ == '__main__': block is a special construct in Python. It ensures that the code inside this block only runs when the art.py file is executed directly. If the file is imported into another Python file, this code won't run.
  • Argument Handling: The sys.argv variable contains the command - line arguments passed to the program. We check if exactly 3 arguments are provided (the name of the script itself plus two numbers representing the number of rows and columns). This helps us ensure that the user provides the correct input.
  • Error Handling: The try/except block is used to catch errors that might occur. If the user provides invalid inputs, such as non - integer values for the rows and columns, the try block will raise a ValueError, and the except block will print an error message and exit the program.

Run the Program

  1. To run our program, we first need to open a terminal in the WebIDE. The terminal is where we'll enter commands to execute our Python script.

  2. Once the terminal is open, we need to navigate to the project directory. This is where our art.py file is located. Use the following command in the terminal:

    cd ~/project

    This command changes the current working directory to the project directory.

  3. Now that we're in the correct directory, we can run the program. Use the following command:

    python3 art.py 5 10

    This command tells Python to run the art.py script with 5 rows and 10 columns. When you run this command, you'll see a 5×10 pattern of characters printed in the terminal. The output will look something like this:

    |\//\\|\//
    /\\|\|//\\
    \\\/\|/|/\
    //|\\\||\|
    \|//|/\|/\

    Remember, the actual pattern is random, so your output will be different from the example shown here.

  4. You can experiment with different dimensions by changing the arguments in the command. For example, try the following command:

    python3 art.py 8 15

    This will generate a larger pattern with 8 rows and 15 columns.

  5. To see the error - handling in action, try providing invalid arguments. Run the following command:

    python3 art.py

    You should see an error message like this:

    Error: Incorrect number of arguments
    Usage: python3 art.py rows columns
    Example: python3 art.py 10 20

Experiment with the Code

You can make the ASCII art patterns more interesting by modifying the character set. Here's how you can do it:

  1. Open the art.py file again in the editor. This is where we'll make the changes to the code.

  2. Find the chars variable in the code. Change it to use different characters. For example, you can use the following code:

    chars = '*#@+.'

    This will change the set of characters used to create the ASCII art.

  3. After making the change, save the file again using Ctrl + S or File > Save. Then, run the program with the following command:

    python3 art.py 5 10

    Now you'll see a different pattern using your new characters.

This exercise demonstrates several important Python concepts, including:

  • Module imports: How to bring in additional functionality from Python's built - in modules.
  • Function definition: How to define and use functions to organize your code.
  • Command - line argument handling: How to accept and process user input from the command line.
  • Error handling with try/except: How to handle errors gracefully in your program.
  • String manipulation: How to create and manipulate strings to form the ASCII art patterns.
  • Random number generation: How to generate random values to create unique patterns.
  • List comprehensions: A concise way to create lists in Python, which is used in the draw() function.

Summary

In this lab, you have learned a variety of Python fundamentals. You successfully verified the Python installation on your system, used the interactive interpreter for simple commands, and created basic programs that accept user input and generate ASCII art patterns. You also grasped important Python concepts such as syntax, data types, variables, and function definitions.

These skills are the foundation for Python development. You now know how to use the interactive mode for quick testing and create and run complete Python programs. To continue your Python journey, consider exploring more built - in functions and modules, learning about data structures, creating complex real - world programs, and studying object - oriented programming in Python.