Python: An Introductory Tutorial

Python is a powerful, easy-to-learn programming language. Object-oriented programming is simple but effective thanks to its efficient high-level data structures. Scripting and rapid application development in many areas on most platforms are

C or C++ (or any other language that can be called from C) can be used to extend the Python interpreter with new functions and data types. Python can also be used to customize applications.

It is not my intention to cover every single feature, or even every commonly used feature, in this blog post. This will introduce you to Python’s most notable features and give you a sense of how the style and flavour of the language differ from other languages.

Over time, if you use computers a lot, you will find that there are some tasks you would like to automate. In some cases, you might wish to perform a search-and-replace on a large number of text files or rename and rearrange a bunch of photos in a complicated fashion. Imagine creating your custom database, or an application specialized to a particular task or even a simple game.

Some people work in the software development world who are responsible for handling many C/C++/Java libraries, however, the usual write/compile/test/recompile cycle is simply too slow. When you are writing a test suite for such a library, it may be tedious to write test code. Don’t worry about designing and implementing a whole new language if you have written a program that only needs a custom extension.

Several of these tasks can be accomplished by writing a Unix shell script or creating Windows batch files, but shell scripts are good for moving around files and changing text data, not GUI applications or games. C/C++/Java programs can be written, but it can take a lot of development time to come up with even a first draft. You can use Python on Windows, Mac OS, and Unix operating systems, and it is simpler to use.

In spite of being simple to use, Python is an actual programming language, offering more structure and support for large programs than shell scripts and batch files. Python, though a high-level language, also has built-in data types like arrays and dictionaries, and, as a result, offers much more error checking than C. As a result, Python is suited to a much broader problem domain than Awk or even Perl, but many things are at least as easy in Python.

A Python program can be split into modules that can be reused in other Python programs. Python comes with a large collection of standard modules that you can use as a foundation for your programs – or as examples for learning Python programming. Some of these modules provide file I/O, system calls, sockets, and even interfaces to graphical user interface toolkits such as Tk.

Python is an interpreted language, which means it doesn’t require you to compile and link, which can save you considerable time when developing programs. It is possible to use the interpreter interactively, so it is easy to experiment with language features, write throw-away programs, or test functions during bottom-up development. You can also use it as a desk calculator.

Programs can be written in Python in a compact and readable manner. For several reasons, Python programs are typically much shorter than equivalent C, C++, or Java programs:

  • A high-level data type allows complex operations to be expressed in one statement;
  • Instead of beginning and ending brackets, indentation is used for grouping statements;
  • Variables and arguments do not need to be declared.

The Python interpreter can be extended with new functions and modules written in C, either for performing critical operations at maximum speed or for linking Python programs to libraries in binary form (such as a graphics library). As you become familiar with Python, you can integrate it into applications written in C and use it as an extension or command language for the applications.

In case you were wondering, the language is named after the BBC television show “Monty Python’s Flying Circus” and has nothing to do with reptiles. Python’s allure has now inspired you to spend some time examining it further.

Using the Python Interpreter

Invoking the Interpreter

Python is typically installed as /usr/local/bin/python3.11 on machines that have it; placing /usr/local/bin in the search path of your Unix shell allows you to start it with the following command:

python3.11

to the shell. There are many possible places for the interpreter to live because choosing the directory to live in is a design choice. Consult your local Python expert or your system administrator. (For example, you can install Python in /usr/local/python.)

The python3.11 command will be available on Windows machines where Python has been installed from the Microsoft Store. Using the py command is easy if you have py.exe installed. Other ways to launch Python are described in Excursus: Setting environment variables.

When you type a character indicating end-of-file at the primary prompt (Control-D on Unix, Control-Z on Windows), the interpreter will terminate. The following command can be used to exit the interpreter: quit().

On systems that support the GNU Readline library, the interpreter supports interactive editing, history substitution and code completion during line editing. To see whether command line editing is supported, type Control-P to the first Python prompt. In Appendix Interactive Input Editing and History Substitution, you can find a list of the commands that will beep if you are using command-line editing. If nothing happens, or if ^P is echoed, you will not be able to use the command line; you will only be able to use backspace to remove characters from the current line.

When called using standard input using a TTY, the interpreter reads and executes commands interactively; when called with a file name argument or with a file as standard input, it will read and execute scripts from that file.

Python is also available as python -c command [argument] …, which executes the command(s) in command. This is analogous to the -c option on a shell. In Python, since statements frequently contain spaces and other special shell characters, the command is usually quoted with single quotes in its entirety.

Modules in Python can also be used as scripts. Lastly, you can invoke these using python -m module [arg] …, which executes the source file for the module as if it were named.

There is some value to being able to run a script and then enter interactive mode afterwards when using a script file. You can do this by passing -i before the script.

The Command-line and environment section describe all command-line options.

Argument Passing

The script name and any additional arguments thereafter are assigned to the argv variable in the sys module when they are known to the interpreter. This list can be accessed by executing import sys. sys.argv[0] is an empty string when no script or arguments are given; otherwise, it contains a single line of the script. The default setting for sys.argv[0] when the script name is ‘-‘ (standard input) is ‘-‘. The -c command sets sys.argv[0] to ‘-c’. A module’s name is retrieved from sys.argv[0] when the -m module is used. Python’s interpreter does not consume optional arguments found after a -c command or -m module but instead leaves them in sys.argv for the command or module to handle.

Interactive Mode

The interpreter is said to be in interactive mode when it reads commands from a tty. If the next command is to be entered at the primary prompt it prompts with three greater-than signs ( >>>); for continuation lines, it prompts with three dots (…). Before printing the first prompt, the interpreter prints a welcome message and a copyright notice:

$ python3.11
Python 3.11 (default, June 5 2021, 08:00:05)
[GCC 10.2.0] on linux
Type “help”, “copyright”, “credits” or “license” for more information.
>>>

Multi-line constructs require continuation lines. Here’s an example:

>> the_world_is_flat = True
>>> if the_world_is_flat:
… print(“The world is not round!”)

The world is not round!

The Interpreter and Its Environment

Source Code Encoding

Python source files are treated as UTF-8 by default. The encoding allows characters from virtually any language to be used in string literals, identifiers, and comments – although the standard library only uses ASCII characters for identifiers, a convention that any portable code should follow. To display all of these characters correctly, your editor must recognize that the file is UTF-8, and it must use a font that supports all the characters in the file.

It is necessary to add a special comment line as the first line of the file to declare an alternative encoding than the default one. The syntax is:

-*- coding: encoding -*-

Python supports several valid codecs including encoding.

As an example, the first line of your source code file should declare that Windows-1252 encoding is to be used:

# -*- coding: cp1252 -*-

When the source code starts with a UNIX “shebang” line, the first line rule does not apply. As a result, the encoding declaration should be added as the second line of the file. As an example:

#!/usr/bin/env python3
# -*- coding: cp1252 -*-

An Informal Introduction to Python

For input and output, prompts (>>> and …) are used to distinguish them: to repeat an example, type everything after the prompt when it appears; lines that don’t begin with prompts are output by the interpreter. It is important to note that you must type a blank line at the end of a multi-line command when a secondary prompt appears on a line by itself.

An example box can be toggled to display prompts and output by clicking on >>> in the upper-right corner. You can copy and paste the input lines into your interpreter if you hide the prompts and output, for example.

Even those examples entered at the interactive prompt contain comments. Python comments start with the hash character, #, and extend to the end of the line. Comment lines may begin with whitespace or code, but not with a string literal. Hash characters are just characters within string literals. When typing examples, comments can be omitted since they are not interpreted by Python and are for clarification.

Here are some examples:
Despite

# this is the first comment
spam = 1 # and this is the second comment
# … and now a third!
text = “# This is not a comment because it’s inside quotes.”

Leave a Reply

Your email address will not be published.