Run a Small Program

PythonPythonBeginner
Practice Now

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

Introduction

Objectives:

  • Make sure Python is installed correctly on your machine
  • Start the interactive interpreter
  • Edit and run a small program

Files Created: art.py

Launch Python

Start Python3 on your machine. Make sure you can type simple statements such as the "hello world" program:

>>> print('Hello World')
Hello World
>>>

In much of this course, you'll want to make sure you can work from the interactive REPL like this. If you're working from a different environment such as IPython or Jupyter Notebooks, that's fine.

Some Generative Art

Create the following program and put it in a file called art.py:

## art.py

import sys
import random

chars = '\|/'

def draw(rows, columns):
    for r in range(rows):
        print(''.join(random.choice(chars) for _ in range(columns)))

if __name__ == '__main__':
    if len(sys.argv) != 3:
        raise SystemExit("Usage: art.py rows columns")
    draw(int(sys.argv[1]), int(sys.argv[2]))

Make sure you can run this program from the command line or a terminal.

python3 art.py 10 20

If you run the above command, you'll get a crash and traceback message. Go fix the problem and run the program again. You should get output like this:

python3 art.py 10 20
||||/\||//\//\|||\|\
///||\/||\//|\\|\\/\
|\////|//|||\//|/\||
|//\||\/|\///|\|\|/|
|/|//|/|/|\\/\/\||//
|\/\|\//\\//\|\||\\/
|||\\\\/\\\|/||||\/|
\\||\\\|\||||////\\|
//\//|/|\\|\//\|||\/
\\\|/\\|/|\\\|/|/\/|

Important Note

It is absolutely essential that you are able to edit, run, and debug ordinary Python programs for the rest of this course. The choice of editor, IDE, or operating system doesn't matter as long as you are able to experiment interactively and create normal Python source files that can execute from the command line.

âœĻ Check Solution and Practice

Summary

Congratulations! You have completed the Run a Small Program lab. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like