100% found this document useful (2 votes)
19 views

A Beginners Guide to Python 3 Programming 2nd Edition John Huntdownload

The document is a promotional overview of various Python programming books, including 'A Beginner's Guide to Python 3 Programming' by John Hunt, which is now in its second edition. It highlights the book's updates, including new chapters and features introduced in Python 3.11, and emphasizes its suitability for beginners as well as advanced topics. Additionally, it provides links to download the books and mentions the availability of supplementary resources online.

Uploaded by

larbimasuma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
19 views

A Beginners Guide to Python 3 Programming 2nd Edition John Huntdownload

The document is a promotional overview of various Python programming books, including 'A Beginner's Guide to Python 3 Programming' by John Hunt, which is now in its second edition. It highlights the book's updates, including new chapters and features introduced in Python 3.11, and emphasizes its suitability for beginners as well as advanced topics. Additionally, it provides links to download the books and mentions the availability of supplementary resources online.

Uploaded by

larbimasuma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

A Beginners Guide to Python 3 Programming 2nd

Edition John Hunt pdf download

https://ebookmass.com/product/a-beginners-guide-to-
python-3-programming-2nd-edition-john-hunt/

Explore and download more ebooks at ebookmass.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmass.com
to discover even more!

Advanced Guide to Python 3 Programming, 2nd 2nd Edition


John Hunt

https://ebookmass.com/product/advanced-guide-to-
python-3-programming-2nd-2nd-edition-john-hunt/

Python Mini Reference 2022: A Quick Guide to the Modern


Python Programming Language for Busy Coders (A
Hitchhiker's Guide to the Modern Programming Languages
Book 3) Harry Yoon
https://ebookmass.com/product/python-mini-reference-2022-a-quick-
guide-to-the-modern-python-programming-language-for-busy-coders-a-
hitchhikers-guide-to-the-modern-programming-languages-book-3-harry-
yoon/

Python for Beginners: Master Python Programming from


Basics to Advanced Level Tim Simon

https://ebookmass.com/product/python-for-beginners-master-python-
programming-from-basics-to-advanced-level-tim-simon/

Python Programming for Beginners: 2 Books in 1 - the


Ultimate Step-By-Step Guide to Learn Python Programming
Quickly With Practical Exercises Mark Reed
https://ebookmass.com/product/python-programming-for-
beginners-2-books-in-1-the-ultimate-step-by-step-guide-to-learn-
python-programming-quickly-with-practical-exercises-mark-reed/
PYTHON PROGRAMMING: 3 MANUSCRIPTS CRASH COURSE CODING WITH
PYTHON DATA SCIENCE. THE STEP BY STEP GUIDE FOR BEGINNERS
TO MASTER SOFTWARE PROJECTS, ALGORITHMS, TRICKS AND TIPS
Tacke
https://ebookmass.com/product/python-programming-3-manuscripts-crash-
course-coding-with-python-data-science-the-step-by-step-guide-for-
beginners-to-master-software-projects-algorithms-tricks-and-tips-
tacke/

Python Programming: 3 Books in 1: Ultimate Beginneru2019s,


Intermediate & Advanced Guide to Learn Python Step-by-Step

https://ebookmass.com/product/python-programming-3-books-
in-1-ultimate-beginners-intermediate-advanced-guide-to-learn-python-
step-by-step/

MicroPython for the Internet of Things: A Beginner’s Guide


to Programming with Python on Microcontrollers 2nd Edition
Bell
https://ebookmass.com/product/micropython-for-the-internet-of-things-
a-beginners-guide-to-programming-with-python-on-microcontrollers-2nd-
edition-bell/

Modern C for Absolute Beginners: A Friendly Introduction


to the C Programming Language 2nd Edition Slobodan
Dmitrovi■
https://ebookmass.com/product/modern-c-for-absolute-beginners-a-
friendly-introduction-to-the-c-programming-language-2nd-edition-
slobodan-dmitrovic/

Learning Scientific Programming with Python 2nd Edition


Christian Hill

https://ebookmass.com/product/learning-scientific-programming-with-
python-2nd-edition-christian-hill-2/
Undergraduate Topics in Computer Science

John Hunt

A Beginners
Guide to Python 3
Programming
Second Edition
Undergraduate Topics in Computer Science

Series Editor
Ian Mackie, University of Sussex, Brighton, UK

Advisory Editors
Samson Abramsky , Department of Computer Science, University of Oxford,
Oxford, UK
Chris Hankin , Department of Computing, Imperial College London, London,
UK
Mike Hinchey , Lero – The Irish Software Research Centre, University of
Limerick, Limerick, Ireland
Dexter C. Kozen, Department of Computer Science, Cornell University, Ithaca,
NY, USA
Andrew Pitts , Department of Computer Science and Technology, University of
Cambridge, Cambridge, UK
Hanne Riis Nielson , Department of Applied Mathematics and Computer
Science, Technical University of Denmark, Kongens Lyngby, Denmark
Steven S. Skiena, Department of Computer Science, Stony Brook University, Stony
Brook, NY, USA
Iain Stewart , Department of Computer Science, Durham University, Durham,
UK
Joseph Migga Kizza, College of Engineering and Computer Science, The
University of Tennessee-Chattanooga, Chattanooga, TN, USA
‘Undergraduate Topics in Computer Science’ (UTiCS) delivers high-quality instruc-
tional content for undergraduates studying in all areas of computing and information
science. From core foundational and theoretical material to final-year topics and
applications, UTiCS books take a fresh, concise, and modern approach and are ideal
for self-study or for a one- or two-semester course. The texts are all authored by
established experts in their fields, reviewed by an international advisory board, and
contain numerous examples and problems, many of which include fully worked
solutions.
The UTiCS concept relies on high-quality, concise books in softback format, and
generally a maximum of 275–300 pages. For undergraduate textbooks that are likely
to be longer, more expository, Springer continues to offer the highly regarded Texts
in Computer Science series, to which we refer potential authors.
John Hunt

A Beginners Guide to Python


3 Programming
Second Edition
John Hunt
Midmarsh Technology Ltd.
Chippenham, Wiltshire, UK

ISSN 1863-7310 ISSN 2197-1781 (electronic)


Undergraduate Topics in Computer Science
ISBN 978-3-031-35121-1 ISBN 978-3-031-35122-8 (eBook)
https://doi.org/10.1007/978-3-031-35122-8

1st edition: © Springer Nature Switzerland AG 2019, corrected publication 2020


2nd edition: © Springer Nature Switzerland AG 2023

This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of
the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology
now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication
does not imply, even in the absence of a specific statement, that such names are exempt from the relevant
protective laws and regulations and therefore free for general use.
The publisher, the authors, and the editors are safe to assume that the advice and information in this book
are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or
the editors give a warranty, expressed or implied, with respect to the material contained herein or for any
errors or omissions that may have been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.

This Springer imprint is published by the registered company Springer Nature Switzerland AG
The registered company address is: Gewerbestrasse 11, 6330 Cham, Switzerland
This book is simply for Denise, the love of my
life.
Preface the Second Edition

I am writing this preface to the second edition of this book in the middle of 2023,
and I am reflecting on what has happened to Python over the last 4 to 5 years.
Python itself has gone from strength to strength, its popularity has not diminished
and if anything has increased. I increasingly come across organizations in all walks
of life that are actively using the language. This is true whether they are schools,
colleges or universities, charities, governmental organization, research institutions
or commercial enterprises. The uses being made of Python keeps on growing and
the ecosystem of supporting libraries available keeps on growing.
This edition represents a significant update from Python 3.7 (which was the current
version when the first edition of the book was written) to Python 3.11 (and a look
ahead to Python 3.12). It also represents a significant extension to the original book
with an additional eight chapters. These chapters represent topics and questions that
those learning Python have expressed an interest in such as frozensets, enumer-
ated types and sorting functions to Python virtual environments. It also reflects new
features in the language such as pattern matching introduced in Python 3.10 and
Exception Groups handling and Exception Notes introduced in Python 3.11.
The book also now includes a chapter entitled ‘Python Bites Back’ which high-
lights for someone learning Python, 14 of the most common mistakes made by a
Python beginner. This chapter can be dropped into at any time but covers the whole
of the language discussed in this book so some sections may be more relevant once
the whole book has been read.

Chippenham, UK John Hunt

vii
Preface to the First Edition

There is currently huge interest in the Python programming language. This is driven
by several factors; its use in schools with the Raspberry Pi platform, its ability to be
used for DevOps scripts, its use in Data Science and Machine Learning and of course
the language itself. Plus of course it is free! So anyone anywhere can download and
install Python and get started.
There are many books on Python; however, most assume previous programming
experience or are focused on particular aspects of Python use such as Data Science
or Machine Learning or have a scientific flavor.
The aim of this book is to introduce Python to those with little or very little
programming knowledge, but to take them through to become an experienced Python
developer.
As such the earlier parts of the book introduce fundamental concepts such as
what a variable is and how a for loop works. In contrast the later chapters intro-
duce advanced concepts such as Functional Programming, object orientation and
exception handling.
In between a wide range of topics are introduced and discussed from a Python
point of view including functions, recursion, operators, Python properties, modules
and packages, protocols and monkey patching, etc.
After the core elements of Python are established each new subject area is intro-
duced by way of an introductory chapter presenting the topic in general, providing
background on that subject, why it is of importance, etc. These introductions cover
structure analysis, functional programming and object orientation.
Some of the key aspects of this book are:
1. It assumes very little knowledge or experience of Python or programming.
2. It provides a basic introduction to Python as well as advanced topics such as
generators and coroutines.
3. This book provides extensive coverage of object orientation and the features in
Python 3 supporting classes, inheritance and protocols.
4. Pythons’ support for functional programming is also presented.

ix
x Preface to the First Edition

5. Following on from introducing the basic ideas behind functional programming,


the book presents how advanced functional concepts such as closures, currying
and higher-order functions work in Python.
6. The book includes exercises at the end of most chapters with online solutions
7. There are several case studies spread through the book that broaden understanding
of preceding topics.
8. All code examples (and exercise solutions) are provided online in a GitHub
repository.

Chapter Organization

Each chapter has a brief introduction, the main body of the chapter, followed by a
list of (typically) online references that can be used for further reading.
Following this there is typically an Exercises section that lists one or more
exercises that build on the skills you will have learnt in that chapter.
Sample solutions to the exercises are available in a GitHub online repository that
supports this book.

What You Need

You can of course just read this book; however following the examples in this book
will ensure that you get as much as possible out of the content.
For this you will need a computer.
Python is a cross platform programming language and as such you can use Python
on a Windows PC, a Linux box or a Apple Mac, etc. So you are not tied to a particular
type of operating system; you can use whatever you have available.
However you will need to install some software on that computer. At a minimum
you will need Python.
This book focuses on Python 3 so you will need that. Some guidance on this is
provided in Chap. 2 on setting up your environment.
You will also need some form of editor in which to write your programs. There
are numerous generic programming editors available for different operating systems
with VIM on Linux, Notepad++ on Windows and Sublime Text on Windows and
Macs being popular choices.
However, using a Integrated Development Environment (IDE) editor such as
PyCharm or potential Visual Studio Code will make writing and running your
programs much easier.
Preface to the First Edition xi

Using an IDE

The IDE I prefer for Python is PyCharm, it is not the only IDE for Python by any
means, but it is a very widely used one.
Other IDEs available for Python include:
● Spyder which is an IDE often used by scientists and engineers see https://www.
spyder-ide.org/.
● Jupiter Notebook which is a web-based IDE and is particularly good for data
scientists https://jupyter.org/.
● Visual Studio Code. This is a very good free editor from Microsoft that has really
useful features https://code.visualstudio.com.
● Sublime Text is more of a text editor that color codes Python; however for a simple
project it may be all you need https://www.sublimetext.com.
Mostly this book is editor or IDE agnostic only Chap. 3 ‘Setting up the Python
Environment’ and Chap. 42 ‘Python Virtual Environments’ really focus on PyCharm.
You can therefore use whatever editor you wish to use.

Conventions

Throughout this book you will find a number of conventions used for text styles.
These text styles distinguish different kinds of information.
Code words, variables and Python values, used within the main body of the text,
are shown using a Courier font. For example:
This program creates a top level window (the wx.Frame) and gives it a title. It also creates
a label (a wx.StaticText object) to be displayed within the frame.

In the above paragraph wx.Frame and wx.StaticText are classes available in a


Python graphical user interface library.
A block of Python code is set out as shown here:
num = int(input( ’Enter another number: ’))
if num > 0:
print(num, ’is positive’)
print(num, ’squared is ’, num * num)
print(’Bye’)
Note that keywords and points of interest are shown in bold font.
Any command line or user input is shown in italics and is also bold:
Visit https://ebookmass.com today to explore
a vast collection of ebooks across various
genres, available in popular formats like
PDF, EPUB, and MOBI, fully compatible with
all devices. Enjoy a seamless reading
experience and effortlessly download high-
quality materials in just a few simple steps.
Plus, don’t miss out on exciting offers that
let you access a wealth of knowledge at the
best prices!
xii Preface to the First Edition

> python hello.py


Or
Hello, world
Enter your name:John
Hello John

Example Code and Sample Solutions

The examples used in this book (along with sample solutions for the exercises at the
end of most chapters) are available in a GitHub repository. GitHub provides a web
interface and a server environment hosting Git.
Git is a version control system typically used to manage source code files (such
as those used to create systems in programming languages such as Python but also
Java, C#, C++, Scala, etc.). Systems such as Git are very useful for collaborative
development as they allow multiple people to work on an implementation and to
merge their work together. They also provide a useful historical view of the code
(which also allows developers to roll back changes if modifications prove to be
unsuitable).
If you already have Git installed on your computer then you can clone (obtain a
copy of) the repository locally using:
git clone https://github.com/johnehunt/beginnerspython
3_2nd
If you do not have git then you can obtain a zip file of the examples using
https://github.com/johnehunt/beginnerspython3_2nd/arc
hive/master.zip
You can of course install Git yourself if you wish. To do this see https://git-scm.
com/downloads. Versions of the Git client for Mac OS, Windows and Linux/Unix
are available here.
However, many IDEs such as PyCharm come with Git support and so offer another
approach to obtaining a Git repository.
For more information on Git see http://git-scm.com/doc. This Git guide provides
a very good primer and is highly recommended.

Bath, UK John Hunt


Contents

1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 What is Python? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Python Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Python History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Python Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Python Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 Python Execution Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.7 Running Python Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.7.1 Interactively Using the Python Interpreter . . . . . . . . . . 6
1.7.2 Running a Python File . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.7.3 Executing a Python Script . . . . . . . . . . . . . . . . . . . . . . . 9
1.7.4 Using Python in an IDE . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.8 Jupyter Notebooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.9 Useful Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2 Where is Python Used . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.1.1 Data Analytics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.1.2 Machine Learning and AI . . . . . . . . . . . . . . . . . . . . . . . . 17
2.1.3 Database Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.1.4 Python for Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.1.5 Python for Film Making . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.1.6 Cross Platform UIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.1.7 Games Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.1.8 Integration Testing Framework . . . . . . . . . . . . . . . . . . . 20
2.1.9 Academic Research . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.1.10 Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.2 Useful Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

xiii
xiv Contents

3 Setting up the Python Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23


3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.2 Check to See if Python is Installed . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.3 Installing Python on a Windows PC . . . . . . . . . . . . . . . . . . . . . . . . 25
3.3.1 Step 1: Downloading Python . . . . . . . . . . . . . . . . . . . . . 25
3.3.2 Step 2: Running the Installer . . . . . . . . . . . . . . . . . . . . . 26
3.3.3 Step 3: Set up the PATH (Optional) . . . . . . . . . . . . . . . . 27
3.3.4 Step 4: Verify the Installation . . . . . . . . . . . . . . . . . . . . . 29
3.3.5 Step 5: Run Some Python . . . . . . . . . . . . . . . . . . . . . . . . 30
3.3.6 Step 6: Exit the Python Interpreter . . . . . . . . . . . . . . . . 30
3.4 Setting up on a Mac . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.5 Setting up an IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.5.1 Downloading the PyCharm IDE . . . . . . . . . . . . . . . . . . 33
3.5.2 Setting up the IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.6 Writing Python Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.7 A Note on Filenames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4 A First Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.2 Hello World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.3 Interactive Hello World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.4 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.5 Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.6 Assignment Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
4.7 Python Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.8 Comments in Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.9 Scripts Versus Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5 Python Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.2 What Are Strings? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.3 Representing Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.4 What Type is String? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.5 What Can You Do with Strings? . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.5.1 String Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.5.2 Length of a String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.5.3 Accessing a Character . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.5.4 Accessing a Subset of Characters . . . . . . . . . . . . . . . . . 55
5.5.5 Repeating Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.5.6 Splitting Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.5.7 Counting Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.5.8 Replacing Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.5.9 Finding Sub Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Contents xv

5.5.10 Converting Other Types into Strings . . . . . . . . . . . . . . . 57


5.5.11 Remove Prefix and Suffix . . . . . . . . . . . . . . . . . . . . . . . . 58
5.5.12 Comparing Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
5.5.13 Other String Operations . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.6 Hints on Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.6.1 Python Strings are Case Sensitive . . . . . . . . . . . . . . . . . 60
5.6.2 Function/Method Names . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.6.3 Function/Method Invocations . . . . . . . . . . . . . . . . . . . . . 60
5.7 String Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
5.8 String Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.9 Formatting Using f-strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
5.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
5.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
6 Numbers, Booleans and None . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
6.2 Types of Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
6.3 Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.3.1 Converting to Ints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.4 Floating Point Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.4.1 Converting to Floats . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.4.2 Converting an Input String into a Floating Point
Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.5 Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
6.6 Boolean Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
6.7 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
6.7.1 Integer Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6.7.2 Negative Number Integer Division . . . . . . . . . . . . . . . . 77
6.7.3 Floating Point Number Operators . . . . . . . . . . . . . . . . . 77
6.7.4 Integers and Floating Point Operations . . . . . . . . . . . . . 78
6.7.5 Complex Number Operators . . . . . . . . . . . . . . . . . . . . . . 78
6.8 Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
6.9 None Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
6.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.11.1 General Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.11.2 Convert Kilometers to Miles . . . . . . . . . . . . . . . . . . . . . 81
7 Flow of Control Using if Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.2 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.3 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
7.4 The If Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
7.4.1 Working with an If Statement . . . . . . . . . . . . . . . . . . . . 85
7.4.2 Else in an If Statement . . . . . . . . . . . . . . . . . . . . . . . . . . 86
7.4.3 The Use of elif . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
xvi Contents

7.5 Nesting if Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87


7.6 If Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
7.7 A Note on True and False . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
7.8 Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
7.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
7.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
7.10.1 Check Input is Positive or Negative . . . . . . . . . . . . . . . 90
7.10.2 Test if a Number is Odd or Even . . . . . . . . . . . . . . . . . . 90
7.10.3 Kilometers to Miles Converter . . . . . . . . . . . . . . . . . . . . 90
8 Iteration/Looping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
8.2 While Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
8.3 For Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
8.3.1 Python for Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
8.3.2 Looping by Non-default Increments . . . . . . . . . . . . . . . 97
8.3.3 Anonymous Loop Variables . . . . . . . . . . . . . . . . . . . . . . 98
8.4 Negative Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
8.5 Break Loop Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
8.6 Continue Loop Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
8.7 For Loop with Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
8.8 A Note on Loop Variable Naming . . . . . . . . . . . . . . . . . . . . . . . . . 103
8.9 Dice Roll Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
8.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
8.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
8.11.1 Calculate the Factorial of a Number . . . . . . . . . . . . . . . 104
8.11.2 Print All the Prime Numbers in a Range . . . . . . . . . . . 105
9 Number Guessing Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
9.2 Setting up the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
9.2.1 Create a New Python File . . . . . . . . . . . . . . . . . . . . . . . . 107
9.2.2 Add a Welcome Message . . . . . . . . . . . . . . . . . . . . . . . . 108
9.2.3 Running the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
9.3 What Will the Program Do? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
9.4 Creating the Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
9.4.1 Generate the Random Number . . . . . . . . . . . . . . . . . . . . 111
9.4.2 Obtain an Input From the User . . . . . . . . . . . . . . . . . . . 111
9.4.3 Check to See if the Player Has Guessed
the Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
9.4.4 Check They Haven’t Exceeded Their Maximum
Number of Guess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
9.4.5 Notify the Player Whether Higher or Lower . . . . . . . . 113
9.4.6 End of Game Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
9.5 The Complete Listing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
9.6 Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Contents xvii

9.6.1 Initializing Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116


9.6.2 Blank Lines Within a Block of Code . . . . . . . . . . . . . . 116
9.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
10 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
10.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
10.2 Recursive Behaviour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
10.3 Benefits of Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
10.4 Recursively Searching a Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
10.5 Recursion in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
10.6 Calculating Factorial Recursively . . . . . . . . . . . . . . . . . . . . . . . . . . 120
10.7 Disadvantages of Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
10.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
10.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
11 Introduction to Structured Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
11.2 Structured Analysis and Function Identification . . . . . . . . . . . . . . 125
11.3 Functional Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
11.3.1 Functional Decomposition Terminology . . . . . . . . . . . 127
11.3.2 Functional Decomposition Process . . . . . . . . . . . . . . . . 128
11.3.3 Calculator Functional Decomposition Example . . . . . 128
11.4 Functional Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
11.5 Data Flow Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
11.6 Flowcharts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
11.7 Data Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
11.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
12 Functions in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
12.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
12.2 What are Functions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
12.3 How Functions Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
12.4 Types of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
12.5 Defining Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
12.5.1 An Example Function . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
12.6 Returning Values from Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 139
12.7 Docstring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
12.8 ReStructured Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
12.9 Function Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
12.9.1 Multiple Parameter Functions . . . . . . . . . . . . . . . . . . . . 146
12.9.2 Default Parameter Values . . . . . . . . . . . . . . . . . . . . . . . . 147
12.9.3 Named Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
12.9.4 Arbitrary Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
12.9.5 Positional and Keyword Arguments . . . . . . . . . . . . . . . 150
12.10 Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
xviii Contents

12.11 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152


12.12 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
13 Scope and Lifetime of Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
13.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
13.2 Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
13.3 The Global Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
13.4 Nonlocal Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
13.5 Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
13.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
13.7 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
14 Implementing a Calculator Using Functions . . . . . . . . . . . . . . . . . . . . . 161
14.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
14.2 What the Calculator Will Do . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
14.3 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
14.4 The Calculator Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
14.5 Behaviour of the Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
14.6 Identifying Whether the User has Finished . . . . . . . . . . . . . . . . . . 164
14.7 Selecting the Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
14.8 Obtaining the Input Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
14.9 Determining the Operation to Execute . . . . . . . . . . . . . . . . . . . . . . 169
14.10 Running the Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
14.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
15 Introduction to Functional Programming . . . . . . . . . . . . . . . . . . . . . . . . 171
15.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
15.2 What is Functional Programming? . . . . . . . . . . . . . . . . . . . . . . . . . 171
15.3 Advantages to Functional Programming . . . . . . . . . . . . . . . . . . . . 173
15.4 Disadvantages of Functional Programming . . . . . . . . . . . . . . . . . . 175
15.5 Referential Transparency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
15.6 Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
16 Higher-Order Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
16.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
16.2 Recap on Functions in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
16.3 Functions as Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
16.4 Higher-Order Function Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . 182
16.4.1 Higher-Order Function Example . . . . . . . . . . . . . . . . . . 183
16.5 Python Higher-Order Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
16.5.1 Using Higher-Order Functions . . . . . . . . . . . . . . . . . . . . 185
16.5.2 Functions Returning Functions . . . . . . . . . . . . . . . . . . . 186
16.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
16.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
Contents xix

17 Curried Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189


17.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
17.2 Currying Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
17.3 Python and Curried Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
17.4 Closures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
17.5 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
17.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
18 Introduction to Object Orientation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
18.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
18.2 Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
18.3 What Are Classes for? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
18.3.1 What Should a Class Do? . . . . . . . . . . . . . . . . . . . . . . . . 197
18.3.2 Class Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
18.4 How is an OO System Constructed? . . . . . . . . . . . . . . . . . . . . . . . 198
18.4.1 Where Do We Start? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
18.4.2 Identifying the Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 200
18.4.3 Identifying the Services or Methods . . . . . . . . . . . . . . . 201
18.4.4 Refining the Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
18.4.5 Bringing It All Together . . . . . . . . . . . . . . . . . . . . . . . . . 203
18.5 Where Is the Structure in an OO Program? . . . . . . . . . . . . . . . . . . 205
18.6 Further Readings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
19 Python Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
19.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
19.2 Python and Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
19.3 Class Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
19.4 Creating Examples of the Class Person . . . . . . . . . . . . . . . . . . . . . 212
19.5 Be Careful with Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
19.6 Printing Out Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
19.6.1 Accessing Object Attributes . . . . . . . . . . . . . . . . . . . . . . 214
19.6.2 Defining a Default String Representation . . . . . . . . . . . 215
19.6.3 Defining a Default Storage Representation . . . . . . . . . 216
19.7 Providing a Class Comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
19.8 Adding a Birthday Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
19.9 Defining Instance Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
19.10 Person Class Recap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
19.11 The Del Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
19.12 Automatic Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . 222
19.13 Intrinsic Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
19.14 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
19.15 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
xx Contents

20 Class Side and Static Behaviour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227


20.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
20.2 Class-Side Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
20.3 Class-Side Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
20.3.1 Why Class-Side Methods? . . . . . . . . . . . . . . . . . . . . . . . 229
20.4 Static Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
20.5 Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
20.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
20.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
21 Class Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
21.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
21.2 What is Inheritance? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
21.3 Defining Inheritance Between Classes . . . . . . . . . . . . . . . . . . . . . . 234
21.4 Terminology Around Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . 237
21.4.1 Types of Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
21.5 The Class Object and Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . 239
21.6 The Built-in Object Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
21.7 Purpose of Subclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
21.8 Overriding Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
21.9 Extending Superclass Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
21.10 Inheritance-Oriented Naming Conventions . . . . . . . . . . . . . . . . . . 243
21.11 Python and Multiple Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
21.12 Multiple Inheritance Considered Harmful . . . . . . . . . . . . . . . . . . . 246
21.13 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
21.14 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
21.15 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
22 Why Bother with Object Orientation? . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
22.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
22.2 The Procedural Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
22.2.1 Procedures for the Data Structure . . . . . . . . . . . . . . . . . 254
22.2.2 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
22.3 Does Object Orientation Do Any Better? . . . . . . . . . . . . . . . . . . . 255
22.3.1 Packages Versus Classes . . . . . . . . . . . . . . . . . . . . . . . . . 255
22.3.2 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
22.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
23 Operator Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
23.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
23.2 Operator Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
23.2.1 Why Have Operator Overloading? . . . . . . . . . . . . . . . . 259
23.2.2 Why not Have Operator Overloading? . . . . . . . . . . . . . 260
23.2.3 Implementing Operator Overloading . . . . . . . . . . . . . . 260
23.3 Numerical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
23.4 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
Contents xxi

23.5 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266


23.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
23.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
23.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
24 Python Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
24.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
24.2 Python Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
24.3 Setter and Getter Style Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
24.4 Public Interface to Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
24.5 More Concise Property Definitions . . . . . . . . . . . . . . . . . . . . . . . . 273
24.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
24.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
25 Abstract Base Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
25.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
25.2 Abstract Classes as a Concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
25.3 Abstract Base Classes in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
25.3.1 Subclassing an ABC . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
25.3.2 Defining an Abstract Base Class . . . . . . . . . . . . . . . . . . 280
25.4 Defining an Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
25.5 Virtual Subclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
25.6 Mixins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
25.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
26 Error and Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
26.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
26.2 Errors and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
26.3 What is an Exception? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
26.4 What is Exception Handling? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
26.5 Handling an Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
26.5.1 Accessing the Exception Object . . . . . . . . . . . . . . . . . . 293
26.5.2 Jumping to Exception Handlers . . . . . . . . . . . . . . . . . . . 294
26.5.3 Catch Any Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
26.5.4 The Else Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
26.5.5 The Finally Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
26.6 Raising an Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
26.7 Defining an Custom Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
26.8 Chaining Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
26.9 Exception Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
26.10 Exception Group Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
26.11 Exception Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
26.12 Generate a Traceback Programmatically . . . . . . . . . . . . . . . . . . . . 306
26.13 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
26.14 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
Visit https://ebookmass.com today to explore
a vast collection of ebooks across various
genres, available in popular formats like
PDF, EPUB, and MOBI, fully compatible with
all devices. Enjoy a seamless reading
experience and effortlessly download high-
quality materials in just a few simple steps.
Plus, don’t miss out on exciting offers that
let you access a wealth of knowledge at the
best prices!
Exploring the Variety of Random
Documents with Different Content
Si hay menor en los daños que recibo.
Quedaos aquí los dos, miéntras yo escribo.
(Vase.)

ESCENA VI.
COQUIN, JACINTA.

Jacinta
¿Qué
. tienes estos dias,
Coquin, que andas tan triste? ¿No solias
Ser alegre? ¿Qué efeto
Te tiene así?
Coquin. Metíme á ser discreto
Por mi mal, y hame dado
Tan grande hipocondría en este lado,
Que me muero.
Jacinta. ¿Y qué es hipocondría?
Coquin
Es .una enfermedad que no la habia
Habrá dos años, ni en el mundo era.
Úsase poco há, y de manera
Lo que se usa, amiga, no se excusa,
Que una dama, sabiendo que se usa,
Le dijo á su galan muy triste un dia:
«Tráigame un poco uced de hipocondría.»
Mas señor entra ahora.
Jacinta
¡Ay. Dios! Voy á avisar á mi señora.

ESCENA VIII.
DON GUTIERRE.—COQUIN, JACINTA.

D. GTente,
ut. Jacinta, espera.
¿Dónde corriendo vas de esa manera?
Jacinta
Avisar
. pretendia
A mi señora de que ya venía
Tu persona.
D. G(Ap.
ut. ¡Oh criados,
En efecto, enemigos no excusados!
Turbados de temor los dos se han puesto.)
Ven acá, díme tú lo que hay en esto:
Díme por qué corrias. (A Jacinta.)
Jacinta
Solo
. por avisar de que venías,
Señor, á mi señora.
D. Gut. El labio sella.
(Ap. Mas deste lo sabré mejor que della.)
Coquin, tú me has servido
Noble siempre, en mi casa te has criado:
A tí vuelvo rendido,
Díme, dime por Dios lo que ha pasado.
Coquin
Señor,
. si algo supiera,
De lástima no más te lo dijera.
¡Plegue á Dios! mi señor...
D. Gut. ¡No, no des voces!
¿De qué aquí te turbaste?
Coquin
Somos
. de buen turbar; mas esto baste.
D. G(Ap.
ut. Señas los dos se han hecho.
Ya no son cobardías de provecho.)
Idos de aquí los dos.—Solos estamos,
(Vanse los dos.)
Honor, lleguemos ya, desdicha, vamos.
¿Quién vió en tantos enojos
Matar las manos y llorar los ojos?
(Alza una cortina, y descubre á Doña Mencía escribiendo.)

ESCENA IX.
Í
DOÑA MENCÍA.—DON GUTIERRE.

D. G(Ap.)
ut. Escribiendo Mencía
Está: ya es fuerza ver lo que escribia.
(Llega á ella y quítale el papel.)
D.ª ¡Ay
MenDios!
. ¡Válgame el cielo! (Se desmaya.)
D. GEstatua
ut. viva se quedó de hielo. (Lee.)
Vuestra Alteza, señor... ¡Que por Alteza
Vino mi honor á dar á tal bajeza!
No se ausente... Detente,
Voz; pues le ruega aquí que no se ausente,
A tanto mal me ofrezco,
Que casi las desdichas me agradezco.—
¿Si aquí la doy la muerte...?
Mas esto ha de pensarse desta suerte.
Despediré criadas y criados:
Solos han de quedarse mis cuidados
Conmigo; y ya que ha sido
Mencía la mujer que yo he querido
Mas en mi vida, quiero
Que en el último vale, en el postrero
Parasismo, me deba
La más nueva piedad, la accion más nueva.
Ya que la cura he de aplicar postrera,
No muera el alma, aunque la vida muera.
(Escribe y vase.—Vuelve en sí Doña Mencía.)

ESCENA X.
DOÑA MENCÍA.

¡Señor, deten la espada,


No me juzgues culpada:
El cielo sabe que inocente muero!
¿Qué fiera mano, qué sangriento acero
En mi pecho ejecutas? ¡Tente, tente!
¡Una mujer no mates inocente!
Mas ¿qué es esto? ¡ay de mí! ¿no estaba agora
Gutierre aquí? ¿No via (¿quién lo ignora?)
Que en mi sangre bañada,
Moria en rubias ondas anegada?
¡Ay Dios, este desmayo
Fué de mi vida aquí mortal ensayo!
¡Qué ilusion! Por verdad lo dudo y creo.
El papel romperé.—¡Pero qué veo!
De mi esposo es la letra, y desta suerte
La sentencia me intima de mi muerte:

El amor te adora, el honor te aborrece; y así


(Lee.)
el uno te mata y el otro te avisa. Dos horas tienes
de vida: cristiana eres, salva el alma, que la vida
es imposible.

¡Válgame Dios! ¡Jacinta, hola! ¿Qué es esto?


¿Nadie responde? ¡Otro temor funesto!
¿No hay alguna criada?
Mas ¡ay de mí! la puerta está cerrada,
Nadie en casa me escucha.
Mucha es mi turbacion, mi pena es mucha.
Destas ventanas son los hierros rejas,
Y en vano á nadie le diré mis quejas,
Que caen á unos jardines, donde apénas
Habrá quien oiga repetidas penas.
¿Dónde iré desta suerte,
Tropezando en la sombra de mi muerte?
(Vase.)
Calle.

ESCENA XI.
EL REY, DON DIEGO.

Rey.En fin, ¿Enrique se fué?


D. DSí, señor:
iego . aquesta tarde
Salió de Sevilla.
Rey. Creo
Que ha presumido arrogante
Que él solamente de mí
Podrá en el mundo librarse.
¿Y dónde va?
D. Diego. Yo presumo
Que á Consuegra.
Rey. Está el Infante
Maestre allí, y querrán los dos
A mis espaldas vengarse
De mí.
D. DiegoTus
. hermanos son,
Y es forzoso que te amen
Como hermano, y como á rey
Te adoren: dos naturales
Obediencias son.
Rey. Y Enrique
¿Quién lleva que le acompañe?
D. DDon
iego.Arias.
Rey. Es su privanza.
D. DMúsica
iego. hay en esta calle.
Rey.Vámonos llegando á ellos:
Quizá con lo que cantaren,
Me templaré.
D. Diego. La armonía
Es antídoto á los males.
(Cantan dentro.)
El infante Don Enrique
Hoy se despidió del Rey;
Su pesadumbre y su ausencia
Quiera Dios que pare en bien.
Rey.¡Qué triste voz! Vos, Don Diego,
Echad por aquesa calle,
No se nos escape quien
Canta desatinos tales.
(Vase cada uno por su parte.)
Sala en casa de Don Gutierre.

ESCENA XII.
DON GUTIERRE; LUDOVICO, cubierto el rostro.

D. GEntra,
ut. no tengas temor;
Que ya es tiempo que destape
Tu rostro y encubra el mio. (Tápase.)
Ludov
¡Válgame
. Dios!
D. Gut. No te espante
Nada que vieres.
Ludov. Señor,
De mi casa me sacasteis
Esta noche; pero apénas
Me tuvisteis en la calle,
Cuando un puñal me pusisteis
Al pecho, sin que cobarde
Vuestro intento resistiese,
Que fué cubrirme y vendarme
El rostro, y darme mil vueltas
Luego á mis propios umbrales.
Dijísteisme que mi vida
Estaba en no destaparme;
Una hora he andado con vos,
Sin saber por donde ande.
Y con ser la admiracion
De aqueste caso tan grave,
Más me turba y me suspende
Inpensadamente hallarme
En una casa tan rica,
Sin ver que la habite nadie
Sino vos, habiéndôs visto
Siempre ese embozo delante.
¿Qué me quereis?
D. Gut. Que te esperes
Aquí solo un breve instante. (Vase.)
Ludov
¡Qué
. confusiones son estas
Que á tal extremo me traen!
¡Válgame Dios! (Vuelve Don Gutierre.)
D. Gut. Tiempo es ya
De que entres aquí; mas ántes
Escúchame: aqueste acero
Será de tu pecho esmalte,
Si resistes lo que yo
Tengo ahora de mandarte.
Asómate á ese aposento.
¿Qué ves en él?
Ludov. Una imágen
De la muerte, un bulto veo
Que sobre una cama yace:
Dos velas tiene á los lados,
Y un crucifijo delante.
Quién es, no puedo decir;
Que con unos tafetanes
El rostro tiene cubierto.
D. GPues
ut. á ese vivo cadáver
Que ves, has de dar la muerte.
Ludov
¿Pues
. qué quieres?
D. Gut. Que la sangres,
Y la dejes que rendida
A su violencia, desmaye
La fuerza, y que en tanto horror
Tú atrevido la acompañes,
Hasta que por breve herida
Ella espire y se desangre.
No tienes que replicar,
Si buscas en mí piedades;
Sino obedecer, si quieres
Vivir.
Ludov.Señor, tan cobarde
Te escucho, que no podré
Obedecerte.
D. Gut. Quien hace
Por consejos rigurosos
Mayores temeridades,
Darte la muerte sabrá.
Ludov
Fuerza
. es que mi vida guarde.
D. GHaces
ut. bien; que ya en el mundo
Hay quien viva porque mate.
Desde aquí te estoy mirando,
Ludovico: entra adelante.
(Entrase Ludovico.)

ESCENA XIII.
DON GUTIERRE.

Este fué el más sutil medio


Para que mi afrenta acabe
Disimulada, supuesto
Que el veneno fuera fácil
De averiguar, las heridas
Imposible de ocultarse.
Y así, contando la muerte,
Y diciendo que fué lance
Forzoso hacer la sangría,
Ninguno podrá probarme
Lo contrario, si es posible
Que una venda se desate.
Haber traido á este hombre
Con recato semejante,
Fué bien; pues si descubierto
Viniera, y viera sangrarse
Una mujer, y por fuerza,
Fuera presuncion notable.
Éste no podrá decir,
Cuando refiera este trance,
Quién fué la mujer; demas,
Que cuando de aquí le saque,
Muy léjos ya de mi casa
Estoy dispuesto á matarle.
Médico soy de mi honor:
La vida pretendo darle
Con una sangría; que todos
Curan á costa de sangre. (Vase.)
Calle.

ESCENA XIV.
EL REY y DON DIEGO, que vuelven á salir cada
uno por su parte; MÚSICA, dentro.

(Cantan dentro.)
Para Consuegra camina,
Donde piensa que han de ser
Teatros de mil tragedias
Las montañas de Montiel.
Rey.¡Don Diego!
D. Diego. Señor...
Rey. Supuesto
Que cantan en esta calle,
¿No hemos de saber quién es?
¿Habla por ventura el aire?
D. DNo te. desveles, señor,
iego
Oir estas necedades;
Porque á vuestro enojo ya
Versos en Sevilla se hacen.
Rey.Dos hombres vienen aquí.
D. DEs verdad:
iego . no hay que esperarles
Respuesta. Hoy el conocerlos
Importa.

ESCENA XV.
DON GUTIERRE, que trae á LUDOVICO, con los
ojos vendados.—Dichos.
D. G(Ap.)
ut. ¡Que así me ataje
El cielo que con la muerte
Deste hombre eche otra llave
Al secreto!—Ya me es fuerza
De aquestos dos retirarme;
Que nada me está peor
Que conocerme en tal parte.
Dejaréle en este puesto. (Vase.)

ESCENA XVI.
EL REY, DON DIEGO, LUDOVICO, con los ojos
vendados.

D. DDe los
iego . dos, señor, que ántes
Venian, se volvió el uno,
Y el otro se quedó.
Rey. A darme
Confusion; que si le veo
A la poca luz que esparce
La luna, no tiene forma
Su rostro: confusa imágen
El bulto, mal acabado,
Parece de un blanco jaspe.
D. DTéngase
iego. tu Majestad,
Que yo llegaré.
Rey. Dejadme,
Don Diego.—¿Quién eres, hombre?
Ludov
Dos
. confusiones son parte,
Señor, á no responderos: (Descúbrese.)
La una, la humildad que trae
Consigo un pobre oficial,
Para que con reyes hable
(Que ya os conocí en la voz,
Luz que tan notorio os hace);
La otra, la novedad
Del suceso más notable
Que el vulgo, archivo confuso,
Califica en sus anales.
Rey.¿Qué os ha sucedido?
Ludov. A vos
Lo diré, escuchadme aparte.
Rey.Retiraos allí, Don Diego.
D. D(Ap.)
iegoSucesos
. son admirables
Cuantos esta noche veo:
Dios con bien della me saque.
LudovNo. la ví el rostro, mas solo
Entre repentidos ayes
Escuché: «Inocente muero;
El cielo no te demande
Mi muerte.» Esto dijo, y luego
Espiró; y en este instante
El hombre mató la luz,
Y por los pasos, que ántes
Entré, salí. Sintió ruido
Al llegar á aquesta calle,
Y dejóme en ella solo.
Fáltame ahora de avisarte,
Señor, que saqué bañadas
Las manos en roja sangre,
Y que fuí por las paredes,
Como que quise arrimarme,
Manchando todas las puertas,
Por si pueden las señales
Descubrir la casa.
Rey. ¡Bien
Hicistes! Venid á hablarme
Con lo que hubiereis sabido,
Y tomad este diamante,
Y decid que por las señas
Dél os permitan hablarme
A cualquier hora que vais.
Ludov
El .cielo, señor, os guarde. (Vase.)
Rey.Vamos, Don Diego.
D. Diego. ¿Qué es eso?
Rey.El suceso más notable
Del mundo.
D. Diego. Triste has quedado.
Rey.Forzoso ha sido asombrarme.
D. DVente
iego. á acostar, que ya el dia
Entre dorados celajes
Asoma.
Rey. No he de poder
Sosegar, hasta que halle
Una cosa que deseo.
D. D¿No
iegomiras
. que ya el sol sale,
Y que podrán conocerte
Desta suerte?

ESCENA XVII.
COQUIN.—EL REY, DON DIEGO.

Coquin. Aunque me mates,


Habiéndote conocido,
¡Oh señor! tengo de hablarte:
Escúchame.
Rey. Pues, Coquin,
¿De qué los extremos son?
Coquin
Esta. es una honrada accion,
De hombre bien nacido en fin;
Que aunque hombre me consideras
De burlas con loco humor,
Llegando á véras, señor,
Soy hombre de muchas véras,
Oye lo que he de decir,
Pues de véras vengo á hablar;
Que quiero hacerte llorar,
Ya que no puedo reir.
Gutierre, mal informado
Por aparentes recelos,
Llegó á tener viles celos
De su honor; y hoy obligado
A tal sospecha, que halló
Escribiendo (¡error cruel!)
Para el Infante un papel
A su esposa, que intentó
Con él que no se ausentase,
Porque ella causa no fuese
De que en Sevilla se viese
La novedad que causase
Pensar que ella le ausentaba...
Con esta inocencia pues
(Que á mí me consta), con piés
Cobardes, adonde estaba
Llegó, y el papel tomó,
Y, sus celos declarados,
Despidiendo á los criados,
Todas las puertas cerró,
Solo se quedó con ella.
Yo enternecido de ver
Una infelice mujer
Perseguida de su estrella,
Vengo, señor, á avisarte
Que tu brazo altivo y fuerte
Hoy la libre de la muerte.
Rey.¿Con qué he de poder pagarte
Tal piedad?
Coquin. Con darme aprisa
Libre, sin más accidentes,
De la accion contra mis dientes.
Rey.No es ahora tiempo de risa.
Coquin
¿Cuándo
. lo fué?
Rey. Y pues el dia
Aun no se muestra, lleguemos,
Don Diego. (Vanse.)
Otra calle, y en ella la casa de Don Gutierre. En la puerta se
ve la señal de una mano sangrienta.

ESCENA XVIII.
Los mismos.

Rey. Así, pues, daremos


Color á una industria mia,
De entrar en casa mejor,
Diciendo que me ha cogido
Cerca el dia, y he querido
Disimular el color
Del vestido; y una vez
Allá, el estado veremos
Del suceso; y así haremos
Como Rey, supremo juez.
D. DNo
iegohubiera
. industria mejor.
Coquin
De .su casa lo has tratado
Tan cerca, que ya has llegado;
Que esta es su casa, señor.
Rey.Don Diego, espera.
D. Diego. ¿Qué ves?
Rey.¿No ves sangrienta una mano
Impresa en la puerta?
D. Diego. Es llano.
Rey.(Ap.) Gutierre sin duda es
El cruel que anoche hizo
Una accion tan inclemente.
No sé qué hacer. Cuerdamente
Sus agravios satisfizo.

ESCENA XIX.
É
DOÑA LEONOR, INÉS, con mantos.—Dichos.

D.ª Salgo
Leon. á misa ántes del dia,
Porque ninguno me vea
En Sevilla, donde crea
Que olvido la pena mia.
Mas gente hay aquí. ¡Ay Inés!
¿El Rey qué hará en esta casa?
InésTápate
. en tanto que pasa.
Rey.Accion excusada es,
Porque ya estais conocida.
D.ª No
Leon
fué
. encubrirme, señor,
Por excusar el honor
De dar á tus piés la vida.
Rey.Esa accion es para mí,
De recatarme de vos,
Pues sois acrêdor, por Dios,
De mis honras; que yo os di
Palabra, y con gran razon,
De que he de satisfacer
Vuestro honor; y lo he de hacer
En la primera ocasion.

ESCENA XX.
DON GUTIERRE.—Dichos.

D. G(Dentro)
ut. ¡Hoy me he de desesperar,
Cielo airado, si no baja
Un rayo de esas esferas
Y en cenizas me desata!
Rey.¿Qué es esto?
D. Diego. Loco furioso
Don Gutierre de su casa
Sale.
Rey. ¿Dónde vais, Gutierre?
D. G(Sale.)
ut. A besar, señor, tus plantas;
Y de la mayor desdicha,
De la tragedia más rara,
Escucha la admiracion,
Que eleva, admira y espanta.
Mencía, mi amada esposa,
Tan hermosa como casta,
Virtuosa como bella
(Dígalo á voces la fama):
Mencía, á quien adoré
Con la vida y con el alma,
Anoche á un grave accidente
Vió su perfeccion postrada,
Por desmentirla divina
Este accidente de humana.
Un médico, que lo es
El de mayor nombre y fama,
Y el que en el mundo merece
Inmortales alabanzas,
La recetó una sangría,
Porque con ella esperaba
Restituir la salud
A un mal de tanta importancia.
Sangróse en fin; que yo mismo,
Por estar sola la casa,
Llamé al sangrador, no habiendo
Ni criados ni criadas.
A verla en su cuarto, pues,
Quise entrar esta mañana...
—Aquí la lengua enmudece,
Aquí el aliento me falta.
Veo de funesta sangre
Teñida toda la cama,
Toda la ropa cubierta,
Y que en ella ¡ay Dios! estaba
Mencía, que se habia muerto
Esta noche desangrada.
Ya se ve cuán fácilmente
Una venda se desata.
¿Pero para qué presumo
Reducir hoy á palabras
Tan lastimosas desdichas?
Vuelve á esta parte la cara,
Y verás sangriento el sol,
Verás la luna eclipsada,
Deslucidas las estrellas
Y las esferas borradas;
Y verás á la hermosura
Mas triste y más desdichada,
Que, por darme mayor muerte,
No me ha dejado sin alma.
(Descúbrese á Doña Mencía en la cama.)[1]
Rey.¡Notable suceso! (Ap. Aquí
La prudencia es de importancia.
Mucho en reportarme haré.
Tomó notable venganza.)
Cubrid ese horror que asombra,
Ese prodigio que espanta,
Espectáculo que admira,
Símbolo de la desgracia.
Gutierre, menester es
Consuelo; y porque le haya
En pérdida que es tan grande
Con otra tanta ganancia,
Dadle la mano á Leonor;
Que es tiempo que satisfaga
Vuestro valor lo que debe,
Y yo cumpla la palabra
De volver en la ocasion
Por su valor y su fama.
D. GSeñor,
ut. si de tanto fuego
Aún las cenizas se hallan
Calientes, dadme lugar
Para que llore mis ánsias.
¿No quereis que escarmentado
Quede?
Rey. Esto ha de ser, y basta.
D. GSeñor,
ut. ¿quereis que otra vez,
No libre de la borrasca,
Vuelva al mar? ¿Con qué disculpa?
Rey.Con que vuestro Rey lo manda.
D. GSeñor,
ut. escuchad aparte
Disculpas.
Rey. Son excusadas.
¿Cuáles son?
D. Gut. ¿Si vuelvo á verme
En desdichas tan extrañas,
Que de noche halle embozado
A vuestro hermano en mi casa...?
Rey.No dar crédito á sospechas.
D. G¿Y
ut.si detras de mi cama
Hallase tal vez, señor,
De Don Enrique la daga?
Rey.Presumir que hay en el mundo
Mil sobornadas criadas,
Y apelar á la cordura.
D. GAutveces,
. señor, no basta.
¿Si veo rondar despues
De noche y de dia mi casa?
Rey.Quejárseme á mí.
D. Gut. ¿Y si cuando
Llego á quejarme, me aguarda
Mayor desdicha escuchando?
Rey.¿Qué importa, si él desengaña
Que fué siempre su hermosura
Una constante muralla
De los vientos defendida?
D. G¿Y
ut.si volviendo á mi casa,
Hallo algun papel que pide
Que el Infante no se vaya?
Rey.Para todo habrá remedio.
D. G¿Posible
ut. es que á esto le haya?
Rey.Sí, Gutierre.
D. Gut. ¿Cuál, señor?
Rey.Uno vuestro.
D. Gut. ¿Qué es?
Rey. Sangrarla.
D. G¿Qué
ut. decís?
Rey. Que hagais borrar
Las puertas de vuestra casa;
Que hay mano sangrienta en ellas.
D. GLos
ut. que de un oficio tratan,
Ponen, señor, á las puertas
Un escudo de sus armas;
Trato en honor, y así pongo
Mi mano en sangre bañada
A la puerta; que el honor
Con sangre, señor, se lava.
Rey.Dádsela, pues, á Leonor;
Que yo sé que su alabanza
La merece.
D. Gut. Sí la doy. (Dale la mano.)
Mas mira que va bañada
En sangre, Leonor.
D.ª Leon. No importa;
Que no me admira ni espanta.
D. GMira
ut. que médico he sido
De mi honra: no está olvidada
La ciencia.
D.ª Leon. Cura con ella
Mi vida, en estando mala.
D. GPues
ut. con esa condicion
Te la doy. Con esto acaba
El Médico de su honra,
Perdonad sus muchas faltas.
A SECRETO AGRAVIO SECRETA
VENGANZA.
DRAMA EN TRES JORNADAS.
PERSONAS.

El rey don Sebastian.


Don Lope de Almeida.
Don Juan de Silva.
Don Luis de Benavides.
Don Bernardino, viejo.
El duque de Berganza.
Doña Leonor, dama.
Sirena, criada.
Manrique, criado.
Cecilio, criado.
Un barquero.
Acompañamiento.
Soldados.

La escena es en Lisboa, en las cercanías de Aldea


Gallega y en otros puntos.
JORNADA PRIMERA.

Vista exterior de una quinta del Rey.

ESCENA PRIMERA.
EL REY DON SEBASTIAN, DON LOPE DE ALMEIDA,
MANRIQUE, acompañamiento.

D. LOtra
ope. vez, gran señor, os he pedido
Esta licencia, y otra habeis tenido
Por bien mi casamiento;
Mas yo que siempre, á tanta luz atento,
Vivo en vuestro semblante, vengo á daros
Cuenta de mi eleccion, y á suplicaros
Que en vuestra gracia pueda
Colgar las armas, y que Marte ceda
A Amor la gloria, cuando en paz reciba,
En vez de alto laurel, sagrada oliva.
Yo os he servido, y solamente espero
Esta merced por galardon postrero,
Pues con esta licencia venturosa
Hoy saldré á recibir mi amada esposa.
Rey.Yo estimo vuestro gusto y vuestro aumento,
Y me alegro de vuestro casamiento;
Y á no estar ocupado
En la guerra que en Africa he intentado,
Fuera vuestro padrino.
D. LEterno
ope. dure ese laurel divino
Que tus sienes corona.
Rey.Estimo en mucho yo vuestra persona.
(Vase el Rey y acompañamiento.)

ESCENA II.
DON LOPE, MANRIQUE.

Manriq
Contento
. estás.
D. Lope. Mal supiera
La dicha y la gloria mia
Disimular su alegría.
¡Felice yo, si pudiera
Volar hoy!
Manriq. Al viento igualas.
D. LPoco
ope. aprovecha; que el viento
Es perezoso elemento.
Diérame el amor sus alas,
Volara abrasado y ciego;
Pues quien al viento se entrega,
Olas de viento navega,
Y las de amor son de fuego.
Manriq
Para. que desengañarme
Pueda, creyendo que tienes
Causa, dime á lo que vienes
Con tanta prisa.
D. Lope. A casarme.
Manriq
¿Y .no miras que es error,
Digno de que al mundo asombre,
Que vaya á casarse un hombre
Con tanta prisa, señor?
Si hoy, que te vas á casar,
Del mismo viento te quejas,
¿Qué dejas que hacer, qué dejas,
Cuando vayas á enviudar?
ESCENA III.
DON JUAN DE SILVA, en traje pobre.—DON LOPE,
MANRIQUE.

D. J(Para
uan. sí.) ¡Cuán diferente pensé
Volver á tí, patria mia,
Aquel infelice dia
Que tus umbrales dejé!
¡Quién no te hubiera pisado!
Pues siempre mejor ha sido,
Adonde no es conocido,
Vivir el que es desdichado.
Gente hay aquí; no es razon
Verme en el mal que me veo.
D. LAguárdate.
ope. No lo creo.
¿Si es verdad? ¿Si es ilusion?
¡Don Juan!
D. Juan. ¡Don Lope!
D. Lope. Dudoso
De tanta dicha, mis brazos
Han suspendido sus lazos.
D. JDeteneos,
uan. que es forzoso
Que me defienda de quien
Tanto honor y valor tiene;
Que hombre que tan pobre viene,
Don Lope amigo, no es bien
Que toque (¡oh suerte importuna!)
Pecho de riquezas lleno.
D. LVuestra
ope. razones condeno,
Porque si da la fortuna
Humanos bienes del suelo,
El cielo un amigo da
Como vos: ¡ved lo que va
Desde la fortuna al cielo!
D. JAunque
uan. haceis que aliento cobre,
En mí mayor mal está:
¡Mirad cuán grande será
Mal que es mayor que ser pobre!
Y porque mi sentimiento
Algun alivio prevenga,
Si es posible que le tenga,
Escuchad, Don Lope, atento.
A la conquista famosa
De la India, que eligió
Para su tumba la noche
Y para su cuna el sol,
Amigos, y tan amigos,
Pasamos juntos los dos,
Que asistieron en dos cuerpos
Un alma y un corazon.
No codicia de riqueza,
Sino codicia de honor
Obligó nuestros deseos
A tan atrevida accion,
Como tocar con bajeles
La provincia que ignoró
Por tantos años la ciencia,
Nunca creida hasta hoy.
La nobleza lusitana
De su fortuna fió
Naves, que ciertas exceden
Las fingidas de Jason.
Dejo esta alabanza á quien
Pueda con más dulce voz
Contar los famosos hechos
Desta invencible nacion;
Porque el gran Luis de Camoens,
Escribiendo lo que obró,
Con pluma y espada muestra
Ya el ingenio y ya el valor
En esta parte. Despues,
Don Lope invicto, que vos,
Por muerte de vuestro padre,
Volvisteis, me quedé yo,
Bien sabeis con cuánta fama
De amigos y de opinion,
Que ahora perdidos hacen
El sentimiento mayor.
Pero en efecto es consuelo:
¡Ved si desgraciado soy,
Que nunca le di, malquisto,
A la fortuna ocasion!
Habia en Goa una señora,
Hija de un hombre á quien dió
Grande cantidad de hacienda
Codicia y contratacion.
Era hermosa, era discreta;
Que, aunque enemigas las dos,
En ella hicieron las paces
Hermosura y discrecion.
Servíla tan venturoso,
Que merecí algun favor;
Pero ¿quién ganó al principio,
Que á la postre no perdió?
¿Quién fué ántes tan felice,
Que despues no declinó?
Porque son muy parecidos
Juego, fortuna y amor.
Don Manuel de Sosa, un hombre
(Hijo del gobernador
Manuel de Sosa) por sí
De mucha resolucion,
Muy valiente, muy cortés,
Bizarro y cuerdo (que yo,
Aunque le quité la vida,
No he de quitarle el honor),
De Violante enamorado
(Que este es el nombre que dió
Ocasion á mi ventura
Y á mi desdicha ocasion),
En Goa públicamente
Era mi competidor.
Poco cuidado me daba
Su amorosa pretension;
Porque siendo, como era,
El favorecido yo,
La pena del despreciado
Hizo mi dicha mayor.
Un dia, que el sol hermoso
Saliera (¡pluguiera á Dios,
Sepultara eterna noche
Su contínuo resplandor!),
Salió con el sol Violante:
Bastaba pedirle yo
Que áun el uno no saliera,
Para que salieran dos.
De criados rodeada
A la marina llegó,
Donde estaba mucha gente,
Porque en aquella ocasion
Habia llegado una nave
Al puerto, y su admiracion
Dió causa á aqueste concurso,
Y á mi desdicha la dió.
Estábamos en un corro
De mucha gente los dos,
Todos soldados y amigos,
Cuando á la vista paso
Violante. Iba tan airosa,
Que allí ninguno dejó
De poner el alma en ella,
Porque su planta veloz
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookmasss.com

You might also like