In the previous article, we introduced some basic concepts about Python and how to use Python at the interactive command line. In this article, we will introduce variables, and also consider how to save a code module and run it, both from the command line and the Python IDLE interface.
The previous article contained the following Python statement:
>>>> a = 3+4
This was our first example of a Python variable. As you may have deduced, in Python, unlike C/C++ or some other languages, you don’t have to declare variables separately. You declare a variable when you use it for the first time. There are three distinct numeric types: integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of integers.
Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals yield integers. For example:
>>> x = 10
yields an integer variable x. Numeric literals containing a decimal point or an exponent sign yield floating point numbers. For example:
>>> x = 3.5
yields a floating point variable x.
You can also create a complex number. Appending ‘j’ or ‘J’ to a numeric literal yields an imaginary number to which you can add an integer or float to get a complex number with real and imaginary parts. For example:
>>> x = 10j + 5
creates a complex number with 5 as the real part and 10 as the imaginary part. You can retrieve both parts by typing:
>>> print(x)
or just the real or imaginary parts:
>>> print(x.real)
>>> print(x.imag)
The variables real and imag, however, are read-only variables and cannot be used to change the values of the real and imaginary components. The constructors int(), float() and complex() can be used to produce numbers of a specific type. For example:
>>> x = int(23)
creates an integer with a value of 23. Interestingly, leaving the parameter blank like this:
>>> x = int()
results in the value 0 being assigned to x.
Textual data in Python is handled with str objects, or strings. Strings are immutable sequences of Unicode code points. String literals can be written in several different ways – single quoted, double quoted, or triple quoted:
>>> text = ‘This is a test’
>>> text = “This is a test”
>>> text = ”’This is a test”’
>>> text = “””This is a test”””
Strings are immutable sequences of Unicode code points. Therefore:
>>> text[0] = ‘B’
is not allowed. However, if we want to print a single character from the string, we can do this:
>>> print(text[0])
or, if we want to print multiple characters that represent a subset of the string, we can specify two indices separater by a colon. For example:
>>> print(text[0:3])
will result in ‘This‘ being printed.
So far, we have been typing in programs at the interactive prompt, which has one big disadvantage: programs you type there go away as soon as the Python interpreter executes them. Because the code typed in interactively is never stored in a file, you cannot run it again without retyping it. To save programs permanently, you need to write your code in files, which are usually called modules. Modules are text files containing Python statements. Once a module is coded and saved in a file, you can ask the Python interpreter to execute the module any number of times.
To code a module, open your favorite text editor (e.g. Notepad in Windows, perhaps vi, emacs or gedit in Linux) and type some statements into a new text file called module01.py:
# My first Python script
name = str(input(‘Please enter your name: ‘)) # Read some input
print(‘Welcome to Python, ‘+name) # Print something out
In this module, we introduced three new concepts. The first line of the module is a comment. A hashtag (#) introduces a comment, which is just a description of what the program is doing. Comments can appear on a line by themselves or to the right of a statement. Multiline comments can be added, but must begin and end with three single quote marks, like this:
”’This is an example
of a multi-line comment that can be inserted into a Python script on the command line or in the Python IDLE interface”’
The other concept we introduced was the input function. input() simply reads characters from the standard input device (in this case, a keyboard). We used the str() constructor to ensure that name is created as a string.
The third concept we introduced was the plus sign (+) to concatenate the literal string ‘Welcome to Python, ‘ and name. As you probably guessed, the program will read in a string from the keyboard representing the user’s name, and will print out a welcome message containing the user’s name.
Once you have saved this text file, you can ask Python to run it by listing its full filename as the first argument to a python command, typed at the system command prompt; e.g.:
> python module01.py
Using the Python IDLE Interface to Run a Module
Alternatively, from the Python IDLE interface, you can navigate to File -> Open, and then browse to module01.py and open it. A new window should appear with the code for the module in it. Navigate to Run -> Module (or in Windows, just press F5) to run the module, and the output should appear in the main IDLE window, after it prints the “RESTART” banner message:
Please enter your name: Grumbledook
Welcome to Python, Grumbledook
There are other ways we can load a module. We could use the import command, assuming the module is within Python’s path:
>>> import module01
If we make changes to the code, we would have to use the reload command in order for them to take effect:
>>> from imp import reload
>>> reload(module01)
Finally, we could use the exec() and open.read() commands in conjunction to simultaneously load and run the module:
>>> exec(open(‘module01.py’).read())
These three options should work both at the command line and in the Python IDLE interface.
In the next article, we will introduce some additional concepts and also code our first Python function.
External Links:
Wikipedia article on Python IDLE interface
Recent Comments