Chapter 1 - Introduction To Python Programming
Chapter 1 - Introduction To Python Programming
I. Module Overview
If you do much work on computers, eventually you find that there’s some tasks you’d like to
automate. For example, you may wish to perform a search-and-replace over a large number of
text files, or rename and rearrange a bunch of photo files in a complicated way. Perhaps you’d
like to write a small custom database, or a specialized GUI application, or a simple game.
If you’re a professional software developer, you may have to work with several C/C++/Java
libraries but find the usual write/compile/test/re-compile cycle is too slow. Perhaps you’re
writing a test suite for such a library and find writing the testing code a tedious task. Or
maybe you’ve written a program that could use an extension language, and you don’t want to
design and implement a whole new language for your application.
This tutorial introduces the reader informally to the basic concepts and features of the Python
language and system. It helps to have a Python interpreter handy for hands-on experience,
but all examples are self-contained, so the tutorial can be read off-line as well.
After successfully completing this learning module, learner will be able to:
History
Python was conceived in the late 1980s and its implementation was started in December 1989 by
Guido van Rossum at CWI in Amsterdam. Python is a successor to the ABC programming language
(itself inspired by SETL) capable of exception handling and interfacing with the Amoeba operating
system. Van Rossum is Python's principal author, and his continuing central role in deciding the
direction of Python is reflected in the title given to him by the Python community, Benevolent Dictator
for Life (BDFL).
Rather than requiring all desired functionality to be built into the language's core, Python was
designed to be highly extensible. New built-in modules can be easily written in C, C++ or
Cython. Python can also be used as an extension language for existing modules and
applications that need a programmable interface. This design, a small core language with a
large standard library with an easily extensible interpreter, was intended by Van Rossum from
the very start because of his frustrations with ABC (which espoused the opposite mindset).
An important goal of the Python developers is making Python fun to use. This is reflected in
the origin of the name (based on the television series Monty Python's Flying Circus), in the
common practice of using Monty Python references in example code, and in an occasionally
playful approach to tutorials and reference materials.[24][25] For example, the metasyntactic
variables often used in Python literature are spam and eggs, instead of the traditional foo and
bar.
Usage
Python is often used as a scripting language for web applications, e.g. via mod_wsgi for the
Apache web server. With Web Server Gateway Interface, a standard API has been developed
to facilitate these applications. Web application frameworks like Django, Pylons, TurboGears,
web2py, Flask, and Zope support developers in the design and maintenance of complex
applications. Libraries like NumPy, SciPy, and Matplotlib allow Python to be used effectively
in scientific computing.
Indentation
Python uses whitespace indentation, rather than curly braces or keywords, to delimit blocks (a
feature also known as the off-side rule). An increase in indentation comes after certain
statements; a decrease in indentation signifies the end of the current block.
Methods
Methods on objects are functions attached to the object's class; the syntax
instance.method(argument) is, for normal methods and functions, syntactic sugar for
Class.method(instance, argument). Python methods have an explicit self parameter to access
instance data, in contrast to the implicit self in some other object-oriented programming
languages (for example, Java, C++ or Ruby).
Typing
Python uses duck typing and has typed objects but untyped variable names. Type constraints
are not checked at compile time; rather, operations on an object may fail, signifying that the
given object is not of a suitable type. Despite being dynamically typed, Python is strongly
typed, forbidding operations that are not well-defined (for example, adding a number to a
string) rather than silently attempting to make sense of them.
Mathematics
Python defines the modulus operator so that the result of a % b is in the half-open interval
[0,b), where b is a positive integer. When b is negative, the result lies in the interval (b,0].
However, this consequently affects how integer division is defined. To maintain the validity of
the equation b * (a // b) + a % b == a, integer division is defined to round towards minus
infinity. Therefore 7 // 3 is 2, but (−7) // 3 is −3. This is different from many programming
languages, where the result of integer division rounds towards zero, and Python's modulus
operator is consequently defined in a way that can return negative numbers.
Implementations
CPython
The mainstream Python implementation, known as CPython, is written in C meeting the C89
standard. CPython compiles Python programs into intermediate bytecode,[65] which are then
executed by the virtual machine. It is distributed with a large standard library written in a
mixture of C and Python. CPython ships in versions for many platforms, including Microsoft
Windows and most modern Unix-like systems. CPython was intended from almost its very
conception to be cross-platform; its use and development on esoteric platforms such as
Amoeba, alongside more conventional ones like Unix and Mac OS, has greatly helped in this
regard. Unofficial builds are also available for Android and iOS.
Jython compiles the Python program into Java byte code, which can then be executed by every
Java Virtual Machine implementation. This also enables the use of Java class library functions
from the Python program. IronPython follows a similar approach in order to run Python
programs on the .NET Common Language Runtime. PyPy is a fast self-hosting
implementation of Python, written in Python, that can output several types of bytecode, object
code and intermediate languages. There also exist compilers to high-level object languages,
with either unrestricted Python, a restricted subset of Python, or a language similar to Python
as the source language. PyPy is of this type, compiling RPython to several languages; other
examples include Pyjamas compiling to JavaScript; Shed Skin compiling to C++; and Cython
and Pyrex compiling to C.
Interpretational semantics
Other shells add capabilities beyond those in the basic interpreter, including IDLE and
IPython. While generally following the visual style of the Python shell, they implement
features like auto-completion, retention of session state, and syntax highlighting.
Development
Python's development is conducted largely through the Python Enhancement Proposal (PEP)
process, described in PEP 1. PEPs are standardized design documents providing general
information related to Python, including proposals, descriptions, design rationales, and
explanations for language features. Outstanding PEPs are reviewed and commented upon on
the python-dev mailing list, which is the primary forum for discussion about the language's
development and approved by the Steering Council (see PEP 13 for the governance model);
specific issues are discussed in the bug tracker maintained at bugs.python.org. Development of
the reference implementation takes place on the GitHub cpython repository.
CPython's public releases come in three types, distinguished by which part of the version
number is incremented:
Standard library
Python has a large standard library, commonly cited as one of Python's greatest strengths,[81]
providing pre-written tools suited to many tasks. This is deliberate and has been described as a
"batteries included" Python philosophy. The modules of the standard library can be augmented
with custom modules written in either C or Python. Boost C++ Libraries includes a library,
Boost.Python, to enable interoperability between C++ and Python. Because of the wide variety
of tools provided by the standard library, combined with the ability to use a lower-level
language such as C and C++, which is already capable of interfacing between other libraries,
Python can be a powerful glue language between languages and tools.
Some parts of the standard library are covered by specifications (for example, the WSGI
implementation wsgiref follows PEP 333), but the majority of the modules are not. They are
specified by their code, internal documentation, and test suite (if supplied). However, because
most of the standard library is cross-platform Python code, there are only a few modules that
must be altered or completely rewritten by alternative implementations.
For software testing, the standard library provides the unittest and doctest modules.
Python's design and philosophy have influenced several programming languages, including:
• Pyrex and its derivative Cython are code translators that are targeted at writing fast C
extensions for the CPython interpreter. The language is mostly Python with syntax
extensions for C and C++ features. Both languages produce compilable C code as
output.
• Boo uses indentation, a similar syntax, and a similar object model. However, Boo uses
static typing and is closely integrated with the .NET framework.[84]
• Cobra uses indentation and similar syntax. Cobra's "Acknowledgements" document
lists Python first among the languages that influenced it. However, Cobra directly
supports design-by-contract, unit tests and optional static typing.
• \ borrowed iterators, generators, and list comprehensions from Python.
• Go is described as incorporating the "development speed of working in a dynamic
language like Python".
• Groovy was motivated by the desire to bring the Python design philosophy to Java.
• OCaml has an optional syntax, called twt (The Whitespace Thing), inspired by Python
and Haskell.
Requirements
• Python 3.9.0 Interpreter
• Text Editor
o Sublime
o VS Code
• IDE (Optional)
o PyCharm
The Python interpreter and the extensive standard library are freely available in source or binary
form for all major platforms from the Python web site, https://www.python.org/, and may be
freely distributed. The same site also contains distributions of and pointers to many free third-
party Python modules, programs and tools, and additional documentation.
On Windows machines where you have installed Python from the Microsoft Store, the python3.9
command will be available. If you have the py.exe launcher installed, you can use the py
command. See setting-envvars for other ways to launch Python.
The interpreter’s line-editing features include interactive editing, history substitution and code
completion on systems that support the GNU Readline library. Perhaps the quickest check to see
whether command line editing is supported is typing Control-P to the first Python prompt you
get. If it beeps, you have command line editing; see Appendix Interactive Input Editing and
History Substitution for an introduction to the keys. If nothing appears to happen, or if ^P is
echoed, command line editing isn’t available; you’ll only be able to use backspace to remove
characters from the current line.
The interpreter operates somewhat like the Unix shell: when called with standard input
connected to a tty device, it reads and executes commands interactively; when called with a file
name argument or with a file as standard input, it reads and executes a script from that file.
A second way of starting the interpreter is python -c command [arg] ..., which executes the
statement(s) in command, analogous to the shell’s -c option. Since Python statements often
contain spaces or other characters that are special to the shell, it is usually advised to quote
Argument Passing
When known to the interpreter, the script name and additional arguments thereafter are turned
into a list of strings and assigned to the argv variable in the sys module. You can access this list
by executing import sys. The length of the list is at least one; when no script and no arguments
are given, sys.argv[0] is an empty string. When the script name is given as '-' (meaning standard
input), sys.argv[0] is set to '-'. When -c command is used, sys.argv[0] is set to '-c'. When -m
module is used, sys.argv[0] is set to the full name of the located module. Options found after -c
command or -m module are not consumed by the Python interpreter’s option processing but left
in sys.argv for the command or module to handle.
Interactive Mode
When commands are read from a tty, the interpreter is said to be in interactive mode. In this
mode it prompts for the next command with the primary prompt, usually three greater-than signs
(>>>); for continuation lines it prompts with the secondary prompt, by default three dots (...).
The interpreter prints a welcome message stating its version number and a copyright notice
before printing the first prompt:
$ python3.9
Python 3.9 (default, June 4 2019, 09:25:04)
[GCC 4.8.2] on linux Type "help", "copyright", "credits" or "license" for more information.
>>>
Continuation lines are needed when entering a multi-line construct. As an example, take a look at
this if statement:
By default, Python source files are treated as encoded in UTF-8. In that encoding, characters of
most languages in the world can be used simultaneously 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 these characters properly, your
editor must recognize that the file is UTF-8, and it must use a font that supports all the characters
in the file.
To declare an encoding other than the default one, a special comment line should be added as the
first line of the file. The syntax is as follows:
where encoding is one of the valid codecs supported by Python. For example, to declare that
Windows-1252 encoding is to be used, the first line of your source code file should be:
One exception to the first line rule is when the source code starts with a UNIX “shebang” line. In
this case, the encoding declaration should be added as the second line of the file. For example:
#!/usr/bin/env python3
# -*- coding: cp1252 -*-
3. Choose the project location. Click … button next to the Location field and specify the
directory for your project.
4. Also, deselect the Create a main.py welcome script checkbox because you will
create a new Python file for this tutorial.
When configuring the base interpreter, you need to specify the path to the Python
executable. If PyCharm detects no Python on your machine, it provides two options:
to download the latest Python versions from python.org or to specify a path to the
Python executable (in case of non-standard installation).
Now click the Create button at the bottom of the New Project dialog.
If you’ve already got a project open, after clicking Create PyCharm will ask you whether to
open a new project in the current window or in a new one. Choose Open in current window -
this will close the current project, but you'll be able to reopen it later.
Choose the keyword class and type the class name, Car.
Note that PyCharm analyses your code on-the-fly, the results are immediately shown in the
inspection indicator in the upper-right corner of the editor. This inspection indication works
like a traffic light: when it is green, everything is OK, and you can go on with your code; a
yellow light means some minor problems that however will not affect compilation; but when
the light is red, it means that you have some serious errors. Click it to preview the details in
the Problems tool window.
3. Let's continue creating the function __init__: when you just type the opening
brace, PyCharm creates the entire code construct (mandatory parameter self,
closing brace and colon), and provides proper indentation.
5. Let's copy and paste the entire code sample. Click the copy button in the upper-right
corner of the code block here in the help page, then paste it into the PyCharm editor
replacing the content of the Car.py file:
class Car:
def say_state(self):
print("I'm going {} kph!".format(self.speed))
def accelerate(self):
self.speed += 5
def brake(self):
if self.speed < 5:
self.speed = 0
else:
self.speed -= 5
def average_speed(self):
if self.time != 0:
return self.odometer / self.time
else:
pass
if __name__ == '__main__':
my_car = Car()
print("I'm a car!")
while True:
action = input("What should I do? [A]ccelerate, [B]rake, "
"show [O]dometer, or show average [S]peed?").upper()
if action not in "ABOS" or len(action) != 1:
print("I don't know how to do that")
continue
if action == 'A':
my_car.accelerate()
elif action == 'B':
my_car.brake()
elif action == 'O':
print("The car has driven {}
kilometers".format(my_car.odometer))
elif action == 'S':
print("The car's average speed was {}
kph".format(my_car.average_speed()))
my_car.step()
my_car.say_state()
At this point, you're ready to run your first Python application in PyCharm.
Run your Application
Use either of the following ways to run your code:
• Right-click the editor and select Run 'Car' from the context menu .
• Press Ctrl+Shift+F10.
• Since this Python script contains a main function, you can click an icon in the
gutter. If you hover your mouse pointer over it, the available commands show up:
Here you can enter the expected values and preview the script output.
The run/debug configuration defines the way PyCharm executes your code. You can save it
to make it a permanent configuration or modify its parameters.
Summary
Congratulations on completing your first script in PyCharm! Let's repeat what you've done
with the help of PyCharm:
• Created a project.
• Created a file in the project.
• Created the source code.
• Ran this source code.