100% found this document useful (2 votes)
68 views72 pages

Ultimate Python Programming 1st Edition Deepali Srivastava PDF Download

The document provides information about the book 'Ultimate Python Programming' by Deepali Srivastava, which includes over 650 programs, 900 practice questions, and 5 projects aimed at teaching Python. It outlines the book's structure, covering fundamental to advanced Python concepts, and emphasizes hands-on learning through exercises and coding examples. Additionally, it mentions the author's background and the resources available for readers, including a code bundle and errata support.

Uploaded by

ermyaslafton
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
68 views72 pages

Ultimate Python Programming 1st Edition Deepali Srivastava PDF Download

The document provides information about the book 'Ultimate Python Programming' by Deepali Srivastava, which includes over 650 programs, 900 practice questions, and 5 projects aimed at teaching Python. It outlines the book's structure, covering fundamental to advanced Python concepts, and emphasizes hands-on learning through exercises and coding examples. Additionally, it mentions the author's background and the resources available for readers, including a code bundle and errata support.

Uploaded by

ermyaslafton
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

Ultimate Python Programming 1st Edition Deepali

Srivastava pdf download

https://ebookgate.com/product/ultimate-python-programming-1st-
edition-deepali-srivastava/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Expert Python Programming 2nd Edition Jaworski

https://ebookgate.com/product/expert-python-programming-2nd-edition-
jaworski/

ebookgate.com

Python Programming 4th Edition Singh A.

https://ebookgate.com/product/python-programming-4th-edition-singh-a/

ebookgate.com

Black hat Python Python programming for hackers and


pentesters 1st Edition Seitz

https://ebookgate.com/product/black-hat-python-python-programming-for-
hackers-and-pentesters-1st-edition-seitz/

ebookgate.com

Practical Maya Programming with Python 1st Edition


Galanakis

https://ebookgate.com/product/practical-maya-programming-with-
python-1st-edition-galanakis/

ebookgate.com
Core Python Programming 2nd Edition Wesley Chun

https://ebookgate.com/product/core-python-programming-2nd-edition-
wesley-chun/

ebookgate.com

Programming Python 3rd ed Edition Mark Lutz

https://ebookgate.com/product/programming-python-3rd-ed-edition-mark-
lutz/

ebookgate.com

Learning BeagleBone Python Programming Unleash the


potential of BeagleBone using Python 1st Edition Hiam

https://ebookgate.com/product/learning-beaglebone-python-programming-
unleash-the-potential-of-beaglebone-using-python-1st-edition-hiam/

ebookgate.com

Advanced Computer Programming in Python 1st Edition Karim


Pichara

https://ebookgate.com/product/advanced-computer-programming-in-
python-1st-edition-karim-pichara/

ebookgate.com

Python Programming for Teens 1st Edition Kenneth A.


Lambert

https://ebookgate.com/product/python-programming-for-teens-1st-
edition-kenneth-a-lambert/

ebookgate.com
Cover
Ultimate
Python
ProgrammingLearn Python with 650+
programs, 900+ practice
questions, and 5 projects
Deepali Srivastava

logo

www.bpbonline.com
First Edition 2024

Copyright © BPB Publications, India

ISBN: 978-93-55516-558

All Rights Reserved. No part of this publication may be reproduced,


distributed or transmitted in any form or by any means or stored in a
database or retrieval system, without the prior written permission of the
publisher with the exception to the program listings which may be entered,
stored and executed in a computer system, but they can not be reproduced
by the means of publication, photocopy, recording, or by any electronic and
mechanical means.

LIMITS OF LIABILITY AND DISCLAIMER OF WARRANTY

The information contained in this book is true to correct and the best of
author’s and publisher’s knowledge. The author has made every effort to
ensure the accuracy of these publications, but publisher cannot be held
responsible for any loss or damage arising from any information in this
book.

All trademarks referred to in the book are acknowledged as properties of


their respective owners but BPB Publications cannot guarantee the
accuracy of this information.

www.bpbonline.com
Dedicated to

Sri Anjaneya Swamy


About the Author
Deepali Srivastava has a Masterʼs degree in Mathematics and is an author
and educator in the field of computer science and programming. Her books
“C in Depthˮ and “Data Structures Through C in Depthˮ are widely used as
reference materials by students, programmers and professionals looking to
enhance their understanding of programming languages and data structures.
These books are known for their clarity, depth of coverage, and practical
approach to learning. In addition to her writing, Deepali Srivastava has
been involved in creating online video courses on Data structures and
Algorithms, Linux and Python programming. Her books and courses have
helped 350,000+ students learn computer science concepts. Her work has
been appreciated by students and has been a valuable resource for those
looking to build their programming skills.
Acknowledgement
I would like to thank God for blessing me with the opportunity and
inspiration to write this book, and for giving me the strength to do it.

I am grateful to my husband Suresh Kumar Srivastava for always believing


in my capabilities and consistently inspiring me to give my best. He
introduced me to book writing and helped me unleash my potential. His
thoughtful suggestions and feedback helped me improve the content and
presentation of this book.

I would like to thank my parents, my brother and my sister-in-law for their


unwavering love and support. Blessings of my parents and late parents-in-
law are a major source of my inner strength.

I am indebted to my teachers in my journey of education, especially my


teachers and friends in MJP Rohilkhand University Bareilly, where I got
introduced to the world of programming.

I extend my appreciation to the readers of my books and students of my


online courses for their interest in my work, and for their appreciation and
suggestions. Any sort of feedback is valuable to me and helps me in
improving my work and creating better content.

I am grateful to the BPB publication team for their guidance and support
provided during every step of the publishing journey. Special appreciation
goes to the editing team, layout team, and all other contributors involved in
bringing this book to life.
Preface
Python is a widely used general-purpose programming language. Its
popularity can be attributed to its simplicity and a rich set of powerful
features. The clean and intuitive syntax makes it an excellent choice for
novices, allowing them to grasp the fundamentals of programming quickly,
and the advanced features make it appealing to experienced programmers
too. It can run on various platforms, including Windows, macOS, and
Linux. Since it is an open-source software, it is freely available to all.

The widespread usage of Python is evident in the technology world, with


major companies and organizations such as Google, Amazon, Instagram,
Facebook, and NASA using it in different ways. Whether you are involved
in machine learning, data science, artificial intelligence, scientific
computing, automation or you need to create robust web applications and
games, Python provides the necessary tools and resources. The extensive
collection of libraries available in Python can be effectively utilized across
diverse domains. Therefore, adding Python to your skill set can greatly
enhance your capabilities and open up numerous opportunities in various
fields.

This book provides a thorough and comprehensive introduction to Python,


focusing on the core programming concepts and problem-solving skills
required for building a solid foundation in programming. Throughout the
book, there are numerous programming examples and end-of-chapter
exercises to give you a hands-on experience. The exercises include
multiple-choice questions and programming problems; multiple-choice
questions will assess both your memory and comprehension of the topic,
while the programming exercises will provide you with a chance to apply
the acquired concepts. The book includes coding conventions and best
practices for writing efficient, readable, and maintainable code. The code in
the book is written and tested using Python version 3.11, which is the most
recent version at the time of publishing the book.

Python is easy to learn. You can start writing Python programs within a few
days. However, if you wish to leverage all the powerful features of Python,
a more in-depth exploration is required. The content in this book can assist
you in achieving that. This book includes 21 chapters that gradually
introduce new topics so learners can proceed at a sustainable pace. If you
are a beginner, start from the first chapter and go through all the chapters in
order, and work out the examples and exercises along the way. If you have
a working knowledge of Python, you can quickly browse through the initial
chapters and then randomly jump to topics that are new to you or that you
want to master. However, I would still recommend reading the chapters in
sequence to get the most out of the book. If you are transitioning from
some other language, you might be tempted to skip the initial information,
but I would suggest you go through all the basic details to avoid any
confusion later. Here is a brief summary of the chapters presented in the
book.

Chapter 1 is an introduction to Python and shows the installation process.


Chapter 2 covers the fundamental elements of Python, such as data types,
variables, input, output, and many other basic concepts you need to get
started in Python. Chapter 3 provides a detailed explanation of strings that
represent textual data in Python. Chapters 4 and 5 cover the container
types: lists, tuples, dictionaries, and sets. Chapter 6 provides an insight into
conditional execution. In chapter 7, we will see how to perform repetitive
tasks using loops, and chapter 8 discusses some common looping
techniques in Python. Chapter 9 introduces the concept of comprehensions
which help us write shorter and readable code.

Chapter 10 contains detailed coverage of functions. We will see how to


create our own functions and will discuss parameters, arguments,
arguments passing, function objects, and many other details about
functions. Chapter 11 shows how to create and use modules and packages.
Chapter 12 is about namespaces and scoping rules. Chapter 13 shows how
to write programs that can create files, write data into files, and read the
data stored in files. Chapters 14, 15, and 16 provide you with a strong
understanding of the object-oriented concepts. We will discuss classes,
objects, methods, inheritance, polymorphism, and magic methods. Chapters
17 and 18 are devoted to advanced topics like iterators, generators, and
decorators. Chapter 19 is about functional programming and lambda
functions. Chapter 20 shows how to handle run-time errors in Python, and
Chapter 21 discusses context managers that are used to automate common
resource management patterns.

At the end of each chapter, you will find exercises, and their solutions are
provided at the end of the book. I would suggest that you try to solve these
exercises by yourself before looking at the solution. Solving exercises and
writing code will help you to internalize the concepts presented in the book.

Some typographical conventions are followed throughout the book for a


good reading experience. The code snippets and programs in the book
appear in this font to differentiate them from the regular text. Program
elements, such as variable names, types, etc., within the regular text, are in
this font. Any output produced by the code on the screen as a result of
running a program or anything that the user has to input through the screen
appears in this font.

My aim was to write an absolute hands-on book that is simple enough to


follow and yet gives detailed knowledge. Reading this book will be a
breeze, yet it will give you a comprehensive knowledge of Python and
instill the confidence to excel in any written test, interview, or professional
work. Programming is fun only when you get your hands dirty with code.
Reading a book is not enough for learning programming. I highly
recommend that you try the coding examples and exercises presented in the
book. The efforts you put in to strengthen your fundamentals of core
programming concepts will take you a long way in your software
development journey.

By the end of this book, you will develop a strong foundation in core
Python skills and will get the ability to explore the vast range of
functionalities offered by the standard library and third-party libraries. As
you progress, you will continue to be amazed by the capabilities of Python
and the remarkable libraries available. With your newfound skills you can
venture into diverse fields like data science or machine learning. Moreover,
if this is the first programming language you are learning, equipped with
the foundation of programming concepts and problem-solving skills, you
can easily learn any other programming language.
After using this book as a tutorial to learn the language, you can always
refer to it as a handy resource whenever you need to recall or review any
concept and apply it to your work.

Writing this book was a very enjoyable, insightful, and amazingly


satisfying journey for me and I am sure my readers will have a similar
experience while reading the book. I hope you enjoy reading the book and
start loving Python.

Happy programming!
Code Bundle and Coloured Images
Please follow the link to download the

Code Bundle and the Coloured Images of the book:

https://rebrand.ly/z815rfg

The code bundle for the book is also hosted on GitHub at


https://github.com/bpbpublications/Ultimate-Python-Programming. In case
there’s an update to the code, it will be updated on the existing GitHub
repository.

We have code bundles from our rich catalogue of books and videos
available at https://github.com/bpbpublications. Check them out!

Errata

We take immense pride in our work at BPB Publications and follow best
practices to ensure the accuracy of our content to provide with an indulging
reading experience to our subscribers. Our readers are our mirrors, and we
use their inputs to reflect and improve upon human errors, if any, that may
have occurred during the publishing processes involved. To let us maintain
the quality and help us reach out to any readers who might be having
difficulties due to any unforeseen errors, please write to us at :

errata@bpbonline.com

Your support, suggestions and feedbacks are highly appreciated by the BPB
Publications’ Family.

Did you know that BPB offers eBook versions of every book published,
with PDF and ePub files available? You can upgrade to the eBook version
at www.bpbonline.com and as a print book customer, you are entitled to a
discount on the eBook copy. Get in touch with us at :

business@bpbonline.com for more details.


At www.bpbonline.com, you can also read a collection of free technical
articles, sign up for a range of free newsletters, and receive exclusive
discounts and offers on BPB books and eBooks.

Piracy

If you come across any illegal copies of our works in any form on the
internet, we would be grateful if you would provide us with the location
address or website name. Please contact us at business@bpbonline.com
with a link to the material.

If you are interested in becoming an author

If there is a topic that you have expertise in, and you are interested in either
writing or contributing to a book, please visit www.bpbonline.com. We
have worked with thousands of developers and tech professionals, just like
you, to help them share their insights with the global tech community. You
can make a general application, apply for a specific hot topic that we are
recruiting an author for, or submit your own idea.

Reviews

Please leave a review. Once you have read and used this book, why not
leave a review on the site that you purchased it from? Potential readers can
then see and use your unbiased opinion to make purchase decisions. We at
BPB can understand what you think about our products, and our authors
can see your feedback on their book. Thank you!

For more information about BPB, please visit www.bpbonline.com.

Join our book’s Discord space

Join the book’s Discord Workspace for Latest updates, Offers, Tech
happenings around the world, New Release and Sessions with the Authors:

https://discord.bpbonline.com
Table of Contents
1. 1. Introduction to Python

1. 1.1 What makes Python so popular

2. 1.2 Python implementation

3. 1.3 Installing Python

4. 1.4 Python Interactive Mode

5. 1.5 Executing a Python Script

6. 1.6 IDLE

7. 1.7 Getting Help

2. 2. Getting Started

1. 2.1 Identifiers

2. 2.2 Python Types

3. 2.3 Objects

4. 2.4 Variables and assignment statement

5. 2.5 Multiple and Pairwise Assignments

6. 2.6 Deleting a name

7. 2.7 Naming convention for constants

8. 2.8 Operators

1. 2.8.1 Arithmetic operators


2. 2.8.2 Relational operators

3. 2.8.3 Logical operators

4. 2.8.4 Identity operators

5. 2.8.5 Membership operators

6. 2.8.6 Bitwise operators

9. 2.9 Augmented assignment statements

10. 2.10 Expressions

11. 2.11 Order of operations: Operator Precedence and Associativity

12. 2.12 Type Conversion

13. 2.13 Statements

14. 2.14 Printing Output

15. 2.15 Getting user input

16. 2.16 Complete programs

17. 2.17 Comments

18. 2.18 Indentation in Python

19. 2.19 Container types

20. 2.20 Mutable and Immutable Types

21. 2.21 Functions and methods

22. 2.22 Importing

23. 2.23 Revisiting interactive mode


24. 2.24 Errors

25. 2.25 PEP8

26. Exercise

3. 3. Strings

1. 3.1 Indexing

2. 3.2 Strings are immutable

3. 3.3 String Slicing

4. 3.4 String Concatenation and Repetition

5. 3.5 Checking membership

6. 3.6 Adding whitespace to strings

7. 3.7 Creating multiline strings

8. 3.8 String methods

9. 3.9 Case-changing methods

10. 3.10 Character classification methods

11. 3.11 Aligning text within strings

12. 3.12 Removing unwanted leading and trailing characters

13. 3.13 Searching and replacing substrings

14. 3.14 Chaining method calls

15. 3.15 String comparison

16. 3.16 String conversions


17. 3.17 Escape Sequences

18. 3.18 Raw string literals

19. 3.19 String formatting

20. 3.20 String formatting using the format() method of string class

21. 3.21 Representation of text - character encodings

22. Exercise

4. 4. Lists and Tuples

1. 4.1 Accessing individual elements of a list by indexing

2. 4.2 Getting parts of a list by slicing

3. 4.3 Changing an item in a list by index assignment

4. 4.4 Changing a Portion of the list by slice assignment

5. 4.5 Adding an item at the end of the list by using append()

6. 4.6 Adding an item anywhere in the list by using insert()

7. 4.7 Adding multiple items at the end by using extend() or +=

8. 4.8 Removing a single element or a slice by using the del


statement

9. 4.9 Removing an element by index and getting it by using pop()

10. 4.10 Removing an element by value using remove()

11. 4.11 Removing all the elements by using clear()

12. 4.12 Sorting a List

13. 4.13 Reversing a List


14. 4.14 Finding an item in the list

15. 4.15 Comparing Lists

16. 4.16 Built-in functions used on lists

17. 4.17 Concatenation and Replication

18. 4.18 Using a list with functions from the random module

19. 4.19 Creating a list

20. 4.20 Using range to create a list of integers

21. 4.21 Using the repetition operator to create a list of repeated


values

22. 4.22 Creating a list by splitting a string

23. 4.23 Converting a list of strings to a single string using join()

24. 4.24 List of Lists (Nested lists)

25. 4.25 Copying a list

26. 4.26 Shallow copy and deep copy

27. 4.27 Repetition operator with nested lists

28. 4.28 Tuples

29. 4.29 Tuple packing and unpacking

30. Exercise

5. 5. Dictionaries and Sets

1. 5.1 Dictionaries

2. 5.2 Adding new key-value pairs


3. 5.3 Modifying Values

4. 5.4 Getting a value from a key by using the get() method

5. 5.5 Getting a value from a key by using the setdefault() method

6. 5.6 Getting all keys, all values, and all key-value pairs

7. 5.7 Checking for the existence of a key or a value in a dictionary

8. 5.8 Comparing dictionaries

9. 5.9 Deleting key-value pairs from a dictionary

10. 5.10 Creating a Dictionary at run time

11. 5.11 Creating a dictionary from existing data by using dict()

12. 5.12 Creating a dictionary by using the fromkeys() method

13. 5.13 Combining dictionaries

14. 5.14 Nesting of dictionaries

15. 5.15 Aliasing and Shallow vs. Deep Copy

16. 5.16 Introduction to sets

17. 5.17 Creating a set

18. 5.18 Adding and Removing elements

19. 5.19 Comparing sets

20. 5.20 Union, intersection, and difference of sets

21. 5.21 Frozenset

22. Exercise
6. 6. Conditional Execution

1. 6.1 if statement

2. 6.2 else clause in if statement

3. 6.3 Nested if statements

4. 6.4 Multiway selection by using elif clause

5. 6.5 Truthiness

6. 6.6 Short circuit behavior of operators and and or

7. 6.7 Values returned by and and or operators

8. 6.8 if else operator

9. Exercise

7. 7. Loops

1. 7.1 while loop

1. 7.1.1 Indentation matters

2. 7.1.2 Removing all occurrences of a value from the list


using the while loop

3. 7.1.3 while loop for input error checking

4. 7.1.4 Storing user input in a list or dictionary

2. 7.2 for loop

1. 7.2.1 Iterating over a string with for loop

2. 7.2.2 Unpacking in for loop header

3. 7.2.3 Iterating over dictionaries and sets


4. 7.2.4 Iterating through a series of integers

3. 7.3 Nesting of Loops

1. 7.3.1 Using nested loops to generate combinations

2. 7.3.2 Iterating over nested data structures

4. 7.4 Premature termination of loops using the break statement

5. 7.5 continue statement

6. 7.6 else block in Loops

7. 7.7 pass statement

8. 7.8 for loop vs. while loop

9. Exercise

8. 8. Looping Techniques

1. 8.1 Iterating in sorted and reversed order

2. 8.2 Iterating over unique values

3. 8.3 Index-Based for loops

4. 8.4 Making in-place changes in a list while iterating

5. 8.5 Skipping some items while iterating

6. 8.6 Using range and len combination to shuffle a sequence

7. 8.7 enumerate function

8. 8.8 Iterating over multiple sequences using zip

9. 8.9 Modifying a collection while iterating in a for loop


10. 8.10 Infinite loop with break

11. 8.11 Avoiding complex logical conditions using break

12. Exercise

9. 9. Comprehensions

1. 9.1 List Comprehensions

2. 9.2 if clause in list comprehension

3. 9.3 Ternary operator in list comprehension

4. 9.4 Modifying a list while iterating

5. 9.5 Getting keys from values in a dictionary using list


comprehension

6. 9.6 Using list comprehensions to avoid aliasing while creating


lists of lists

7. 9.7 Multiple for clauses and Nested list Comprehensions

8. 9.8 Extracting a column in a matrix

9. 9.9 Dictionary Comprehensions

10. 9.10 Inverting the dictionary

11. 9.11 Set Comprehensions

12. 9.12 When not to use comprehensions

13. Exercise

10. 10. Functions

1. 10.1 Function Definition


2. 10.2 Function call

3. 10.3 Flow of control

4. 10.4 Parameters and Arguments

5. 10.5 No type checking of arguments

6. 10.6 Local Variables

7. 10.7 return statement

8. 10.8 Returning Multiple Values

9. 10.9 Semantics of argument passing

1. 10.9.1 Why study argument passing

2. 10.9.2 Pass by assignment

3. 10.9.3 Assignment inside function rebounds the parameter


name

4. 10.9.4 Immutables vs Mutables as arguments

5. 10.9.5 How to get the changed value of an immutable type

6. 10.9.6 How to prevent change in mutable types

7. 10.9.7 Digression for programmers from other languages

8. 10.9.8 Advantages of Python’s information passing

10. 10.10 Default Arguments

11. 10.11 Default arguments that could change over time

12. 10.12 Positional and Keyword Arguments

13. 10.13 Unpacking Arguments


14. 10.14 Variable number of positional arguments

15. 10.15 Variable number of keyword arguments

16. 10.16 Keyword-only arguments

17. 10.17 Positional-Only Arguments

18. 10.18 Multiple Unpackings in a Python Function Call

19. 10.19 Arguments and Parameters summary

20. 10.20 Function Objects

21. 10.21 Attributes of a function

22. 10.22 Doctrsings

23. 10.23 Function Annotations

24. 10.24 Recursive Functions

25. Exercise

11. 11. Modules and Packages

1. 11.1 Modules

2. 11.2 Types of modules

3. 11.3 Exploring modules

4. 11.4 Creating and naming a new module

5. 11.5 Importing a module

6. 11.6 Importing all names from a module

7. 11.7 Restricting names that can be imported


8. 11.8 Importing individual names from a module

9. 11.9 Using an alias while importing

10. 11.10 Documenting a module

11. 11.11 Module search Path

12. 11.12 Module object

13. 11.13 Byte compiled version of a module

14. 11.14 Reloading a module

15. 11.15 Scripts and modules

16. 11.16 Packages

17. 11.17 Importing a package and its contents

18. 11.18 Subpackages

19. 11.19 Relative imports

20. Exercise

12. 12. Namespaces and Scope

1. 12.1 Namespaces

2. 12.2 Inspecting namespaces

3. 12.3 Scope

4. 12.4 Name Resolution

5. 12.5 global statement

6. 12.6 nonlocal statement


7. Exercise

13. 13. Files

1. 13.1 Opening a File

2. 13.2 File opening modes

3. 13.3 Buffering

4. 13.4 Binary and Text Files

5. 13.5 Closing a file

6. 13.6 with statement

7. 13.7 Random Access

8. 13.8 Using seek in text mode

9. 13.9 Calling seek in append mode

10. 13.10 Reading and writing to the same file

11. 13.11 Reading a File using read()

12. 13.12 Line oriented reading

13. 13.13 Writing to a file

14. 13.14 Redirecting output of print to a file

15. 13.15 Example Programs

16. 13.16 File Related Modules

17. 13.17 Command Line Arguments

18. 13.18 Storing and Retrieving Python objects using pickle


19. Exercise

20. Project : Hangman Game

14. 14. Object Oriented Programming

1. 14.1 Programming Paradigms

2. 14.2 Introduction to object-oriented programming

3. 14.3 Defining Classes and Creating Instance Objects

4. 14.4 Adding methods to the class

5. 14.5 Adding instance variables

6. 14.6 Calling a method inside another method

7. 14.7 Common pitfalls

8. 14.8 Initializer

9. 14.9 Data Hiding

10. 14.10 Class Variables

11. 14.11 Class and object namespaces

12. 14.12 Changing a class variable through an instance

13. 14.13 Class Methods

14. 14.14 Creating alternative initializers using class Methods

15. 14.15 Static Methods

16. 14.16 Creating Managed Attributes using properties

1. 14.16.1 Creating read only attributes using properties


2. 14.16.2 Creating Computed attributes using properties

3. 14.16.3 Deleter method of property

17. 14.17 Designing a class

18. Exercise

19. Project : Quiz creation

20. Project : Snakes and Ladders Game

21. Project : Log in system

15. 15. Magic Methods

1. 15.1 Overloading Binary Arithmetic operators

2. 15.2 Reverse methods

3. 15.3 In-place methods

4. 15.4 Magic Methods for comparison

5. 15.5 Comparing objects of different classes

6. 15.6 String representation of an instance object

7. 15.7 Construction and destruction of objects

8. 15.8 Making instance objects callable

9. 15.9 Overloading type conversion functions

10. 15.10 List of magic methods

11. Exercise

12. Project : Date Class


16. 16. Inheritance and Polymorphism

1. 16.1 Inheriting a class

2. 16.2 Adding new methods and data members to the derived class

3. 16.3 Overriding a base Method

4. 16.4 Invoking the base class methods

5. 16.5 Multilevel Inheritance

6. 16.6 object class

7. 16.7 Multiple Inheritance

8. 16.8 Method Resolution Order (MRO)

9. 16.9 super and MRO

10. 16.10 Polymorphism

11. 16.11 Abstract Base classes

12. 16.12 Composition

13. Exercise

17. 17. Iterators and Generators

1. 17.1 Iterables

2. 17.2 Iterators

3. 17.3 for loop Iteration Context – How for loop works

4. 17.4 Iteration Tools

5. 17.5 Iterator vs Iterable


6. 17.6 Creating your own Iterator

7. 17.7 Making your class Iterable

8. 17.8 Some More Iterators

9. 17.9 Lazy evaluation

10. 17.10 itertools Module

11. 17.11 Generators

12. 17.12 Generator function vs Normal function

13. 17.13 Generator expressions

14. Exercise

18. 18. Decorators

1. 18.1 Prerequisites for understanding decorators

2. 18.2 Introduction to decorators

3. 18.3 Writing your first decorator

4. 18.4 Applying your decorator to multiple functions

5. 18.5 Automatic decoration syntax

6. 18.6 Decorator Example: Timer

7. 18.7 Decorator Example: Logger

8. 18.8 Decorator Example: Counting function calls

9. 18.9 Applications of decorators

10. 18.10 Decorating functions that take arguments


11. 18.11 Returning values from decorated functions

12. 18.12 Decorator Example: Checking return values

13. 18.13 Decorator Example: Checking argument values

14. 18.14 Applying Multiple Decorators

15. 18.15 Preserving metadata of a function after decoration

16. 18.16 General template for writing a decorator

17. 18.17 Decorators with parameters

18. 18.18 General template for writing a decorator factory

19. 18.19 Decorator factory example

20. 18.20 Applying decorators to imported functions

21. 18.21 Decorating classes

22. 18.22 Class Decorators

23. 18.23 Class Decorators with parameters

24. Exercise

19. 19. Lambda Expressions and Functional Programming

1. 19.1 Lambda expression

2. 19.2 Comparing def statement and lambda expression

3. 19.3 Examples of lambda expressions

4. 19.4 Using Lambda expressions

5. 19.5 Using lambda expressions for returning function objects


6. 19.6 Lambda expressions as closures

7. 19.7 Creating jump tables using lambda functions

8. 19.8 Using lambda expressions in sorted built-in function

9. 19.9 Functional programming

10. 19.10 map

11. 19.11 map with multiple iterables

12. 19.12 filter

13. 19.13 Reducing an iterable

14. 19.14 Built-in reducing functions

15. 19.15 operator module

16. Exercise

20. 20. Exception Handling

1. 20.1 Types of Errors

2. 20.2 Strategies to handle exceptions in your code

3. 20.3 Error Handling by Python (Default exception handling)

4. 20.4 Built-in Exceptions: Python Exceptions Class Hierarchy

5. 20.5 Customized Exception Handling by using try…except

6. 20.6 Catching multiple exceptions using multiple except


handlers and single except handler

7. 20.7 How to handle an exception

8. 20.8 Guaranteed execution of finally block


9. 20.9 else Block

10. 20.10 Why do we need an else block

11. 20.11 How to get exception details

12. 20.12 Nested try statements

13. 20.13 Raising Exception

14. 20.14 Re-raising Exception

15. 20.15 Chaining Exceptions

16. 20.16 Creating your own exceptions in Python (Custom


exceptions)

17. 20.17 Assertions

18. Exercise

21. 21. Context Managers

1. 21.1 with statement

2. 21.2 Implementing our own context manager

3. 21.3 Exception raised inside with block

4. 21.4 Why we need with statement and context managers

5. 21.5 Runtime context

6. 21.6 Example: Sending output of a portion of code to a file

7. 21.7 Example : Finding time taken by a piece of code

8. 21.8 Using context managers in the standard library

9. 21.9 Nested with statements and multiple context Managers


10. 21.10 Implementing a context manager by using a decorator on a
generator

11. Exercise

22. Solutions

23. Index
Introduction to Python 1

Python is a widely used high-level and general-purpose programming


language originally developed by Guido Van Rossum in the early 1990s in
the Netherlands. It is maintained by a community of core developers who are
actively engaged in its growth and advancement. Although the official logo
of Python shows two intertwined snakes, it is not named after any snake.
Van Rossum named this language after a 1970s comedy show 'Monty
Python's Flying Circus'.
Python has three major versions; the initial version, Python 1.0, was released
in January 1994. The second major version, Python 2.0, was released in
2000, and the third major version, Python 3.0, was released in 2008. Python
3 is not backward compatible with Python 2; this means that the code written
in Python 2 may not work as expected in Python 3 without making some
modifications. In this book, we will use Python 3. The latest release of
Python is available on its official website www.python.org. Python is an
open-source software, which means that it is free to use and distribute.

1.1 What makes Python so popular


Python is a general-purpose language used in a wide variety of domains. It is
used extensively in different fields such as web development, data mining,
artificial intelligence, image processing, robotics, network programming,
developing user interfaces, database programming, scientific and
mathematical computing, game programming, and even education. Most of
the top companies and organizations, such as Google, Facebook, Amazon,
and NASA, use Python in different ways. Let us see some of the key factors
that contribute to Python's popularity.
Python is very easy to learn. It doesn't take much time to become productive
with Python. This is why it is often the introductory programming language
taught in many universities. Compared to languages such as C++ or Java,
Python code tends to be more concise, requiring fewer lines of code to
achieve the same functionality. Due to the simple syntax of Python,
programmers can focus more on finding the solution to a problem instead of
getting caught up in complex language features. Python uses indentation for
grouping together statements, resulting in a visually clean layout that
enhances code readability.
Python offers a convenient command line interface known as the 'Python
interactive shell' or 'Python REPL' (Read-Eval-Print Loop). With the Python
interpreter, you have the option to work interactively, allowing you to test
and debug small sections of code in real-time. The interactive mode serves
as a useful tool for experimenting and exploring Python's features.
One of the main advantages of Python is that it takes care of memory
management automatically. Python's built-in memory management system
allocates memory when needed and frees it up when it is no longer in use.
Programmers do not have to worry about managing memory manually, as
they would have to do in other languages like C or C++.
Python includes a vast standard library of modules; this is why the phrase
'Batteries included' is often used for Python. These modules contain code
that you can use in your own programs. In addition to the extensive standard
library, many third-party libraries are also available for use. Thus, you have
access to lots of prewritten reusable code in the form of standard library
modules and third-party modules, which can do most of the work for you
and save you from reinventing the wheel. This code can be incorporated into
your code to develop complex solutions with minimal effort. Whether you
are working on web programming, creating graphics, analyzing data,
performing mathematical calculations, engaging in scientific computing, or
developing games, you will find reusable code modules that can help you
achieve your goals.
Python supports multiple programming paradigms, including procedural,
functional, and object-oriented programming. Thus, programmers have the
flexibility to choose the coding structure that best suits their needs. The
object-oriented features of Python are much easier to implement and are
more intuitive when compared to similar features found in other
programming languages.
Python is a cross-platform and portable programming language, which
means that programs written in Python can be developed and executed on
various hardware platforms and operating systems. The same code can be
executed on multiple platforms without making any significant changes. The
cross-platform development minimizes the efforts required to adapt the
programs to different systems and thus facilitates code reuse and sharing on
different platforms.
Python has the capability to interact with software components written in
other languages. Python code can call libraries written in C and C++, and it
can also integrate with components developed in Java and .NET. This allows
Python programmers to tap into the strengths and functionalities of other
languages and libraries written in them. Python is also embeddable which
means that Python code can be placed within the code of another language
like C or C++.
Another reason for Python's popularity is its large base of active and
supportive developer community. Community members are actively engaged
in improving and enhancing the capabilities of Python as well as in
developing various libraries and tools. There are numerous resources and
extensive support available due to the vibrant community members.
Python has emerged as the preferred programming language for developers
because of its ease of use and powerful features. It is suitable both for
beginners and experts alike, and due to its versatility, it can be used in a
variety of applications.
In the next section we will learn about Python implementations and will see
what happens internally when a Python program is executed. While it is not
necessary to have this knowledge in order to write and run programs, having
a fundamental understanding of what occurs behind the scenes during
program execution is beneficial for a comprehensive understanding of the
language.

1.2 Python implementation


The terms C, C++, Basic, Java, or Python refer to programming languages,
which are essentially sets of rules and specifications. In order to use these
languages, they need to be implemented by creating software that allows us
to write programs in that language and run them on a computer. The
implementation of a language is the program that actually runs the code that
you write in that language. An implementation translates the source code to
native machine code instructions (binary 0s and 1s) so that the computer's
processor can execute it.
There are primarily two approaches to implementing a programming
language: compilation and interpretation. In compilation, a compiler
translates the complete program code in one go to another language such as
machine code or bytecode. If the translated code is machine code that is
understood by the processor, then it is directly executed, and if it is
bytecode, then it has to be again input to another interpreter or compiler. In
interpretation, an interpreter translates the code to machine code one line at a
time; a line of code is read, translated, and executed, then the next line is
read, translated, and executed, and so on. The code is translated line by line
at run time, so the interpreted implementations tend to be slower than the
compiled ones, which translate the whole code at once.
An implementation of a language can be a compiler, interpreter, or a
combination of both. A programming language can have multiple
implementations, and these implementations can be written in different
languages and can use different approaches to compile or interpret code. The
notion of interpretation and compilation is associated with language
implementation rather than the language itself; describing a language as
compiled or interpreted is not technically correct. The language
implementations that are written for a language are described as compiled or
interpreted and not the language. Compilation or interpretation is not a part
of the language specification; it is an implementation decision. The
implementations of C and C++ mostly use the compilation approach, while
Java, Python, and C# implementations generally use a combination of
compilation and interpretation techniques. C and C++ compilers translate
source code to machine code, which is executed directly by the processor.
Python has multiple implementations. The original and standard
implementation of Python is CPython written in C language. It is the most
widely used and up-to-date implementation of Python. When you download
Python software from the official site python.org, this is the implementation
that you get. The other implementations are Jython written in Java, and
IronPython written for the .NET platform. PyPy is the implementation that is
written in RPython, which is a subset of Python.
The software that is used for running Python programs is referred to as
Python interpreter. Let us understand how CPython interpreter combines the
compilation and interpretation techniques to execute a Python program.
We write our Python code in a source file (.py file), but the computer cannot
understand and execute this code; it can execute only machine code, which
consists of instructions written in binary form (0s and 1s). The source code
has to be converted to machine code so that the processor can execute it. The
source code is not directly converted to machine code. It is first compiled
into an intermediate form known as the bytecode. This bytecode is a low-
level code that is Python-specific and platform-independent, but it is not
understandable to the processor.
There is another software called Python Virtual Machine (PVM), that is
responsible for executing this bytecode on a specific platform. The bytecode
passes through the Python Virtual machine; it interprets this bytecode, which
means that it converts the bytecode instructions to machine code instructions
one by one and sends these machine code instructions to the processor for
execution, and we get the output. So, the job of PVM is to convert the
bytecode instructions to machine code instructions that the processor can
understand and execute.

Figure 1.1: The execution of a Python program

This is what happens when we execute a Python program. The intermediate


compilation step is hidden from the programmer; we can just type and run
our program immediately. The programmer does not have to explicitly
compile the code, so there is no separate compile time in Python; there is
only runtime. The compilation to bytecode is done to improve the efficiency
as the bytecode can be interpreted faster than the original source code.
In this whole process, the bytecode complier is a software that converts
source code to bytecode, and PVM is a software that converts bytecode to
machine code for the target platform. Python Virtual machine contains some
platform-specific components that may be implemented differently for each
platform. This allows the virtual machine to covert the bytecode into native
machine code according to the platform. It abstracts away the underlying
hardware and operating system details and thus provides a consistent
runtime environment for Python programs across different platforms. Both
the bytecode compiler and the virtual machine are part of the Python
interpreter software and are included in your Python installation.
The intermediate bytecode is generally cached for faster execution. It is
stored in .pyc or .pyo files inside a folder named __pycache__ and the
programmer can just ignore these files. When the program is run multiple
times without modifying the source code, the compiled bytecode from the
cached file is loaded and executed instead of re-compiling from source code
to bytecode every time. This bytecode is stored only for imported files, not
for the top-level scripts; we will see the difference between the two later in
the book.
The Jython implementation translates Python code into Java bytecode,
enabling its execution on a Java virtual machine. An advantage of Jython is
its ability to directly access Java libraries. Similarly, IronPython is designed
for the .NET framework and facilitates integration with .NET components.
Some implementations of virtual machines (bytecode interpreters) use just-
in-time (JIT) compilation approach to speed up the interpretation process.
The PyPy implementation of Python has better speed as it includes a just-in-
time compiler for faster execution of the bytecode. Just-in-time compiler
will compile the frequently executed blocks of bytecode to machine code
and cache the result. Next time, when the virtual machine has to execute the
same block of bytecode, the precompiled(cached) machine code is utilized
and executed, resulting in faster execution. So, the JIT compiler uses the
compilation approach to improve the efficiency of bytecode execution.

1.3 Installing Python


To download Python, visit the official website of Python. On the homepage,
select the Downloads option to go to the download page, or you can directly
go to www.python.org/downloads/. The website will automatically detect
your operating system and provide a suitable installer that corresponds to
your system's requirements, whether it be 32-bit or 64-bit. Click on the
Download button to download the installer (.exe) file for the latest version of
Python. At the time of writing this book, the latest version is 3.11.3. If you
wish to download any previous version of Python, you can scroll down the
page and click on the download button located next to the version number
you desire.

Figure 1.2: Official website of Python

Once the download is complete, double-click on the installer to execute it


and begin the installation process. On the first screen of the installer, you
will be presented with two choices: "Install Now" and "Customize
Installation." Clicking on "Install Now" will install Python with the default
features, while clicking on "Customize Installation" will allow you to
change the installation location or install other optional and advanced
features. The defaults should work well for now, so we will go with Install
Now. Before clicking on Install Now, make sure to select the Add
python.exe to PATH checkbox, as this will add Python to your system's
PATH environment variable and will enable you to run Python from the
command prompt.

Figure 1.3: Installing Python

Click Yes if it asks for permission to make changes to your device. The
installation begins, and all the required Python files, along with the standard
library, will be installed on your system.
Figure 1.4: Installation in progress

After the installation is complete, the following pop-up box will appear. This
shows that Python is installed on your system. Click on Close to complete
the installation and exit the installer. The appearance of the images shown in
the screenshots may vary depending on the version of Python that you
choose to install.
Figure 1.5: Installation successful

To verify the installation, write cmd in the Start search menu to open the
command prompt window and type the command python --version.
If Python has been successfully installed on your system, it will show the
version of the Python installed. Now write python (all in lowercase) in the
command window. You will see a line with some text describing the Python
version, and after that, you will see a prompt with three greater-than signs
(>>>). This is the Python shell prompt. Write 8 + 2 and press Enter; you
will get the output as 10 on the next line. The prompt appears again; this
time, write print('Hello world'), and the text Hello world will
appear on the next line. This verifies that Python is up and working on your
system. On this interactive Python shell, you can execute single statements
of Python. To quit this Python shell and come back to your command
prompt, type quit() or exit() or press Ctrl-Z.
Figure 1.6: Verifying installation on the command line

You can also verify your installation by opening the Integrated Development
and Learning Environment application(IDLE), which is installed by default
with Python. To open IDLE, type idle or python in the Start search menu
and click on the IDLE app. If the installation is successful, IDLE will show
an interactive Python shell window in which you can type Python commands
at the shell prompt (>>>) and execute them.

Figure 1.7: Verifying installation on IDLE

Installation on Mac is done in a similar way. Most macOS systems come


with Python, but usually, it is the 2.x version. To check if Python is installed,
type python --version on your terminal. To check if Python 3 is
installed, type python3 --version on your terminal. If Python 3 is not
installed, you can install it from the official website, and if it is installed, you
can update it to get the latest version.
Visit the official Python website and download the installer package (.pkg
file) that if offers for your system. After downloading, double-click on the
installer to run the installation process. Proceed with the installation by
following the on-screen instructions and accepting the defaults. You may
need to enter your administrator password to authorize the installation.
After the installation process is complete, Python's installation folder will
automatically open up. Inside this folder, you will find IDLE application,
which, as we have seen, is the development environment that comes with
Python. Double-click on this application to open it. If the installation is
successful, IDLE will display the interactive Python shell. You can type
Other documents randomly have
different content
We soon obtained a view of the lakes that spread themselves before
us—viz.: Llyn Peris and Llyn Padarn, with the romantic castle of
Dolbadarn upon its rocky promontory. On issuing from a pass on
our left, as I was informed, is a valuable copper mine, and a stream
of water conveyed over the road, by the aid of a wooden conduit,
into the lake, which stream was for the use of the mine.
At length, I reached the inn, called Victoria, ordered breakfast, and
procured an admittance to the Castle of Dolbadarn. This ancient
fortress is supposed to have been built by one Padarn Beisrudd ab
Idwal, for the purpose of guarding the mountain pass which I had
just quitted. A single round tower is all that remains of the castle,
although traces are left of a much more extensive building. Here
Owen Gôch was imprisoned twenty years by his brother Llewelyn,
the last Prince of Wales of the British line; and an ode is still extant,
written by Howel Voel, wherein his captivity is affectionately
lamented.
The view from the castle is truly sublime, comprising the two lakes,
and the tremendous range of mountains, that seem to admit of no
outlet from the vale. But the most beautiful prospect is from the
lake in front of the promontory on which the castle stands, and is
reflected in the smooth waters beneath, while the majestic Snowdon
towers in the distance.
Returning to the Victoria, I partook of the refreshments provided,
and then retracing my steps, I visited the little rustic church of
Llanberis, which, for its simplicity, is well worthy of attention. Upon
entering the doorway, there is a small stone font placed upon a
pedestal which is approached by three stone steps: it resembles a
small washing tub, and its cover is much like a copper-lid.
Advancing into the interior, the music loft is upon the left, under
which is a dilapidated screen, opposite to the font. A doorway in the
centre of the screen leads into the body of the church, where
ancient oaken benches are ranged upon either side, and the pulpit
and communion table are immediately in front. The old arched roof
is held together by iron pins, which project on each side of the
timbers, and the whole interior is whitewashed. The only pew in the
church adjoins the communion table, both of which have suffered
materially by the worm and time. The few monuments in this simple
structure are upon small slate slabs, about the size of a school-boy’s,
and are hung up on the wooden beams.
On leaving the church, there is a monumental slate slab on the left
of the path, bearing the following inscription and verses:—

Underneath
Lieth the remains
Of John, the son of
Robert Closs, who was
Interred Decr. 1st,
1805, aged 7 years.
Ar ben mynydd dydd-y-daith oî howyder
A che dodd y maith
Gadewais (gwelais goeg waith)
Drueni’r Byd ar unwaith.
Oerfel fu uchel a chos, i angau
Llyn ingol i’mddangos
Mantell niwl mewn tywyll nos
A dychryniad dechreunos.

Upon returning to my inn at Gwrydd, I discovered that the landlady


was sister to little John Closs; and from her I learnt the story of his
melancholy fate. It is as follows:—
John was a pretty boy, about seven years of age, with fair hair and
blue eyes, of a sweet temper, adored by his parents, and loving
them most affectionately in return. Indeed little John Closs was the
talk of the parish, and held up as a pattern of filial love and
reverence to all the children in the village. His uncle had a small
farm at Nant Bettws; and John’s father having sent him to reside
there for a few months, the fond mother would often cross the
mountain to see her son and her sister, returning home in the
evening of the same day. Little John got tired of living away from
home, and one night, after his mother had quitted the cottage to
return to Llanberis, he wept so bitterly, and prayed so earnestly to
be permitted to follow her home, that the good people at Bettws
permitted him to try and overtake her, which they considered he
might easily do, as she had not left the house ten minutes before he
started.
The mother reached Llanberis in safety; but the poor boy lost his
way in a snow storm on Moel Einion, and was not heard of for more
than a week afterwards; when, one day, a man crossing the
mountain, found the child stretched on the ground in a slumbering
position, his face towards the earth, buried in his hands, and quite
dead.
The following morning, I proceeded towards Capel Curig, but this
road is very uninteresting. The tourist is, however, amply gratified, if
it happen to be tolerably clear weather, on his arrival at an ancient
stone bridge which crosses a stream that tumbles over some black
rocks on the right, and winds its way in graceful variety, forming a
pleasing spot to rest upon. Looking back towards Llanberis, the
mountain scenery is very fine; and I here took my farewell look of
Snowdon arid Snowdonia.

CAPEL CURIG,
is in the parish of Llandegai. It derives its name from a man who
was canonized, and founded a chapel in this mountainous region.
He was the son of Llawdden Lluyddog, of Edinburgh. There are here
two lakes, and some tolerable fishing may be had, if you take a
boat; but from the banks it is quite useless to attempt it. From this
spot, excursions may be made to Llanberis, and

MOEL SIABOD,
from the summit of which a magnificent view is obtained of the
mountains of Snowdonia, of nine different lakes, and the sea beyond
Carnarvon. The distance from the inn to the apex of the mountain
does not exceed three miles and a half.

DOLWYDDELAN CASTLE,
situated about five miles from Capel Curig, and on the eastward side
of Moel Siabod, deserves notice. It is built upon a lofty rock, which
on one side is inaccessible. There are two square towers, and a
court in the middle. It is surrounded by mountains, and must in
ancient days have been a fortress of considerable importance. It is
said, Llewelyn the Great was born in the castle; and this fact is
sufficient to interest the stranger who is capable of appreciating and
feeling reverence for a hero, who so long struggled with unwearied
assiduity and unconquerable bravery for his native land, and who
fought and died in the sacred cause of liberty.
Within four miles of Capel Curig is an oval lake, of about three miles
in circumference, called Llyn Ogwen which must by no means be
overlooked. The scenery around is delightful and the waters are
well stored with excellent trout of fine flavour, and surpassing all
others in that respect, in the Carnarvonshire lakes.
At the western end of this lake, are the Falls of Benglog, (being
three in number and upwards of one hundred feet in height) from
whence the waters take their course through Beavers’ Hollow, a wild
and romantic glen, rocky and barren.
Powell, in his History of North Wales, says, “In Tevi, above all the
rivers in Wales, were, in Giraldus’s time, a great number of castells,
which may be Englished beavers, and are called in Welsh avanc,
which name onlie remaineth in Wales at this day, but what it is, very
few can tell. It is a beast not much unlike an otter, but that it is
bigger, all hearie saving the taile, which is like a fish taile as broad as
a man’s hand. This beast useth as well the water as the land; and
hath a voice, sharp teeth, and biteth cruellie till he perceives the
bones cracke. * * * * He that will learn what strong nests they
make, which Giraldus calleth castells, which they build upon the face
of the water with great bowes, which they cut with their teeth, and
how some lie upon their backs holding the wood with their fore feet,
which the other draweth with a crosse stick, the which he holdeth in
his mouth, to the water’s side, and other particularities of their
natures, let him read Giraldus in his Topographie of Wales.”
In this stream are found the fresh water muscle, which the country
people call cregyn diluw, i.e. shells of the deluge, supposed to have
been brought into it by Noah’s flood.
On the left of the lake are the Crags of Trivaen, huge shattered
ridges, which overhang the pool and keep it in continual shadow,
while the sides of Braich-ddu slope gradually to the lake’s margin.
The Francon Mountains, in the distance, are astonishing, and
altogether this lake scene may be considered the finest in
Carnarvonshire.
A gentleman, in the winter of 1831, was driving along the road
which skirts the borders of the lake, when upwards of a thousand
tons of rock fell from the heights of Benglog, a little below the Falls,
into Nant Francon, a short time after he had passed them, and he
beheld one portion roll into the valley and river, while the other
rested upon the road he had just travelled, rendering it impossible
for any carriage to proceed by that route, until the obstruction was
removed.
A mile distant from Llyn Ogwen is another lake, well worthy of being
visited, which lies in a deep hollow of the Glyder Mountains, called

LLYN IDWAL,
where the gloomy horror of the scenery is most appalling;
particularly the terrific chasm of Twll Du, or the Black Cleft. This
spot derived its name from the following crime which was
perpetrated here.
Prince Owain Gwynedd, who reigned in the twelfth century, had a
favourite called Nevydd Hardd, to whose care he intrusted his son
Idwal, and who betraying his trust, commanded his son Dunawt to
destroy the young prince, a crime which he too faithfully obeyed,
perpetrating the cruel deed at this place. But, being discovered,
Nevydd and his posterity were degraded from the rank of nobles to
bondsmen, and Rhun, the son of Dunawt, who again became
possessed of the property of his ancestors, granted the ground upon
which the Church of Llanrwst now stands, as an expiatory gift for
the foul crime imputed to his father. The grave of Idwal is still
pointed out by the inhabitants, close to the lake.
The scenery around is well calculated to inspire fear in the timid, as
being adapted to the committal of atrocity of any kind. Bleak, black,
desolate, and stern, it thrills the beholder with an indescribable
sensation of terror.
The lake is well stored with fish, of a darker colour than those in the
Ogwen, and of a less delicate flavour. These lakes are in the parish
of Llan Tegai, so called from its patron saint Tegai, the son of Ithel
Hael, a nobleman of Armorica, brother to Credivael and Flewin, who
built Penmynydd and Llanflewin, in Anglesey, about the year 636.
See Rowland’s Mona Antiqua Rest. p. 189.
After a delightful day’s ramble amongst this wild and sublime
scenery, I returned to the inn at Capel Curig, and on the following
morning took the road to Llanrwst, which in a short time becomes
particularly interesting. The dark and comfortless sterility is
exchanged for a delightful valley, with luxuriant woods, which stretch
to the summit of the hills upon either side; and near the two mile
stone is one of the most picturesque cottages imaginable, placed on
the side of a hill above the bridge, which crosses the river Llugwy,
and gives additional beauty to the romantic dell.
Half a mile beyond is an Observatory, which stands upon the highest
point of a towering cliff, a portion of whose summit is clothed with
purple heath, and the remainder presents a face of grey barren rock,
while beneath a forest of rich foliage creeps from its base far up the
craggy sides.
Within a mile of this place are the celebrated waterfalls, called

RHAIADR Y WENNOL,
i.e. the Cataract of the Swallow—a fall of about sixty feet in width.
The river, at the top of the first fall, flows in an unbroken sheet, but
soon becomes dispersed in various streams that dash and struggle
through the impending masses of rock, charming the ear with their
complicated roar. At the second fall, it rushes in a collected volume
into the boiling vortex, from whence, at the third, it is dispersed in
spray. A small wicket gate by the road side, leads to a footpath
through the grounds to the Falls, where the visitor cannot fail to find
an adequate reward for his digression. The old oak trees that
overhang the ravine are beautifully grouped. On one side, a large
rock rises perpendicularly nearly 500 feet, and the earth is clothed
with velvet moss and decked with wild flowers. Fancy would picture
just such a retreat, for a wandering sylph! while the rays of light,
darting through the greenwoods, remind us of the flittings of Sir
John Wynne’s ghost, which was said to haunt this glen for many
years, but is now laid at rest in the depths of the Lower Fall.
Journeying onward, I reached the village of

BETTWS Y COED,
which, being translated, is the Station in the Wood; and a most
delightful station it is. The Shrewsbury and Holyhead road runs
through it, and the junction of the Llugwy and the Conwy rivers is at
no great distance. The church is a venerable structure, and contains
an old monument, erected to the memory of Gruffydd, the son of
David Gôch, who was a natural son of David, the brother of
Llewelyn, the last Prince of Wales. He died in the fourteenth
century, and a stone statue of him is in a recess on the north side of
the church, with this inscription: “Hic jacet Gruffydd ap Davyd Gôch,
agnus Dei miserere mei.”
At about a mile from Bettws is an iron bridge of one arch, which
carries the Holyhead road over the river Conwy. Its span is 105 feet,
and it is called the Waterloo Bridge, from its having been erected in
the year that tremendous battle was fought. But the principal object
is

PONT-Y-PAIR,
the Bridge of the Caldron. It has four arches, and the natural rock
supplies it with piers, that seem to defy the efforts of time or the
fury of the waters. Immediately above the bridge is the fall and
salmon-leap. The river rolls and plunges into a deep reservoir
below. The grandeur of the scene during the floods, I was informed,
surpasses imagination, and unfortunately for me, the heat of the sun
had dried them up, when I visited this celebrated spot.
For this bridge the inhabitants are indebted to one Howell, a mason,
who resided at Penllyn in the year 1468; and having occasion to
attend the assizes at Conway, he was unexpectedly prevented from
passing the Lleder by the fury of the flood. That a similar
disappointment might not occur to others, he erected a wooden
bridge across that river, and trusted to the generosity of travellers to
remunerate him. The success of this attempt encouraged him to
erect the bridge at Bettws y Coed, which is now called Pont y Pair,
but he died before it was completed.
Upon the right of this bridge is Carreg y Gwalch, or the Rock of the
Falcon, well clothed with trees, through which the bald cliffs peep,
like a body of sharp shooters from a brush wood anxious to escape
detection. In this rock is a recess called the Cave of Shenkin, a
celebrated outlaw, who found shelter here from the unremitting
efforts of justice during the reign of Edward IV. It is blocked up by a
piece of rock.
CHAPTER VIII.

Gwydir Castle.—Llanrwst Shaking Bridge.—Inn.—Town Hall.—Free


Schools.—Alms Houses.—Rhaiadr y Parc Mawr.—Llyn Geirionydd.
—Taliesin.—Trevriw.—Slate Quarries.—Conway.—The Suspension
Bridge.—The Castle.—Local Customs.—Excursion to the Orme’s
Head.

“On a rock whose haughty brow


Frowned o’er old Conway’s foaming flood,
Rob’d in a sable garb of woe,
With haggard eye, the poet stood.”
Gray.

Within half a mile from the town of Llanrwst is

GWYDIR CASTLE,
the property of Lord Willoughby d’Eresby, a family mansion of no
very attractive appearance. It is situated on the right of the road
which winds between it and a lofty wood-clad precipice, called
Carreg y Gwalch, or the Rock of the Falcon. It was built by John
Wynne ab Meredydd, in 1555, and has lately undergone some
alteration. The breakfast parlour contains a curious carving of the
arms of the Gwydir family, supported by Julius Cæsar and Augustus;
the former holding his commentaries in one hand, and his sword in
the other; the latter, his sword only. The dining room has some
specimens of carving, that are worthy of observation; but
throughout the mansion there is very little of what belonged to it
originally. The chairs, panelling, and even tables, being coloured for
the purpose of giving the apartments the appearance of antique
splendour, which, until lately, they wanted.
The drawing-room is spacious and lofty, and is lighted by a double
row of windows, which gives it a heavy look: this unusual
arrangement was caused by the removal of the dormitory, to give
height to this room. Over the fire-place is a finely executed carving
of Julius Cæsar in oak. At the N.W. end of the room, a piece of
tapestry represents a vintage, and at the S.E. another specimen of
needlework commemorates the landing of Charles the Fifth at
Grenada.
The coronation chair of George the Second is shewn in this
apartment, and the footstool used by Queen Caroline on her trial at
Westminster Hall. There is a centre table, very richly ornamented
with carved work; and another, which in shape exactly resembles the
slab and pedestal of a tombstone, so that the visitor naturally
enough walks up to it, expecting to see the customary “Hic jacet,”
&c.
The cradle of Sir Richard Wynne, bearing the date of 1634,
completes the list of curiosities contained in this room.
The garden, which is extensive, contains some valuable plants and
shrubs, and the terrace is a pleasant promenade, sloping from which
are beds of beautiful flowers, of various classes and descriptions.
After satisfying the housekeeper with a trifling gratuity, I proceeded
to Llanrwst, but halted upon the bridge to take a view of the Conwy,
(over which beautiful river its arches expand) and the town to which
it leads. I was here accosted by an old man, who asked me, “if I
should like to feel the bridge shake?” As I answered in the
affirmative, he desired me to place my back against the side over
the centre arch, and striking the opposite parapet rather heavily with
his own, a tremulous motion was distinctly felt; on this account it is
called the Shaking Bridge. It was built in 1636, from a plan of the
celebrated Inigo Jones, and cost £1000, which was defrayed by the
counties of Denbighshire and Carnarvonshire, which it unites.

LLANRWST
is built upon the Denbighshire side of the river. The Three Eagles is
the most commodious inn in the town; and, being rather fatigued, I
threw my limbs upon a sofa, and resigned myself to the drowsy god,
first taking especial care to order a substantial repast to be in
readiness for me on my return from the land of Nod. My last waking
recollection was the words of Mr. Lover’s favourite song,

“There’s no use at all in my going to bed,


For its dhrames and not sleep, that comes into my head.”

Dreams, however, did not picture my slumbers, and I awoke to the


unrivalled delight of a weary and hungry traveller—an excellent hot
dinner.
The following morning I employed in paying my respects to the
different gentlemen to whom I had letters, and in gaining what
information I could respecting the objects most worthy of notice in
the town and surrounding neighbourhood.
The church and chapel adjoining were the first subjects to engage
my attention. In the former there is nothing interesting, excepting
an oaken screen, exquisitely carved, which was taken from the
Abbey of Maenan, the gallery for the singers being above it. On the
opposite side is the

GWYDIR CHAPEL.
This beautiful structure was erected in the year 1633, by Sir Richard
Wynne, of Gwydir, from a design of Inigo Jones, and was for many
years the burial place of the illustrious family of Gwydir. At the sides
of the chapel, fixed in panels of wood, are several engravings on
brass, illustrative of the personages who are interred below; and in
the east corner is a tablet of white marble, containing the following
remarkable pedigree, comprising a period of 500 years.

“This chapel was erected A.D. 1633, by Sir Richard Wynne, of


Gwydir, in the county of Carnarvon, Knight and Baronet;
Treasurer to the High and Mighty Princess Henrietta Maria,
Queen of England, Daughter of Henry the Fourth, King of
France, and wife to our Sovereign Lord King Charles; where
lieth buried his father Sir John Wynne, of Gwydir, Knight and
Baronet, son and heir to Morris Wynne, son and heir to John
Wynne, son and heir to Meredith Wynne, which three lie buried
in the church of Dolwyddelen, with tombs over them. This
Meredith was son and heir to Evan, son and heir to Robert, son
and heir to Meredith, son and heir to Howell, son and heir to
David, son and heir to Griffith, son and heir to Cradock, son and
heir to Roderick, Lord of Anglesea, son to Owen Gwynneth,
Prince of Wales, and younger brother to David, Prince of Wales
who married Emma Plantagenet, sister to King Henry the
Second. There succeeded this David three princes; his nephew
Leolinus Magnus, who married Joan, daughter to King John,—
David, his son, nephew to King Henry the Third,—and Llewelyn
the last Prince of Wales of that house and line, who lived in King
Edward the First’s time. Sir John Wynne married Sydney, who
lyeth buried here, daughter of Sir William Gerrard, Knight, Lord
Chancellor of Ireland, by whom he had issue, Sir John Wynne,
who died at Lucca, in Italy, Sir Richard Wynne, now living,
Thomas Wynne, who lyeth here, Owen Wynne, now living,
Robert Wynne, who lyeth here, Roger Wynne, who lyeth here,
William Wynne, now living, Maurice Wynne, now living, Ellis
Wynne, who lyeth buried at Whitford, in the County of Flint,
Henry Wynne, now living, Roger Wynne, who lyeth here, and
two daughters, Mary, now living, married to Sir Roger Mostyn, in
the County of Flint, Knight, and Elizabeth, now living, married to
Sir John Bodville, in the County of Carnarvon, Knight.”
Beneath this is a superb engraving of Dame Sarah Wynne, one of
the daughters of the old Chevalier Sir Thomas Myddelton, of Chirk
Castle, and wife of the above-mentioned Sir Richard Wynne; she
died June 16th, 1671. This piece of engraving was executed by one
William Vaughan, in a style of elegance hardly to be met with, and
may be justly reckoned among the first productions of the age in
which he lived.
On the south side are two stately pyramidal columns of variegated
marble, decorated with martial insignia; one to the memory of
Meredith Wynne, the other to Sir John Wynne and Sydney his wife;
on their pedestals are Latin inscriptions on black marble which have
been thus translated:—

“To the Memory of Meredith Wynne, a descendant of Owen


Gwynedd, Prince of Wales, who under happy auspices, founded
the House of Gwydir, removed and endowed the Church of Sant
Gwyddelen, during the third Tournean expedition, in the fifth
year of Henry the Eighth. He died in the month of March,
1525.”
“To the Memory of John Wynne of Gwydir, Knight and Baronet,
with Sydney the daughter of William Gerrard, Knight, Chancellor
of the Kingdom of Ireland, the wife of his youth, to whom she
bore eleven sons and two daughters; they lie here waiting the
appearance of Christ in Glory.”

Between the above monuments is a small tablet of white marble to


the memory of John Wynne ab Meredith with a Latin inscription to
the following effect:—

“John Wynne ab Meredith,


an inheritor of his Father’s virtues, a just and pious
man, to whom Euna, his wife, brought five
sons and two daughters. He died
the 9th of July, 1559.”
On the floor is a stone effigy in armour, with the feet resting on a
lion couchant, of Howel Coetmore ap Gruffydd Vychan ap Dafydd
Gam, alias Gôch, natural son to David, Prince of Wales, from whose
descendants according to tradition, Gwydir was purchased by the
Wynnes.
Near to the effigy of Howel Coetmore is the under-part of a stone
coffin in which Llewelyn ab Iorwerth, surnamed the Great, the son-
in-law of King John, was buried at the Abbey of Conwy; to the coffin
is fixed a piece of brass with this inscription:—

“This is the coffin of Leolinus Magnus, Prince


of Wales, who was buried at the Abbey of
Conwy, which upon the dissolution
was removed thence.”

On going from the chapel to the church, you pass over a large
square flag of free stone, having on its sides a Latin inscription thus
translated:—

“To the Memory of the Sons of John Wynne of Gwydir, Knight


and Baronet, who died during their father’s life time; John,
Knight, was buried at Lucca, in the free State of Italy, in the
year of his age 30, of our Lord 1613. Robert, who had entered
into holy orders, in the year of his age 24, of our Lord 1617.
Thomas, Roger, Thomas, in their minority.—Death! a vapour!
Behold! we have existed.”

In the chancel, between the reading desk and the communion table,
is a flag of free stone on the remains of Margaret Vaughan, heiress
of Caergai; she was esteemed the Sappho of her age; many of her
poetical productions are still extant.
The gallery over the reading desk is said to have been removed here
from the Abbey of Aberllechog, or Maenan Abbey, upon the
dissolution of that religious house.
Under the reading desk in the Church, in a pew belonging to Kyffdy,
is a Latin epitaph to the memory of Griffith Lloyd, of Bruniog, Rector
of this parish; this is said to have been written by himself, and has
been much admired for its singularity: it runs thus:—

“Once the undeserving School-master,


Then the more undeserving Lecturer,
And last of all, the most undeserving Rector of this Parish.
Do not think, speak, or write any thing evil of the dead.”

There is a Market Hall, Town Hall, Free Schools, and Alms Houses.
The latter were erected by Sir John Wynne, in 1610, and received
the name of Jesus Hospital. He endowed them for the reception of
twelve poor men, by ceding the rectorial tithes of Eglwys Vâch,
which are valued at £200 per annum. Within a mile of Llanrwst
there is a spring, which is much esteemed for its healthful qualities.
The water is soft, and a drop of sal-volatile mixed with a cup of it
turns it white as milk, while oil of tartar causes it to assume a pearl
colour. If during the tourist’s visit to Llanrwst there should chance to
fall much rain, I would advise him by all means to view the cataract
called
RHAIADR Y PARC MAWR,
in the valley of Nant Bwlch yr Haiarn, near Gwydir, but otherwise the
minuteness of the stream occasions no extraordinary effect from this
fall, which is about one hundred feet in height. The chief object of
interest, however, in this vicinity, is the celebrated lake, called

LLYN GEIRIONYDD,
upon the borders of which once lived the chief of the Welsh bards,
Taliesin. At the eastern side of the lake is a mound, upon the
summit of which there is a kind of hollow, and in it are the remains
of an ancient edifice, which was probably the residence of Taliesin,
in the reign of Maelgwn Gwynedd, King of Britain. Taliesin when an
infant was found by Prince Elphin by the side of a wear belonging to
his father, Gwyddno Garanhir, Lord of Cantrev Gwaelod. The Prince
fostered the infant, and had it liberally educated; and, at a proper
age, introduced him to the court of his father, Gwyddno. Upon this
occasion, Taliesin presented the king with a poem, the subject of
which was his own history, and another to the prince, which he
called Dyhuddiant Elphin, or the consolation of Elphin, a translation
of which is in Evan’s Specimens of Welsh Poetry. Taliesin had an
opportunity of being serviceable to his benefactor; for once, when
the Prince was imprisoned by his uncle, Maelgwn, in the castle of
Dyganwy, the magic of his muse effected his release. This
celebrated bard was the preceptor of Merddin ab Morvryn, and to
him the lovers of poetry are indebted for five new metres, while the
historian and antiquary are equally benefited by his accurate
description of the manners and customs of the Ancient Britons.
I quitted Llanrwst on the following morning, and took the road to
Conwy; two miles and a half brought me to the pretty village of

TREVRIW,
which presents an animated scene. It is situated upon the banks of
the beautiful river Conwy, which is navigable up to this point for
vessels of fifty tons burthen, that supply the town and
neighbourhood with coals, lime, groceries, &c., &c., and return laden
with slate, supplied from the adjacent mines and quarries. A
number of small boats, called coracles, used by the fishermen, are
seen studding the delightful stream, while the larger vessels, towed
against the wind or sailing before it, present a pleasing picture.
From this place to Conwy there is nothing particularly to attract
attention, until you arrive within a mile of that celebrated town,
when, from the brow of a hill, is obtained a view of the venerable
fortress erected by the first Edward, and the strongly fortified walls,
completely encompassing the town, and strengthened by massive
towers. They are coeval with the castle, and are built in the form of
a Welsh harp, like those of Carnarvon; but here there are no
environs, and the town presents the same appearance as when the
chivalric monarch first fortified it.

CONWY.
The town derives its name from Cyn (chief) and Wy river.
The principal inn is the Castle, which affords every accommodation
the traveller can desire. The Wynnes are celebrated here, as in all
parts of North Wales. In the interior of the town stands Plâs Mawr,
which was erected in 1585, and is still a remarkable structure; its
founder was Robert Wynne, of Gwydir, the uncle of Sir John Wynne,
the historian. Over the grand entrance is inscribed, in Greek
characters “bear and forbear,” over which in Roman characters, “J.
H. S. X. P. S.” (Jesus Hominum Salvator et Populi Salus.) The Old
College is in Castle Street, and the Church is built from the remains
of the ancient Cistercian Abbey, which was founded here by Llewelyn
ab Iorwerth, 1185. It contains a rich baptismal font of gothic
structure, with a tablet to the memory of Nicholas Hookes, of the
town of Conwy, who was the forty-first child of William and Alice
Hookes, and who was himself the father of twenty-seven children.
During my short stay in Conwy, I endeavoured to discover the best
view of the town, which, I think, is from the eastern side of the river,
about midway between the chain bridge and the mansion of
Dyganwy. Nothing can be more interesting. The variety of small
craft, sailing and anchored, before its warlike screen; the castle, with
its towers and turrets, rising in hostile grandeur upon its rocky base;
the bridges, and lovely scenery beyond of purple hills and thriving
villages; and the bright waters sporting with the luxuriant foliage of
its woody margin, create a sensation of delight in the pursuer of
picturesque scenery which he has probably seldom before
experienced.
Another delightful view may be obtained by ascending the rock
which overhangs the lodge of the suspension bridge upon its eastern
side. This very beautiful specimen of art has however lost a great
portion of its attraction since the completion of the more wonderful
structure of the Tubular Bridge, which, like a mighty conqueror, looks
proudly conscious of its own importance, and compels the former to
take a secondary position in the estimation of the visitor. It consists
of only one span of 400 feet, and two abutments of masonry, which
are in perfect harmony with the venerable appearance of the Castle.
But the chief object of interest is the Castle, which surpasses in
picturesque grandeur any building of the kind I ever beheld. I
thought Carnarvon Castle the most beautiful of ruins, but it is not, in
my opinion, to be compared with Conwy. The solidity of its
structure, and its expansive site, resembling the fortresses of Syria
and the Holy Land, give to its exterior all that the most romantic
imagination could desire. Its foundation is a rock of slate, and its
works are impregnable. Nothing but famine could, at the time it was
erected, have had power to subdue it. Its walls are from ten to
twelve feet in thickness, and it had formerly a deep and broad moat,
on the west and north-west sides; which, with the sea washing its
base on the east and south, formed insurmountable barriers to the
assailants.
It was evening when I first entered this noble ruin. The porteress
very ungraciously left me to my meditations after admitting me,
locking the gate after her, and leaving me like a state prisoner in the
royal fortress. I confess I was little pleased with the manners of my
conductress, and the solitary situation in which I was placed, and
sensations arose within me like those which a school boy feels when
passing a churchyard at midnight. The sun had set, and the deep
shadows of eve were darkening into night, as I stood alone in the
court yard, and flitting visions arose before me of those who had
crossed its space in distant by-gone ages—“the plumed troops,” and
courtly dames, and all the glitter of the olden times. As I thus stood
amongst the ruins, a deep drawn sigh, close by my ear, made my
heart leap into my throat, as I turned to discover from whence it
proceeded. But all was solitude around. The huge festoons of ivy,
unruffled by a breath of air hung in funereal grandeur on the walls.
As I passed into what had been the banqueting hall, the darkness
increased. It was a noble apartment, and measured 130 feet in
length, and thirty in breadth, in height twenty. Nine windows looked
southward, up the river, and two into the courtyard. In the recesses
were stone seats, capable of accommodating twelve persons; and,
as I seated myself in one of these, my delusion of other days came
over me. Here sat the first Edward, the hero of Palestine; here was
the monarch besieged, and almost reduced by famine; here Hotspur
and King Richard held a conference; and the latter, putting himself
into the power of Northumberland, was betrayed by him, and sent a
prisoner to the usurper, Bolingbroke.

“Life’s but a walking shadow—a poor player,


That struts and frets his hour upon the stage,
And then is heard no more!”

As I made this apt quotation, another deep and heavy sigh, and a
rustling in the ivy, startled me, and the bird of solitude, the lonely
owl, flapped his heavy wings, and flew past me to a remoter corner
of the ruined hall. I arose, and walked to a small chamber, where
there was an open ornamented casement, and which, as I was
afterwards informed, bears the name of the Queen’s Oriel; from
which there is a pleasant prospect of part of the ruin and scenery
beyond.
I then proceeded to the terrace, at the south-western extremity,
which is on the surface of the rock, and the prospect from this spot,
interesting at all times, is doubly so by moonlight. The suspension
and tubular bridges beneath, the ocean on the left, and this fertile
valley on the right, with the sparkling Conwy meandering through it,
compose a scene of unexampled beauty.
In the year 1290, when Edward was engaged in a dispute with the
King of France, and was determined to revenge himself upon that
potentate, in order to obtain supplies, he made the experiment of
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy