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...

Variables and Statements | Core Python 3.8

Variables  Another concept that might be familiar to you is variables. If algebra is but a distant memory, don’t worry: variables in Python are easy to understand. A variable is a name that represents (or refers to) some value. For example, you might want the name x to represent 3. To make it so, simply execute the following: >>> x = 3 This is called an assignment. We assign the value 3 to the variable x. Another way of putting this is to say that we bind the variable x to the value (or object) 3. After you’ve assigned a value to a variable, you can use the variable in expressions. >>> x * 2  6 Unlike some other languages, you can’t use a variable before you bind it to something. There is no “default value.” ■ Note  the simple story is that names, or identifiers, in python consist of letters, digits, and underscore characters (_). they can’t begin with a digit, so Plan9 is a valid variable name, whereas Plan is not. Statements  Until...

Dictionaries: When Indices Won’t Do | Core Python 3.8

You’ve seen that lists are useful when you want to group values into a structure and refer to each value by number. In this chapter, you learn about a data structure in which you can refer to each value by name. This type of structure is called a mapping. The only built-in mapping type in Python is the dictionary. The values in a dictionary don’t have any particular order but are stored under a key, which may be a number, a string, or even a tuple. Dictionary Uses The name dictionary should give you a clue about the purpose of this structure. An ordinary book is made for reading from start to finish. If you like, you can quickly open it to any given page. This is a bit like a Python list. On the other hand, dictionaries—both real ones and their Python equivalent—are constructed so that you can look up a specific word (key) easily to find its definition (value).     A dictionary is more appropriate than a list in many situations. Here are some examples of uses of Pyth...

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...