Skip to main content

Execution the Program | Core Python 3.8

Saving and Executing Your Programs 

The interactive interpreter is one of Python’s great strengths. It makes it possible to test solutions and to experiment with the language in real time. If you want to know how something works, just try it! However, everything you write in the interactive interpreter is lost when you quit. What you really want to do is write programs that both you and other people can run. In this section, you learn how to do just that.
    First of all, you need a text editor, preferably one intended for programming. (If you use something like Microsoft Word, which I really don’t really recommend, be sure to save your code as plain text.) If you are already using IDLE, you’re in luck. With IDLE, you can simply create a new editor window with File › New File. Another window appears, without an interactive prompt. Whew! Start by entering the following:

print("Hello, world!")

Now select File › Save to save your program (which is, in fact, a plain text file). Be sure to put it somewhere where you can find it later, and give your file any reasonable name, such as hello.py. (The .py ending is significant.)
    Got that? Don’t close the window with your program in it. If you did, just open it again (File › Open). Now you can run it with Run › Run Module. (If you aren’t using IDLE, see the next section about running your programs from the command prompt.)
    What happens? Hello, world! is printed in the interpreter window, which is exactly what we wanted. The interpreter prompt may be gone (depending on the version you’re using), but you can get it back by pressing Enter (in the interpreter window).
   Let’s extend our script to the following:

name = input("What is your name? ") 

print("Hello, " + name  + "!")

If you run this (remember to save it first), you should see the following prompt in the interpreter window:

What is your name?

Enter your name (for example, JC) and press Enter. You should get something like this:

Hello, JC!

Running Your Python Scripts from a Command Prompt 

Actually, there are several ways to run your programs. First, let’s assume you have a DOS window or a UNIX shell prompt before you and that the directory containing the Python executable (called python.exe in Windows, and python in UNIX) or the directory containing the executable (in Windows) has been put in your PATH environment variable.7 Also, let’s assume that your script from the previous section (hello.py) is in the current directory. Then you can execute your script with the following command in Windows:

C:\>python hello.py

or UNIX:

$ python hello.py

As you can see, the command is the same. Only the system prompt changes.

Making Your Scripts Behave Like Normal Programs 

Sometimes you want to execute a Python program (also called a script) the same way you execute other programs (such as your web browser or text editor), rather than explicitly using the Python interpreter. In UNIX, there is a standard way of doing this: have the first line of your script begin with the character sequence #! (called pound bang or shebang) followed by the absolute path to the program that interprets the script (in our case Python). Even if you didn’t quite understand that, just put the following in the first line of your script if you want it to run easily on UNIX:

#!/usr/bin/env python

This should run the script, regardless of where the Python binary is located. If you have more than one version of Python installed, you could use a more specific executable name, such as python3, rather than simply python. 
    Before you can actually run your script, you must make it executable.

$ chmod a+x hello.py

Now it can be run like this (assuming that you have the current directory in your path):

$ hello.py

If this doesn’t work, try using ./hello.py instead, which will work even if the current directory (.) is not part of your execution path (which a responsible sysadmin would probably tell you it shouldn’t be).
    If you like, you can rename your file and remove the py suffix to make it look more like a normal program.

If you don’t understand this sentence, you should perhaps skip the section. You don’t really need it.

What About Double-Clicking? 

In Windows, the suffix (.py) is the key to making your script behave like a program. Try double-clicking the file hello.py you saved in the previous section. If Python was installed correctly, a DOS window appears with the prompt “What is your name?”8 There is one problem with running your program like this, however. Once you’ve entered your name, the program window closes before you can read the result. The window closes when the program is finished. Try changing the script by adding the following line at the end:

input("Press <enter>")

Now, after running the program and entering your name, you should have a DOS window with the following contents:

What is your name? JC

Hello, JC! 

Press <enter>

Once you press the Enter key, the window closes (because the program is finished).

Comments 

The hash sign (#) is a bit special in Python. When you put it in your code, everything to the right of it is ignored (which is why the Python interpreter didn’t choke on the /usr/bin/env stuff used earlier). Here is an example:

# Print the circumference of the circle: 

print(2 * pi * radius)

The first line here is called a comment, which can be useful in making programs easier to understand— both for other people and for yourself when you come back to old code. It has been said that the first commandment of programmers is “Thou Shalt Comment” (although some less charitable programmers swear by the motto “If it was hard to write, it should be hard to read”). Make sure your comments say significant things and don’t simply restate what is already obvious from the code. Useless, redundant comments may be worse than none. For example, in the following, a comment isn’t really called for:

# Get the user's name: 

user_name = input("What is your name?")

It’s always a good idea to make your code readable on its own as well, even without the comments. Luckily, Python is an excellent language for writing readable programs.

Comments

Popular posts from this blog

Strings | Core Python 3.8

Strings  Now what was all that "Hello, " + name + "!" stuff about? The first program in this chapter was simply print("Hello, world!") It is customary to begin with a program like this in programming tutorials. The problem is that I haven’t really explained how it works yet. You know the basics of the print statement (I’ll have more to say about that later), but what is "Hello, world!"? It’s called a string (as in “a string of characters”). Strings are found in almost every useful, real-world Python program and have many uses. Their main use is to represent bits of text, such as the exclamation “Hello, world!” Single-Quoted Strings and Escaping Quotes Strings are values, just as numbers are: >>> "Hello, world!"  'Hello, world!' There is one thing that may be a bit surprising about this example, though: when Python printed out our string, it used single quotes, whereas we used double quotes. What’s the differ...

Lists and Tuples | Core Python 3.8

This chapter introduces a new concept: data structures. A data structure is a collection of data elements (such as numbers or characters, or even other data structures) that is structured in some way, such as by numbering the elements. The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number—its position, or index. The first index is zero, the second index is one, and so forth. Some programming languages number their sequence elements starting with one, but the zeroindexing convention has a natural interpretation of an offset from the beginning of the sequence, with negative indexes wrapping around to the end. If you find the numbering a bit odd, I can assure you that you’ll most likely get used to it pretty fast.     This chapter begins with an overview of sequences and then covers some operations that are common to all sequences, including lists and tuples. These operations will also work with strings, which will be use...

Functions and Modules | Core Python 3.8

Functions  In the “Numbers and Expressions” section, I used the exponentiation operator (**) to calculate powers. The fact is that you can use a function instead, called pow. >>> 2 ** 3  8  >>> pow(2, 3)  8 A function is like a little program that you can use to perform a specific action. Python has a lot of functions that can do many wonderful things. In fact, you can make your own functions, too (more about that later); therefore, we often refer to standard functions such as pow as built-in functions.     Using a function as I did in the preceding example is called calling the function. You supply it with arguments (in this case, 2 and 3), and it returns a value to you. Because it returns a value, a function call is simply another type of expression, like the arithmetic expressions discussed earlier in this chapter.6 In fact, you can combine function calls and operators to create more complicated expressions (like I did...

Exceptions | Core Python 3.8

When writing computer programs, it is usually possible to discern between a normal course of events and something that’s exceptional (out of the ordinary). Such exceptional events might be errors (such as trying to divide a number by zero) or simply something you might not expect to happen very often. To handle such exceptional events, you might use conditionals everywhere the events might occur (for example, have your program check whether the denominator is zero for every division). However, this would not only be inefficient and inflexible but would also make the programs illegible. You might be tempted to ignore these exceptional events and just hope they won’t occur, but Python offers an exception-handling mechanism as a powerful alternative.     In this tutorial, you’ll learn how to create and raise your own exceptions, as well as how to handle exceptions in various ways. What Is an Exception?  To represent exceptional conditions, Python uses exception obj...