0% found this document useful (0 votes)
17 views87 pages

Python Programming For Beginners 2 Books In 1 The Ultimate Stepbystep Guide To Learn Python Programming Quickly With Practical Exercises Mark Reed pdf download

The document is a guide titled 'Python Programming For Beginners 2 Books In 1' by Mark Reed, aimed at teaching Python programming through practical exercises. It covers fundamental concepts such as variables, data types, decision making, and object-oriented programming, structured in a step-by-step format for ease of learning. Additionally, it emphasizes the importance of practice and provides resources for further learning and community support.

Uploaded by

shiplisasoy
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
0% found this document useful (0 votes)
17 views87 pages

Python Programming For Beginners 2 Books In 1 The Ultimate Stepbystep Guide To Learn Python Programming Quickly With Practical Exercises Mark Reed pdf download

The document is a guide titled 'Python Programming For Beginners 2 Books In 1' by Mark Reed, aimed at teaching Python programming through practical exercises. It covers fundamental concepts such as variables, data types, decision making, and object-oriented programming, structured in a step-by-step format for ease of learning. Additionally, it emphasizes the importance of practice and provides resources for further learning and community support.

Uploaded by

shiplisasoy
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/ 87

Python Programming For Beginners 2 Books In 1

The Ultimate Stepbystep Guide To Learn Python


Programming Quickly With Practical Exercises
Mark Reed download
https://ebookbell.com/product/python-programming-for-
beginners-2-books-in-1-the-ultimate-stepbystep-guide-to-learn-
python-programming-quickly-with-practical-exercises-mark-
reed-43835132

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Computer Programming For Beginners And Cybersecurity 4 Manuscripts In


1 The Ultimate Manual To Learn Step By Step How To Professionally Code
And Protect Your Data This Book Includes Python Java C And
Cybersecurity Alan Grid
https://ebookbell.com/product/computer-programming-for-beginners-and-
cybersecurity-4-manuscripts-in-1-the-ultimate-manual-to-learn-step-by-
step-how-to-professionally-code-and-protect-your-data-this-book-
includes-python-java-c-and-cybersecurity-alan-grid-56901338

Python Highway 2 Books In 1 The Fastest Way For Beginners To Learn


Python Programming Data Science And Machine Learning In 3 Days Or Less
Practical Exercises Included Aaron Cox

https://ebookbell.com/product/python-highway-2-books-in-1-the-fastest-
way-for-beginners-to-learn-python-programming-data-science-and-
machine-learning-in-3-days-or-less-practical-exercises-included-aaron-
cox-29341982

Programming For Beginners 2 Books In 1 Linux For Beginners Sql For


Beginners Matthew Python

https://ebookbell.com/product/programming-for-beginners-2-books-
in-1-linux-for-beginners-sql-for-beginners-matthew-python-11165060

Python Programming 2 Books In 1 Python For Data Science Python For


Beginners Del Porter

https://ebookbell.com/product/python-programming-2-books-in-1-python-
for-data-science-python-for-beginners-del-porter-50325654
Python For Beginners 2 Books In 1 Coding For Beginners Using Python
Python Crash Course Mark Matthes

https://ebookbell.com/product/python-for-beginners-2-books-
in-1-coding-for-beginners-using-python-python-crash-course-mark-
matthes-24439920

Python For Beginners 2 Books In 1 Coding For Beginners Using Python


Python Crash Course Mark Matthes

https://ebookbell.com/product/python-for-beginners-2-books-
in-1-coding-for-beginners-using-python-python-crash-course-mark-
matthes-11698658

Python 3 Books In 1 Your Complete Guide To Python Programming With


Python For Beginners Python Data Analysis And Python Machine Learning
Brady Ellison

https://ebookbell.com/product/python-3-books-in-1-your-complete-guide-
to-python-programming-with-python-for-beginners-python-data-analysis-
and-python-machine-learning-brady-ellison-50622032

Python Crash Course For Beginners Learn Python Programming From


Scratch With Handson Exercises In This Beginner Friendly Python Book
Kean

https://ebookbell.com/product/python-crash-course-for-beginners-learn-
python-programming-from-scratch-with-handson-exercises-in-this-
beginner-friendly-python-book-kean-24445806

Python Crash Course For Beginners Learn Python Programming From


Scratch With Handson Exercises In This Beginner Friendly Python Book
Robert Kean Kean

https://ebookbell.com/product/python-crash-course-for-beginners-learn-
python-programming-from-scratch-with-handson-exercises-in-this-
beginner-friendly-python-book-robert-kean-kean-24446032
PYTHON PROGRAMMING FOR
BEGINNERS
2 Books in 1

The Ultimate Step-by-Step Guide To Learn Python Programming


Quickly with Practical Exercises
© Copyright 2022 - All rights reserved.
The content contained within this book may not be reproduced, duplicated or transmitted without direct written permission from
the author or the publisher.
Under no circumstances will any blame or legal responsibility be held against the publisher, or author, for any damages,
reparation, or monetary loss due to the information contained within this book, either directly or indirectly.
Legal Notice:
This book is copyright protected. It is only for personal use. You cannot amend, distribute, sell, use, quote or paraphrase any part,
or the content within this book, without the consent of the author or publisher.
Disclaimer Notice:
Please note the information contained within this document is for educational and entertainment purposes only. All effort has
been executed to present accurate, up to date, reliable, complete information. No warranties of any kind are declared or implied.
Readers acknowledge that the author is not engaged in the rendering of legal, financial, medical or professional advice. The
content within this book has been derived from various sources. Please consult a licensed professional before attempting any
techniques outlined in this book.
By reading this document, the reader agrees that under no circumstances is the author responsible for any losses, direct or
indirect, that are incurred as a result of the use of the information contained within this document, including, but not limited to,
errors, omissions, or inaccuracies.
Table of Contents
BOOK 1
INTRODUCTION
CHAPTER 1: GETTING STARTED
Why Python?
Installing Python
Summary
CHAPTER 2: SOFTWARE DESIGN CYCLE
Solving Problems
Summary
CHAPTER 3: VARIABLES AND DATA TYPES
Python Identifiers
Introduction to Variables
Python and Dynamic Typing
Basic Text Operations
Numbers
Summary
CHAPTER 4: DECISION MAKING IN PYTHON
Conditional Statements
“While” Loops
“For” Loops
Summary
CHAPTER 5: PYTHON DATA STRUCTURES
Sequences
Creating a Basic Game
Summary
CHAPTER 6: FUNCTIONS
Creating Functions
Global Variables
Handling Global Variables
Writing Tic Tac Toe
Summary
CHAPTER 7: INTRODUCTION TO OBJECT-ORIENTED
PROGRAMMING
Classes
Python Inheritance
Polymorphism
Creating Modules
Summary
CHAPTER 8: EXCEPTIONS
When Things Go Haywire
Summary
REFERENCES
BOOK 2
INTRODUCTION
CHAPTER ONE: ALGORITHM AND INFORMATION PROCESSING
Conceptual Introduction
Structure of Modern Computer System
Computer Software
Python Basics
CHAPTER TWO: WORKING WITH PYTHON STRINGS
Python Strings
CHAPTER THREE: DATA SEQUENCES, DICTIONARIES, AND
SETS
Python Sequence
Python Sequence Operations
Python Sequence Functions
Python Collections
Python Boolean
Python Dictionary
CHAPTER FOUR: MATH FUNCTIONS IN PYTHON
Introduction
Python Math Functions
Random Module in Python
Cryptographically Secure Random Generator in Python
CHAPTER FIVE: DATE AND TIME FUNCTIONS
Introduction
Python Time Module
Python Time Using Floating Point Numbers
Working with Python Time Using Data Structures
Converting Python Time from Seconds to an Object
CHAPTER SIX: FILE PROCESSING
What Is a File
Python File Methods
Python Input/Output Operations
Importing Python OS Module
OS Path Module in Python
CHAPTER SEVEN: EXCEPTION HANDLING
Exception
Exception Class Hierarchy
CHAPTER EIGHT: GRAPHICS AND IMAGE PROCESSING
Python Graphics
Turtle Graphics
Image Processing
Graphical User Interface (GUI)
Event Driven Programs
CHAPTER NINE: NETWORK AND CLIENT/SERVER
PROGRAMMING
Socket Programming
Communication Breakdown
CGI Programming
FINAL WORDS
REFERENCES
PYTHON PROGRAMMING
The Ultimate Beginners Guide to Learn
Python Programming Step-by-Step
INTRODUCTION

Python is a powerful language. It is also the easiest language to learn. Python has found
preference in a variety of technology fields like Machine Learning, Deep Learning, and Data
Science. With the rate at which Python is finding preference among many technological fields,
it’s the best time to learn the language.
We want to make it easy to start that journey, no matter what your skills and knowledge are. It
does not matter if you know nothing about programming as a whole.
Each chapter of this book builds on the previous chapters in an easy to understand step-by-step
process. You will learn theory and also practice what you learn. Programming practice is perhaps
the most important step, even when the concepts themselves haven’t quite made sense. It is in the
act of doing that we test our concepts and refine them. Practice is also the only way you become
a programmer. Take breaks when you need to and don’t be afraid to experiment.
CHAPTER 1:

GETTING STARTED

Programming skills are in demand, and there are no signs of this slowing down any time soon.
Whether it is web development, Machine Learning, or the Internet of Things, programming is
everywhere. It used to be that people learned to program in college. Now, programming is taught
to children in school. Soon, most fields will expect some programming knowledge. Coupled with
these changes is the fact that learning programming is becoming freely available, accessible, and
easy. There are entire ecosystems that are driving these changes.
First, we will explore why learning Python is one of the best decisions you could make. We will
then explore the tools you need to get started and set up your environment. If you come from
another programming language like C, C++, or Java, it might be best to skip this chapter or skim
through it.
Why Python?
Python was developed in 1991 by Guido van Rossum, who named the project after his favorite
British comedy Monty Python. To this day, there are several Monty Python "Easter Eggs" within
the official documentation.
Since then, Python has been used to introduce people to programming because of its intuitive
syntax and its ability to create complex programs and process large amounts of data. As a
beginner, you will learn how quickly you can write a basic program and how easily you can scale
your project into something more commercial.
Python is easy to read. It has a human-like English structure that makes it easy to understand and
recall. The number of libraries and premade functions that you can add to your code, saving you
time, has also increased. If you study and do your work, you will be equipped to write a program
that will be easy to read ten years from now. As a programmer, you will know how important
program maintenance is and how easy Python is to administrate compared to other languages.
Let's briefly explore reasons to learn Python with a list. Lists are easy to digest and remember.
1. User-friendly: Programming languages allow communication between humans and
machines. Python is a high-level programming language, which means it is closer to
human language than machine language. Machines do not understand Python on
their own. There is an interpreter that translates Python code into machine language.
2. Powerful: Despite how easy it is to learn, Python is immensely powerful. It is just as
useful as languages like C++, which are low-level programming languages. Places
like Google, Microsoft, IBM, Xerox, and NASA use Python. You can even use
Python to develop games.
3. OOP: Object orientated programming is one the most effective programming
paradigms. It allows programmers to treat problems, actions, and data like real-
world objects represented in code. It is not always best to use it, though, which
makes Python interesting because it is a multi-paradigm language. This means you
can use it for object-orientated programming, functional programming, and others.
It’s flexible. You can benefit from OOP while using techniques belonging to other
paradigms.
4. Computer-friendly: Python doesn't require a lot of processing power or RAM to run.
For instance, developers use Python to create little robots that are operated by $5
computers. It can also run on any operating system. It means you can develop your
application on different operating systems simultaneously, and it will still work the
same. It also means your programs will be able to run on multiple platforms.
5. Language adaptability: You can combine Python with other languages to take
advantage of the different features and advantages. For instance, you can combine it
with C++ to take advantage of the system optimizations and speed it offers in the
backend.
6. It's free: Python is free and open-source. The license allows you to make changes to
the source code in a way that fits your purposes. At this point, this might not be
important to you, but it might be later on.
7. Community: There is a huge Python community online. This is because Python is
open source, has broad applicability, and is easy to learn. So, you will find many
people dedicated to learning or teaching the language. And if you get stuck, you will
find help easily. You will find plenty of collaboration opportunities with other
people on the same path as you as well.
Installing Python
Before we get started, you will need to download and install Python on your system. The
installation procedure is very easy. It is just like the installation of any other program on your
system.
To do so, go to www.python.org and go to the "Downloads" section. Once you get there, pick the
right installer for your system. Make sure you are downloading the latest version as well.
When the installer has downloaded, run it and follow the steps. Do not change anything.
We advise that you install Python and get used to working on it on your system. Online
platforms are good for practice, but not for building things. So, working on your system will help
prepare you better. We also advise that you write the code yourself. If you copy and paste,
experiment with the code. Doing this will help drill the lessons in you.
Using a Text Editor
You can write Python in almost any text editor. There are many to choose from. There are
programs like Notepad, Notepad++, gedit, and others. Some text editors will be better than others
as they provide features that are useful to programmers. For instance, Notepad++ has syntax
highlighting, meaning you will be able to see when you make errors in your code and fix them.
Other editors like Notepad are plain, meaning you will not be able to tell you are making a
mistake until you try running the code. Try picking a text editor that feels natural to you.
Avoid using word processors.
Using an IDE
An IDE, Integrated Development Environment, is a program for writing code that comes with
multiple important features for programming. Many come with graphical interfaces, have
autocomplete, history functions, and are integrated with other debugging tools, can run
commands, deploy, and more. The advantage of using an IDE is convenience. IDE's have many
support features, shortcuts, reminders, and suggestions on how to fix errors.
One of the most popular IDE’s is IDLE. IDLE comes with Python. IDLE can run in two modes:
interactive and script. Interactive is best when you want Python to respond immediately to your
code.
There are many IDE’s out there. Do a little research and pick the one you like best.
Your First Program
Now that you are set up, it's time to write your first program. We will be using IDLE for this
example, but you can use a text editor or an online Python console if you like. We recommend
you use IDLE so you familiarize yourself with IDEs.
Run IDLE in interactive mode. It is easy to find. Just search for it on your system and click on it.
The window you will see is called a Python shell. There will be a blinking cursor, indicating you
can type. Type the following:
print (“Hello World!”)
The following should display on the next line: Hello World!
That's it! You have written your first Python program that displays the message "Hello World!"
As you can see, the code is self-explanatory. It reads like an English command. This is what we
mean by Python is easy to read and understand.
We use the "print()" function to display text written in parentheses with quotation marks. If you
don't have quotation marks, you will get an error. The code will not run. Python is also case
sensitive, so if you were to capitalize the function, it would not work.
In IDLE's interactive mode, you get the output of your program immediately, but the downside is
that you cannot save your project and continue working on it later. To do that, you will need to
use script mode. To do this, click "File" and select "New File." It'll take you to a new window.
Write the code again: print ("Hello World!").
You will notice that when you press Enter, nothing happens. The blinking cursor jumps to the
next line. It's an important feature because it means you can write more instructions. To run the
code, you will have to click "File," then "Save As." Give the file the name you want. You will
see it has the default ".py" extension. The extension is important. If the ".py" is missing, the
interpreter will not read/run the code. Click on "Run" to run the script. You will see that IDLE
will display the results in the interactive window.
In the end, you want to be able to run your program the way you run others. To do this, you will
need an executable file, which you double click, and it runs the code. If you did that now, a
window would open and close. It would look like nothing happened, but that would be
inaccurate. The program has run and terminated itself too fast for you to notice. You will need to
give it instructions that enable it to be open long enough for you to see. Before we get into that,
let's discuss code comments.
Code Comments and Your Program
Open the script we just started and type:
# Hello World!
# This is a demonstration of the “print” function.
When you run the program, you will see that it still displays the same message. The lines you
wrote don't appear. Python ignored them. These lines are called comments; they are always
preceded by #, and they're there to make the code more readable by explaining it. It might look
unnecessary now because you understand the code you are writing. This ceases to be true when
you work with others, or your applications become complex, featuring plenty of variables and
functions. Your code needs to make sense to those who collaborate with you and to yourself
months in the future. Your collaborators can investigate what your code does, but it won't be a
pleasant experience. It is simply inefficient to do things that way.
If you are worried that having more comments will affect your application's performance, don't
worry about it. It won't. Python always ignores comments.
You can make your comments more readable by leaving empty lines. This will not do anything
to your code. Leaving empty lines of space between code blocks and sections is fine; they are
ignored. Go back to your script and add the following line:
input (“\n\n Hit the Enter key to exit!”)
Run it, and it will show a console with the message "Hello World!" and then display "Hit the
Enter Key to exit!" The program will wait for you to press the enter key. It is one way to keep the
program open.
Summary
In this chapter, we have had a brief overview of Python: why it is a good choice, its uses, and its
nature. We then installed Python and wrote some code, explored IDLE, and saw how we could
write programs and run them. We also saw how we could take input and talked about the
importance of comments. Now you are ready to learn!
CHAPTER 2:

SOFTWARE DESIGN CYCLE

Before we begin, it's worth taking a step and learning about the software design cycle. Most
programming books don't discuss this, but it is very important to understand how programs are
designed and made. It is a skill that will become indispensable as you become a programmer.
You should also know that a lot of what we are going to talk about comes up a lot in interviews.
We are going to learn how to identify a problem and fix it using programming. The first stage of
this process has to do with designing the application. You will see how you can break up a
solution into small, actionable steps that solve a problem. You must do so to see the underlying
logic of the steps we take for granted when we fix problems. All the questions we are going to go
through will help you learn the process. It is also mnemonic. In the second part of the chapter,
we will use what we have learned and write code. After that stage, you can test and refine the
program in your capacity.
We will also learn pseudo code, which is also known as a design language. Pseudocode does not
give instructions to the machine and functions as a guide. It's one of those rarely discussed
important programming skills that make you more organized as a developer.
Solving Problems
Programming uses logic to solve problems. You will see this as you learn throughout this book
and other resources. There will be plenty of practice and exercises. Programming is about
solving problems, whether or not you are building an application for work. It's still true when
you create a clone of another program so that you can improve it. Right now, as you read this,
there are likely some problems you have on your mind. Maybe that is why you took this book.
Maybe you have an idea for a game or an app that you would like to share with the world. To
reach those goals, you have to start by asking some questions. Why? Because applications can
get pretty complicated quickly, and you need to know what you are doing, so you don't get lost.
Writing an application without going through this process is as impractical as J.R.R Tolkien
writing The Lord of The Rings without asking himself questions about the culture, history, the
people, and features of the world he is writing about. If you sit down to devise a plan, you will
develop your application much faster because you face fewer problems.
The possibility is, whatever idea you have in mind, there is probably already someone who has
built it. The point is not coming up with something new. Although you can, the point is about
asking yourself if something can be improved. It also makes things easy for you because you
don't have to build anything from scratch. You can find the code that is written and shared and
then optimize it. You might think this is cheating, but it isn't. Most of the tools we use today are
built this way. People built on top of each other's technology to produce something more
beautiful.
Problem Identification
Before coding, you need an idea. To find one quickly, think of something you do often. Choose
something repetitive that you think can be automated by code. Programming is always perfect
for mundane tasks. This is your first problem. The next step is finding a way you can tell the
computer to do this task for you. What instructions - in Python - can the computer follow to fix
this problem? You will also need to get results that show that the computer is doing what you
want it to do. Now let's go through the basic development cycle. The important thing to
remember is that you don't have to be strict about this. You can adapt methods to situations. The
principles are not necessarily a blueprint, so you can be creative with it.
Without thinking about the structure, starting can be difficult, and adding solutions and building
just as you go can lead to an unpleasant experience. Here are the steps you should take:
1. The software’s purpose: Write down the problem and what your program should
do to fix the problem. Because you are new to programming, start with something
simple. A program that prints messages to a user is sufficient. Once you know what
you want to do, you have to think clearly about how you can solve that problem. It's
the brainstorming session. All your ideas don't have to be perfect, but you just need
to think they can work so you'll have an idea of what to do if they don't.
2. The type of user: Next, you have to ask yourself who your target users are. Even If
you are doing a personal project, you should get into the habit of doing so. Ask
yourself who is going to find his program useful. Are they your friends or family?
The general public? How do you anticipate they will interact with the program? Do
they have technical knowledge? What are they going to expect? Once you ask
yourself questions along these lines, you will begin to see a clearer picture of your
program. You will not only know what it should do, but you will also know how it
should do it and how it should look while doing it.
3. The computer system: Then, you need to anticipate the operating system of your
audience. Are they going to be on a Windows, Apple, or Linux computer?
Sometimes you will need to think about the device they are more likely to use. Is it
an Apple tablet or an Android phone? You don't have to be too specific. You need to
have an idea so you can make some provisions for it while you code.
All of these questions will guide the design of your applications. When you answer them at the
beginning of a project, you make the road ahead a lot simpler. If you don't have answers to all
these questions for some reason, it is fine. Some of the answers will come to you as you develop.
Finding the Solution
You now have a basic idea of what you want to build, where it works, who it is for, and how it
must work. It might look like you don't need to carry on any longer thinking about it, but there is
still work to do. Many developers spend a lot of time designing their programs instead of
actually coding. Now you need to ask yourself what your intended target's requirements are.
Then understand their needs. It might involve an agreement between you and the client if you are
building this for someone specific. Once you understand what they want, you need to think about
a solution. The solution might not be obvious, it might be tenuous, and it might get complicated.
Still, if you have written down your process, you will have an easier time adjusting your strategy
and avoiding other issues. You also save yourself a lot of time. There is no point building it only
to discover you have to start over and change it because no one wants it. Here are some things to
think about at this point:
1. Functional requirements: These are the things that your program has to do. Your
program's functional request is what the system has to do to give you the result you want.
For instance, it might need to calculate and print a message or the answer. You cross
these steps off as you code.
2. Results: When the time comes, you will need to test your program to see if it behaves as
it should. When you start, it will be fine running the application to see if it does what you
want it to. As you mature and your applications become more complex, you will need to
find better testing methods. Testing skills help reduce bugs and ensure good performance.
In some cases, you might write some tests that have predetermined answers and see if the
program delivers the answers you expect. You will do this during the development stage,
not after you have finished. It's daunting having to go back over the rest of your
application to figure out why it does not work. It is time-consuming and will be testing.
As a beginner, it will be enough to just run your program and see that it works.
3. Maintenance: When you design a program, you need to think about how it will be used.
Software meant to be used often needs maintenance and support. This means you need to
have plans for changes, updates, and extensions. But if your program is web-based you
need to find ways to update it without taking it down. To make maintenance easy, you
need a program that is easy to read. You’ll find that most developers do this the entire
lifetime of their software. Software needs to adapt with changes and improve to stay
relevant.
All this requires your code to be clear and reusable. It is the simple things which will
make upgrades and maintenance easy to do.
Below is an example of a software design document of the “Hello World” program we built:
Problem: The system needs to display a message to the user.
User: Me
Operating System: Windows / Linux
Interface: Command line terminal
Functional requirements: Print a line of text
Testing: Perform application run test, making sure text is displayed.
Start Designing
Now you are ready to start designing the application. You do so by writing the program in
pseudocode, which you can later translate into code. Pseudocode uses English to describe what a
program should do at each stage to deliver the results we want. Pseudocode explains every line
of code or block of code that we should write, the inputs it should receive, how it acts, and what
it should output. Also, pseudocode allows you to brainstorm. For instance, you start envisioning
the data types, variables, and functions you will need to make the applications work.
There are no specific rules to pseudocode. You can write it any way you want. This only changes
when you work with other programmers because you will have to use the standard chosen by
them. In most contexts, pseudocode follows the syntax and rules of other languages, but the
functions and commands are written in words, not in code. But right now, there is no need to talk
about this as you don't know the language. What you need to understand now is the idea behind
the structure. Here's how you write pseudocode:
# Start program
# Enter two values, X and Y
# Add the values together
# Print sum
# End program
All pseudocode is commented out so that Python ignores it when you run it. If you don't
comment it out, you will get errors. The example above shows us the main design of your
program. It's a description of all the code necessary for the program to achieve its goal. When
you fulfill each one of these, the program will execute.
Improving Your Pseudo Code
Readability remains an important factor when writing pseudocode. Python interprets spaces and
tabs as delimiters, and they are interpreted in different ways, affecting how the app behaves. In
your pseudocode, you can use indentation to indicate which logical statements and actions go
together, but because you commented out the pseudocode, your indentation will not affect the
code. It means you can use whichever kind you feel comfortable with. We will discuss this more
in upcoming chapters.
The first line of a code block is always written without indentation. All the code that belongs to it
is indented into subsections. If you write your pseudocode in a way that resembles Python code,
writing the needed code will be easier. It is why developers advise pseudocode be written this
way. For now, write the pseudocode in a way that makes sense to you. As you learn the syntax,
you will use the Python code structure. Below is the pseudocode following the same principles:
# Perform the first task
# Enter the first value
# Verify whether the value is text
# Print the value
It makes things clear, and the developer knows where to place the code. To create a separation
between this code block and another, you only need to put an empty line between them and begin
the next block without indentation. Now, you can write out your design following these
principles.
Summary
In this chapter, we looked at the software design cycle. We saw how the process of creating a
Python program starts. We learned how to break our problems into objectives and tasks. We also
learned about the role pseudocode plays in the development and Python's pseudocode principles.
This chapter emphasized the importance of planning and outlining your applications to avoid
problems further down the road. Now that you know all this, you are ready to learn the language
itself.
CHAPTER 3:

VARIABLES AND DATA TYPES

Variables are like containers used to store data values so the computer can process them. Without
variables, the processes would not occur because there would be nothing to process. Data values
come in different types: lists, integers, strings, floats, dictionaries, and more. In programming,
many functions rely on the use of variables for their functionality. Variables allow us to write
operations without knowing the exact data the function will manipulate. In fact, computers
convert most kinds of data into variables.
In this chapter, we learn about variables and data types. We will see the fundamental role played
by variables in the development of any program. We will learn with real examples where we will
manipulate strings and perform mathematical operations.
Python Identifiers
When coding, you need to be able to identify a data type by its label. Identifiers are labels/words
that are not commented out or placed within quotation marks. Identifiers label things so the code
is more readable, provided that the names relate to your project. Don't use the same identifiers
for multiple variables or functions; conflicts will occur. So, your identifiers have to be unique to
each variable.
Identifiers allow you to use any word you want except those reserved by Python. Those used by
Python are an integral part of the language, and they are known as keywords. Some of those
keywords are: False, lambda, class, import, global, while, yield, continue. You will come to
understand these later as you learn. Because you won't always remember these keywords, Python
warns you when you use one.
Now, let's learn how to name variables. Variables should always start with an underscore or a
letter. This is not a rule; you can break it, and your programs will run. It is a convention
established by other programmers for a good reason. You can use numbers in your variables as
long as your identifier does not start with one. Also, Python is case sensitive, meaning the
following name variable would not count as the same variable: "newVariable," "NewVariable,"
"NEWVARIABLE," and "_newVariable." Python will see each one as a unique variable,
although semantically, they are the same. It means you should watch your capitalization.
Experienced developers advise you to stick to one style throughout your project. So, if you start
your variables with an uppercase letter, you should follow the same rule in your entire project. It
prevents unnecessary confusion between you and other programmers.
Introduction to Variables
Defining, declaring, or introducing a variable is done in two stages. You will find this is true in
most programming languages. The first stage is an initialization, where a container is created
with the appropriate identifier. The second stage is an assignment where a value is placed in the
container. Both are performed in one operation. Here's an example of it below.
variable = value
You perform the initialization and define assignment through the equals sign.
A block of code that does something is called a statement. The assignment is the statement.
Expressions are code that evaluates to obtain a value/result. Below is a list of assignments, and at
the end, we have an expression that gets the total price.
number = 0
product_weight = 2.1
price_per_kilogram = 10
filename = 'file.txt'
trace = False
sentence = "this is an example"
total_price = product_weight * price_per_kilogram
In programming, you need to be orderly. You should write every statement in a line. In the
example above, we have a list of assignments similar to a grocery list. When writing a program
like this, you need variables that you can use to perform various tasks. For now, understand that
variables come in different types, and these types make up a program. They serve as ingredients
to a recipe. Before we start exploring the types, let's discuss dynamic typing in Python.
Python and Dynamic Typing
In Python, the data type of a variable is automatically inferred, which means you don't have to
specify it when you write code. This is called dynamic typing. Most programming languages
want you to specify whether your variable is a number, list, or dictionary. Dynamic typing allows
us to be less verbose. It allows us to focus more on functionality.
The disadvantage of this is that Python will not warn you when you make certain mistakes, like
adding variables that we shouldn't add together. Python will assume that is what you mean to do.
Beginners face the tricky task of keeping track of their variables: where they are assigned, what
their values are, and how they change. One tip to doing this is declaring your variables at the top
of a code block. This way, they are all at the same place where you can easily inspect them,
allowing you to easily follow your code. The other tip is creating a design document. You can
also create a table where you will declare all your variables. Knowing and keeping track of your
variables will enable you to troubleshoot and maintain your code with ease.
Dynamic typing allows Python to flag variables used with the wrong data type. So if you
perform an operation using both, your operation will be invalid, meaning you receive a
"TypeError," like the one below:
x=2
y = 'text'
trace = False
x + y Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
y - trace Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'bool'
You don't have to understand the code to appreciate what just happened. The x variable is a
number, and the y variable is text. You can't perform calculations with words and numbers. That
is why you get an error. You can add words together to form sentences or even add sentences
together. You can also do mathematical operations with numbers. What you can't do is mix both.
This TypeError is called the Traceback. It tells you to go back and fix something in the logic of
your program. This is an example of many other TypeErrors Python will warn you about. You
need to ensure the operations you want to perform don't break real-world rules about how they
should work.
In the previous example, we have two types of variables: an integer (int) and a string (str).
Strings are text or words, and integers are whole numbers. These are some of Python's data
types. Python provides ways of combining variable types to form more complex data types; we
will explore this later. For now, let's build our programming foundations by practice.
Basic Text Operations
Strings are a popular data type in any programming language. We used one when we made our
"Hello World" program. In that program, we used one print statement. So how do you print
multiple statements? If you use the methods we used without the first program, you just add
another print statement in the next line. There are other ways of doing this, like concatenation.
Concatenation is combining strings into one. You can perform concatenation in several ways.
Below, it is done by separating variables by a comma:
characterClass = “warrior”
characterGender = “male”
print (character gender, characterClass)
The output will be "male warrior."
You can also use the strings themselves instead of the variables that hold them:
print (“male” “warrior”)
The output will be "malewarrior." When using this method, you need to add space, so the output
has space between the words. You can add an extra space at the end of the first word or the
beginning of the second. Here's how you'd do it:
print (“male ” “warrior”)
or like this:
print (“male” “ warrior”)
The output will be "male warrior."However, concatenating strings in this way may cause
problems. Here's one below:
print (characterGender “warrior”)
The result will look something like this:
File "<stdin>", line 1
print (characterGender “warrior”)
^ SyntaxError: invalid syntax
You’ll get an error like the one shown above when you attempt concatenating strings to a
variable in this way. You can only do this with two separate strings.
You can use the plus operator to combine strings. In Python and most programming languages, it
is referred to as a concatenation operator because it combines strings. Here's how it looks:
x = “male”
y = “warrior”
x+y
The output will be "malewarrior."
Python also uses the plus symbol to do mathematical operations. So concatenating strings this
way requires Python to assess the variables first, meaning it works harder. So don't use this
method unnecessarily, as heavy usage will cause the program to demand more from the system.
This is an example of design planning. When you concatenate many strings, try to find other
methods and only use them when you don't see a better alternative.
Quotes
In Python, quotes are important. You might have already seen this as we were going through the
previous examples. Quotes mark characters and words as text. A character is defined as a single
letter, punctuation mark, number, or space. A text is really a string of characters. This is why the
data type is called "string." Python separates text from commands and keywords using quotes
enclosures. So far, we have only used double quotation marks, but Python offers other ways of
doing this.
For instance, you can write the "Hello World" program with single or double-quotes. Here's how
you would do it:
print (“Hello World”)
print (‘Hello World’)
Both of these will produce the same results because Python will not see a difference between the
two. So you will have to choose whichever you prefer. Then how do you test a block of text that
has multiple lines? Python allows you to use block quotes with all their breaks and spaces. Here
is how you would do that:
x = ’’’ this is a long line of text
that requires multiple lines’’’
y =””” this is another long line of strings
but this time, we're using double quotes
because they’re cooler ”””
Both methods will produce the same results, albeit using single or double quotation marks.
Python will read them the same, so it all comes down to what you prefer.
Now, how do you use quotes inside a string? To do this, you have to use different quotation
marks. For example, double quotations for the string and singles quotes for what is quoted. Like
this:
x = “She told me to ‘quote ’like this”
In the example above, we have a quote hierarchy, where double quotes make the string and the
single quotes mark the quoted text. In singles quotes, we have a substring, and in double-quotes,
we have the main string. This is called a nested quote.
Developing a Text Application
We now know a bit about software design, texts, and strings. Let's put all that to practice. We are
going to create a script that generates information about characters in a roleplaying game. We
will name variables for name, gender, race, and description. All of them will be strings. Python
will print the output on the display.
You have the knowledge you need to do all of this. Before you follow the example below, try
developing your own program. Here’s our example:
“““
myFile.py
Problem: Generate information on roleplaying characters
Target audience: Personal / Friends and family
System: Windows / Linux
Interface: Command Line
Functional requirements: Print a character sheet.
Users will input name, gender, race, and description.
Test: Basic execute test.
”””
Name = “”
Gender = “”
Race = “”
Description = “”
# Prompt user for information
Name = input (‘what is your name? ‘)
Gender = input (‘what gender are you? (male / female / not sure): ‘)
Race = input (‘what race are you? (Human / Elf / Orc / Dwarf / Gnome): ‘)
# Output character sheet
cool_line = ‘<__==|#|==--++**\$/**++--==|#|==__>
print("\n", cool_line)
print("\t", Name)
print("\t", Race, Gender)
print("\t", Description)
print(cool_line, "\n")
If you closely, this is the improved version of our Hello World program. We used the same
techniques to create something a bit more complex. First, we have our design document that
provides information about the program. Then we made use of escape sequences in our code: "\t"
for "tab" and "\n" for "newline." Escape sequences are used to format text, making it easier to
read. Whitespaces are one of the typical ways text is formatted, and this is why these two are
used often.
We have a character sheet. Now it is time to come up with an attribute for them. We can do that
through numbers.
Numbers
Numbers are assigned to variables the same way you would assign strings or any data type.
Here’s an example:
x=5
y=2
Python will be able to discern whether it is dealing with a number because of the absence of
quotations or letters. In this instance, an integer. Before we go any further, you need a basic
understanding of how computers work.
Computers store data in binary, a sequence of ones and zeroes. Information is processed by
triggering a vast amount of switches that can either be on or off (1 or 0). There is much more to
learn about this topic, but this is enough information for our purposes.
Let’s look at some numeral types:
1. Integers: In programming and mathematics, whole numbers are called integers.
Integers don't have decimal points, but they can be negative or positive. Integers are
frequently used in operations.
2. Floats: Floats have decimal points. If 2 is an integer, 2.5 is a float. Floats can also
either be negative or positive, and they are assigned to variables the same way
integers are. Python can differentiate between floats and integers automatically.
3. Booleans: They are the most basic type there is, and they represent how computers
work. A Boolean can either be True(1) or False(0). They are often used with logical
operators like "and", "or" and "not." We'll explore this in detail later. Variables are
assigned Boolean values using True and False keywords. They are always
capitalized; otherwise, it will not work.
Basic Operations
You have seen how we assign values to variables. We will now perform some basic operations
like add (+), subtract (-), multiply (*), and divide (/). When you perform operations like these,
you create an expression. Expressions are code that the computer has to work through to get a
result. Expressions can be assigned to variables. Below is an example:
strength = 10 + 2
dexterity = 10 - 4
endurance = 6 * 2
awesomeness = strength + dexterity * endurance
awesomeness
84
You are probably surprised to find the result isn't 216. It isn't, because Python understands math,
so it knows which calculations have precedence over which. The calculation is like this: (10 + 2)
+ ((10 - 4) * (6 * 2)).
This example shows how Python evaluates expressions and decides which sections go with
which. There are many more operations in Python. To fully understand the kind of process that
occurs when these decisions are made, you need to know Python has operator precedence. This
tells Python which operator to pay attention to first. If you don't want Python to use its default,
you can guide it, like below:
awesomeness = (strength + dexterity) * endurance
Now the result is 216 because it has to start with the expression in parentheses.
We have only worked with integers, but the same rules would still apply even if we used floats.
Python also lets you convert numeral types to other numeral types. Here are the most common
ones:
1. Converting any number to an integer: int (x)
2. Converting any number to any float: float (x)
3. Converting any value to a string: str (object)
Note how our focus is now functions instead of operators. The syntax change makes this
obvious. We are manipulating values contained in parentheses. Parentheses are part of the
function. Here are some examples below:
float (12)
12.0
int (10.4)
10
float (int (15.5))
15
Now that we have explored numerical data, let’s create an application to apply everything we
have learned.
Developing a Number Application
One of the most important things to learn before you start building more complex programs is
storing data and comparing values. In other words, you need to learn about conditional
statements and data manipulations of other data types. Before you do so, you need to understand
how to manipulate numerical data types.
Say you want to buy material to make curtains from. You need to know what material you need
and how much of it will be enough. You calculate this based on the size of your windows. Your
functional requirements are the window dimensions, which you will use to determine how much
material you need to buy, and its cost. Then you do some research. As a programmer, you’ll need
to research topics you know little about. In this case, you will investigate how much curtain
material is calculated. Alternatively, you can go to a fabric store and talk to experts. Once the
research is completed, you can make your software design document. Make this a habit. You will
be happy that you did. Here's how it would look:
# Prompt user to input window dimensions measured in centimeters
# Consider a margin of error and add to the dimensions
# Calculate the width of the fabric
# and calculate the length of the material for one curtain
# You need two curtains, double the quantity of material
# and divide by 10 to have the dimensions in meters
# Calculate the price of everything
# Print result
You'll need information about the width of the material and price per meter. A width of 150 cm
costs ten currency units per meter. We would need to get information about the height and width
of the windows. This data will be given to us by the user, meaning we will use the input function.
The function will give us a string, which we will need to convert into a float. Then we can make
our calculations: Here’s how it should look:
# One roll of material is 150 cm in width
# One meter of material costs 10 units of currency
material_width = 150
price_meter = 10
# Prompt the user to input the window measurements in cm
window_height = input( ‘What is the height of your window (cm): ')
window_width = input( ‘What is the width of your window (cm): ')
# Extra material is needed for the hems
# Convert the string to a float
# Without the conversion you will not be able to do the math
curtain_width = float(window_width) * 0.75 + 20
curtain_length = float(window_height) + 15
# Calculate how much material you need
# The calculation is done in widths
# Calculate the total length of material needed for every curtain (stick to cm)
widths_of_cloth = curtain_width / material_width
total_length = curtain_length * widths_of_cloth
# Double the quantity of material because we have two curtains
# Remember to divide by ten in order to calculate meters
total_length = (total_length * 2) / 10
# Calculate the price
price = total_length * price_meter
# Print the result
print("You require", total_length, "meters of cloth for ", price)
Please note that the numbers in this example aren’t accurate because we did not use actual
information about curtains and fabric. Only when we do can we offer the correct result. For our
purposes here, this does not matter; we have learned a lot regardless.
Summary
We learned about variables and assigning values to them. We explored basic data types like
integers, floats, and strings, and performed text and numerical operations. With strings, we
learned how to combine them and convert them. You have enough knowledge to create a basic
program that takes input and outputs results based on those inputs. It's very basic, but these are
the foundations you need to build more complex applications. In the next chapter, we learn how
to teach programs to compare values and make decisions.
CHAPTER 4:

DECISION MAKING IN PYTHON

You have learned how to design applications and manipulate numbers and strings. Now, you
need to learn how to add more functionality to your applications. The more you learn there, the
more complex your designs will become, too, because you will be dealing with complex
problems. Remember to always visit your old applications as you learn. Update and improve
them. This is one of the most typical roles a programmer has to perform. Also, the exercises help
you gauge your progress.
In this chapter, we will learn several methods that will allow us to compare values and make
decisions based on those comparisons. This allows us to create more adaptable programs,
assessing conditions before acting. The ability to choose from several choices based on some
criteria creates complexity. This means your code management skills need to grow with your
skills because you will soon be able to write bigger scripts. In addition, you will learn how to use
loops.
Conditional Statements
The application is not accurate, and it lacks some functionality. Also, there are logical issues in
the code, and we need to fix them. We can improve accuracy through value comparisons because
if we can compare values, we can instruct the application to act differently based on those
comparisons. This is what conditional statements are made for.
Conditional statements add an extra layer of sophistication. In all our examples, we have used a
list of commands to achieve our ends. This will change the conditional statements. An
application will be able to decide between several options the most appropriate actions as
dictated by us. If a condition is met, the problem will act a certain way, and if it is not met, it will
act in another way. Below is the pseudocode of conditional statements:
If condition is true:
Perform these actions;
If this condition is true:
Perform another set of actions;
If this condition is false:
Don’t do anything;
Look at how logical that is. This is an example of how putting our thoughts in pseudocode can
make things very clear. So, make it a habit of yours. Look at how effortlessly the pseudocode
above has demonstrated conditional statements. Conditional statements follow a simple
structure: if x, then y.
There are several ways conditions can be checked, namely by using comparison operators listed
below:
1. Less than: <
2. Less than or equal: <=
3. Greater than: >
4. Greater than or equal: >=
5. Equal: ==
6. Not equal: !=
Operators are used in a variety of ways. For example, you can write the same conditional
statement using a different operator by tweaking the conditional statement's logic. Conditional
statements return true or false answers when they are checked. Like below:
5<9
True
-10 >=10
False
5.5 != 5.5
False
23.56 > 78.2
False
Now, let's assess a conditional expression by assigning a value to a variable first:
myVariable = 10
myVariable == 10
True
As you can see, first, we used a single equals sign to assign a value. Then we used two equal
signs to check if the number stored in myVariable is equal to ten. In other words, two equals
signs are used to compare if values are equal, and a single one assigns values. This expression
will return a Boolean value: True or False. If you use the wrong operator in a conditional
statement, Python will throw an error. In some cases, using the assignment operator over the
comparison operator might not lead to any errors if the assignment performed does not impede a
particular function's role. This is where you might think the program produces strange or wrong
results.
Control Flow
Most applications need to be able to choose which section of code gets executed when something
happens. To do this, you need a control flow statement. Control flow statements evaluate
statements and instructions to decide how they should be executed. So far, you have learned how
to compare values. But this is very useful when you can use the answer returns to direct the
program. In other words, control flow statements are conditional statements because they check
some condition and execute code based on the results.
Conditional statements are created by using the following keywords: if, elif, else. If you come
from another language, note we don’t use the “then” keyword. Now, let’s look at the syntax:
if condition:
#Do this
print “This condition is true”
elif condition != True:
#Do this instead
print “This condition isn’t true”
else:
#Perform a default action if none of the conditions are met
print “The condition isn’t true or false”
The syntax above is easy to understand because we already think this way in our day to day
lives. Let's examine the code.
We have an "if" conditional followed by the expression that is to be checked. The next statement,
elif, means "else if." It will be checked when the first conditional returns false. The else
statement is executed when all other conditions return false. In order words, it is the default; it
can also be used to catch data that doesn't fit what is being assessed. If you don't set the "else" to
catch something unexpected, the program will run regardless. With that said, you don't always
have to use the "elif'' or "else" statements. In some cases, you want a program to carry on
executing or do nothing if a condition is not met. In that case, you will use an "if" statement.
Notice how the code is indented. Python requires you to do this, or you will get an error. Other
programming languages rely on clear delimiters like curly braces. Python doesn't do this. Look at
what happens when you don't:
if x:
print (x)
x+1
indent = “terrible”
File “<stdin>, line 4
indent = “terrible”
^
IndentationError: unindent does not match any outer indentation level
Conditional statements are very important. You will use them a lot in your career. Programs can
use them to verify data, for example. This is called validation. You can write a program that
performs a check on an item. Imagine the program would have a checklist of features an item
needs to fulfill, and it ticks a box for each feature present. You can use them to check if a data set
falls within a specific range. Many of what programs do would be near impossible without
conditionals.
Handling Errors
Many of the scripts we have written have been simple, so they didn't require more than a test run.
But as you build more complex programs, you will need to test your programs in more
sophisticated ways, or you will miss pernicious bugs. Tests also help you determine if your
application is competitive or really does what it seems to do. One way to test your applications is
through a trace table. Trace tables are used to test algorithms or logic errors. They do this by
simulating every step of your application execution, and each statement is evaluated. They look
like this:
Step Statement Notes variable1 variable2 condition1 condition2
1
2
3
To see them in action, let's go back to our curtains application to see where we went wrong. We
will trace variables' values and statements from beginning to end. We will replace trace table
headers with variable names and program conditions. Ideally, you'd perform multiple tests with
different data sets to find many other possibilities. This is because the most critical application
errors occur because of abnormal values, also referred to as critical values. These are values that
the application does not expect, so it has no support for them. This is why you should test
vigorously to expose gaping design flaws.
In our curtain application, the crucial value is the material width, set to 150 cm. Reserving 20 cm
for the hems would mean the largest width we can use for a single curtain is 130 cm. For
anything larger, we would need to stitch width together and so on. We have surmised that the
curtains will need to cover three-quarters of the window's width. This means one width of the
material can cover a maximum of 170 cm. So, for larger windows, we would need to calculate
several widths. We also need to ask ourselves other questions, like if the window is more wide
than deep. It would mean turning the material, providing 15 cm of hem. But then the window's
height has to be less than 125 cm.
Notice how we have to take a lot of conditions into account. The easiest way to verify them
would be to set multiple potential window sizes we can check: 100 by 100, 100 by 200, and so
on. You would also have to calculate results yourself to ensure the program is giving you the
correct results. Let's do this:
1. Let's start with 100 x 100 as the measurement. In this case, we don't have to think
about the width for obvious reasons. Taking the hem into consideration, we'd need
115 x 95 cm of material. Keep in mind that there are two possibilities here. You can
measure by the width or the length. Both will produce different values. If you
measure by length, you will need about 230 cm of material, and if you measure by
width, you'd need 190 cm of material.
2. In the second case, the window is 100 x 200 cm. The curtains need a width of 150
cm. Because this is the width of the material, we should add 20cm for the hem and
another 20 cm for the joining material. This brings our total to 190, meaning the
dimensions of our curtain are 115 x 190 cm. If we measure along the length, we will
need more material than when we measure along the width.
Continue calculating other cases. What we did reveals flaws in our design. When you continue
further, you will realize that flipping the window's dimensions leads to material problems.
Meaning if we measure along the width, it will only be worth it when the width is greater than
the depth. Another condition is a depth of less than 125 cm. It's now up to the programmer to
make crucial design decisions. Should you offer an option to consider material measurements
along the width or keep it lengthwise? We also need to think of accuracy. It would be best to
have the results rounded to the nearest half meter; this is about the final result, not the
calculations.
With that information, let's create a trace table and compare data. Using print functions, it would
look like this:
# add headers to the trace table
print()
print(‘\twidth\theight\twidths\ttoal\tprice’)
# take the hems into account
# Before anything else, you need to convert the string to a number variable
# If you don't, you will get an error due to using mathematical operators on text
curtain_width = (float(window_width) * 0.75) + 20
print('\t', curtain_width)
curtain_length = float(window_height) + 15
print('\t\t', curtain_length)
# Next, you need to figure out the width of material you need
# and calculate the length of cloth needed for every curtain.
# keep all measurements in centimeters
widths = curtain_width / roll_width
print('\t\t\t', widths)
total_length = curtain_length * widths
print('\t\t\t\t', total_length)
# Don’t forget you have two curtains.
# Double the material and divide by ten for result in meters instead of centimeters
total_length = (total_length * 2) / 10
print('\t\t\t\t', total_length)
#Now we need the price in total
price = total_length * price_per_metre
print('\t\t\t\t\t', price)
We’ll leave it here for now. Notice that we used tab to separate variable columns and organize
our trace table. Now that we have this, we can test our design. Here’s how it should look:
Enter the height of the window (cm): 100
Enter the width of the window (cm): 100
width heightwidths total price
95.0
115
0.678571428571
78.0357142857
15.6071428571
78.0357142857
You need 15.6071428571 meters of cloth for 78.0357142857.
After our first test, we noticed a couple of issues. Our conversion to meters wasn't accurate, so
our results are inaccurate. Our output has too many decimals for it to be actionable. We simply
don't need that when dealing with fabric. We can solve this by using the "round" function. The
round functions will take two parameters, the number to reduce decimals and the number of
points we need to reduce to. In this case, two decimals points are enough. Notice that we are
rounding the results, not the calculations themselves. If we try to round the calculations, this
might lead to errors. With these modifications, you should get results like these:
You need 2.92 meters of cloth for 14.59.
Our output display has improved. But if we go and purchase materials using these measurements,
we would end up a bit short. So, we need to know what value to expect to confirm the program is
working well. Without running tests, it would be impossible to tell if our calculations are
accurate and useful. While we may find our output discoursing at this point, comparing our
numbers to expected values can help us figure out where we went wrong. Take some time to go
through the program, run more tests, and figure out what is not working. Some fine-tuning is
needed. How can we implement it?
Adding the Conditionals
To improve our program, we need to add conditional statements. We need the application to be
able to measure the cloth in more than one way. For instance, if the length is smaller than the
material roll's width, we can flip it and use one width of material. What do we do if the curtain
should be longer and wider than the fabric rolls? Say we need a material that is equal to less than
half of the width of the roll. It means we would have to buy a material roll of the same length.
But if we need more than half, we would have to get two more rolls. We just described the kinds
of conditions we need the program to check before it starts making calculations. Let's begin with
the pseudocode. This time we will follow Python syntax:
if curtain width < roll width:
total_length = curtain width
else:
total_length = curtain length
if (curtain width > roll width) and (curtain length > roll width):
if extra material < (roll width / 2):
width +=1
if extra material > (roll width / 2):
width +=2
We now need to calculate how many roll widths there are in certain widths and how much fabric
is needed to determine an entire width. Here's how we would calculate that:
widths = int(curtain_width/roll_width)
additional_material = curtain_width%roll_width
All that was required was an integer function to remove decimals and find out how much extra
material we have using the modulo operator. Now use the knowledge you have gained to
improve your program. Consider repeating this process with different values.
We also use programming to make things more efficient by automating repetitive tasks. One way
of achieving this is through loops. Python allows us to create loops in two ways: through the
"while'' statement or the "for" statement.
“ While” Loops
A "while" loop starts by checking if a condition is true. A statement is executed as long as the
condition is true. So it checks if it is true and executes, then it checks against and executes, and
so on. Here's an example of one:
x=1
while x < 10:
print(x)
x += 1
This loop checks if x is smaller than ten, then it executes code. It checks if x is still smaller and
continues to execute until x is no longer smaller than ten. During the execution, the x value is
incremented by one. Every execution of the code in the loop is called an iteration because it is
repeated several times.
When making "while" loops, you need to be aware of two things. The variable that is checked by
the loop needs to be initialized before the loop is run, and the variable needs to update/change
with every iteration, or else you will have an infinite loop. Infinite loops can be dangerous, and
Python won't tell you when you have created one. If you find a program is stuck in an infinite
loop, you need to terminate it, but this may not work in some circumstances. Infinite loops won't
damage your computer, but they can overcrowd and deplete your system's resources, causing
your system to slow down or reboot. In some rare circumstances, infinite loops are helpful or
desired. But it is best to avoid them as a beginner.
Conditional statements allow you to use any type of variable. Let's consider a program that
calculates the mean of multiple values that the user puts in. What should be the problem that this
application focuses on? The program needed to take into account the user's input because it
doesn't know how many values the user will enter and if they will be positive values. To do this,
we need a loop containing a sentinel value. A sentinel value signals the program to break a loop
when a special value is detected. The program needs to check if the user's input value holds a
value that the script would accept. For example, the loop would iterate as long as there are
positive values and stop when a negative value is detected. Here's an illustration of this below:
offset = 0
total = 0
x=0
while x >= 0:
x = int (input (“Enter a positive value: ”))
total += x
offset += 1
mean = total / offset
print (mean)
Another issue is that we do not know the type of values entered by the user, so we should
automatically convert them into a format we can work with: integers. If a user enters a string, the
program will terminate because of a value error.
Another important aspect of loops is quitting them. The "break" and "continue" methods help us
break out of a loop without causing issues. For instance, you may want to quit a loop when a
certain condition is met without checking other conditions. In that case, you use "break." If you
want to skip a specific iteration, you can use "continue," and the loop will go to the next
iteration.
In some cases, you want the program to verify a condition and not act in any specified manner.
To do this, you use the "pass" keyword. The pass keyword forms a null statement, meaning the
program will skip the loop and move the next code block. Here's an example below:
while True:
my_input = int (new_input (“$? : >> “))
if my_input > 0:
pass
else:
print (“This input is negative”)
Now let’s see an example of using break and continue:
offset = 0
total = 0
while True:
my_input = float (input (“$? : >> “))
if my_input < 0:
if offset == 0:
print (“You need to enter some values!”)
continue
break
total += my_input
offset += 1
print (offset, ‘:’, total)
Python allows you to nest multiple loops and conditional statements. Interestingly you can have
an infinite structure of loop levels, but it is not recommended. When you nest too many loops,
you can become quickly confused when errors occur. Knowing which condition a program
should follow out of many options is hard. So try to keep it simple if you can. Indentation also
makes things hard to read. Each loop and conditional needs to be indented, creating a large
number of intricate blocks. It will look haphazard to any programmer, regardless of skill level.
The general rule is to check your program from other solutions if you need to go over two
looping layers. There is simply no need for such complexity. A simple solution is waiting to be
found. Find it.
“ For” Loops
Loops can also be created with the "for" statement. It has the same structure as the "while" loop,
and in most cases, you can use both interchangeably. But for loops are best used for interaction
over a sequence like lists, dictionaries, and strings. In the first iteration, the first element in the
sequence is retrieved, then the second, and so forth.
To understand "for" loops, you need to understand a few basics about sequences. We will talk
more about sequences in the next chapter, but we have already worked with one: strings: Strings
are just a sequence of characters. There are also lists, which are sequences of elements that are
manipulated. There are also tuples, which are similar to lists but cannot be edited. Below is an
example of a "for" loop:
buildings = [“store”, “house”, “hospital”, “school”]
for x in buildings:
print (x)
Each element in the list will be printed. You can also loop through a string, like this:
for x in “store”:
print (x)
Every character in “store” will be printed individually.
We can break “for” loops just as we would with “while” loops. Below we stop the loop when
“hospital” is found in the list.
buildings = [“store”, “house”, “hospital”, “school”]
for x in buildings:
print (x)
if x == “hospital”:
break
As you can see, the break occurs after “hospital” is printed. Below is another case:
buildings = [“store”, “house”, “hospital”, “school”]
for x in buildings:
if x == “hospital”:
break
print (x)
In this example, the loop breaks before “hospital” is printed. Next is the “continue” keyword that
will skip a specified iteration, in this case “hospital”:
buildings = [“store”, “house”, “hospital”, “school”]
for x in buildings:
if x == “hospital”:
continue
print (x)
As you can see, each element is printed except “hospital”.
Summary
In this chapter, we learned how to make programs more intelligent. Many basic tasks require us
to use logical operators, comparison operators, and assignment operators. We have also learned
how to use loops and conditional statements to introduce decision making.
Improving designing with conditionals and loops is a common feature in programming. Use
these tools to improve your program. We also looked at trace tables and how they help with logic
error detections. Lastly, programming itself is where you design, program, test, and repeat until
you solve a problem.
In the next chapter, we will look at Python data structures and how to manipulate them.
CHAPTER 5:

PYTHON DATA STRUCTURES

Data structures are fundamental to any programming language. We are going to look at working
with lists, tuples, dictionaries, and strings. We are going to create a more complex program to
illustrate their use. We will build a game since games use data structures for character statistics
and inventory. We will also need to calculate combat results and turn them into textual data. We
will build on the knowledge from previous chapters, so don't fret. You will also get good practice
with loops and conditionals.
Our design and development discussion will continue, especially now when working with a more
complex program. A game requires many mathematical operations and textual data, and Python
is great for that. Until now, we have only focused on using code to produce basic outputs. In the
real world, programs are more complex than that. They involve complex structures that demand
a huge number of statements. When you know Python's data structures well, you will be able to
simplify the process. Data structures like tuples, lists, dictionaries, and strings will help in that
regard.
Another Random Document on
Scribd Without Any Related Topics
perish wherein I was born” (3:3). But predestination and election
are not arbitrary. Wisdom has chosen the best possible plan, has
ordained the salvation of all who could wisely have been saved, has
permitted the least evil that it was wise to permit. Rev. 4:11—“Thou
didst create all things, and because of thy will they were, and were
created.” Mason, Faith of the Gospel, 79—“All things were present to
God's mind because of his will, and then, when it pleased him, had
being given to them.” Pfleiderer, Grundriss, 36, advocates a realistic
idealism. Christianity, he says, is not abstract optimism, for it
recognizes the evil of the actual and regards conflict with it as the
task of the world's history; it is not pessimism, for it regards the evil
as not unconquerable, but regards the good as the end and the
power of the world.

Jones, Robert Browning, 109, 311—“Pantheistic optimism asserts


that all things aregood; Christian optimism asserts that all things are
working together for good. Reverie in Asolando: ‘From the first
Power was—I knew. Life has made clear to me That, strive but for
closer view, Love were as plain to see.’ Balaustion's Adventure:
‘Gladness be with thee, Helper of the world! I think this is the
authentic sign and seal Of Godship, that it ever waxes glad, And
more glad, until gladness blossoms, bursts Into a rage to suffer for
mankind And recommence at sorrow.’ Browning endeavored to find
God in man, and still to leave man free. His optimistic faith sought
reconciliation with morality. He abhorred the doctrine that the evils
of the world are due to merely arbitrary sovereignty, and this
doctrine he has satirized in the monologue of Caliban on Setebos:
‘Loving not, hating not, just choosing so.’ Pippa Passes: ‘God's in his
heaven—All's right with the world.’ But how is this consistent with
the guilt of the sinner? Browning does not say. He leaves the
antinomy unsolved, only striving to hold both truths in their fulness.
Love demands distinction between God and man, yet love unites
God and man. Saul: ‘All's love, but all's law.’ Carlyle forms a striking
contrast to Browning. Carlyle was a pessimist. He would renounce
happiness for duty, and as a means to this end would suppress, not
idle speech alone, but thought itself. The battle is fought moreover
in a foreign cause. God's cause is not ours. Duty is a menace, like
the duty of a slave. The moral law is not a beneficent revelation,
reconciling God and man. All is fear, and there is no love.” Carlyle
took Emerson through the London slums at midnight and asked him:
“Do you believe in a devil now?” But Emerson replied: “I am more
and more convinced of the greatness and goodness of the English
people.” On Browning and Carlyle, see A. H. Strong, Great Poets and
their Theology, 373-447.

Henry Ward Beecher, when asked whether life was worth living,
replied that that depended very much upon the liver. Optimism and
pessimism are largely matters of digestion. President Mark Hopkins
asked a bright student if he did not believe this the best possible
system. When the student replied in the negative, the President
asked him how he could improve upon it. He answered: “I would kill
off all the bed-bugs, mosquitoes and fleas, and make oranges and
bananas grow further north.” The lady who was bitten by a mosquito
asked whether it would be proper to speak of the creature as “a
depraved little insect.” She was told that this would be improper,
because depravity always implies a previous state of innocence,
whereas the mosquito has always been as bad as he now is. Dr.
Lyman Beecher, however, seems to have held the contrary view.
When he had captured the mosquito who had bitten him, he crushed
the insect, saying: “There! I'll show you that there is a God in
Israel!” He identified the mosquito with all the corporate evil of the
world. Allen, Religious Progress, 22—“Wordsworth hoped still,
although the French Revolution depressed him; Macaulay, after
reading Ranke's History of the Popes, denied all religious progress.”
On Huxley's account of evil, see Upton, Hibbert Lectures, 265 sq.

Pfleiderer, Philos. Religion, 1:301, 302—“The Greeks of Homer's time


had a naïve and youthful optimism. But they changed from an
optimistic to a pessimistic view. This change resulted from their
increasing contemplation of the moral disorder of the world.” On the
melancholy of the Greeks, see Butcher, Aspects of Greek Genius,
130-165. Butcher holds that the great difference between Greeks
and Hebrews was that the former had no hope or ideal of progress.
A. H. Bradford, Age of Faith, 74-102—“The voluptuous poets are
pessimistic, because sensual pleasure quickly passes, and leaves
lassitude and enervation behind. Pessimism is the basis of Stoicism
also. It is inevitable where there is no faith in God and in a future
life. The life of a seed underground is not inspiring, except in
prospect of sun and flowers and fruit.” Bradley, Appearance and
Reality, xiv, sums up the optimistic view as follows: “The world is the
best of all possible worlds, and everything in it is a necessary evil.”
He should [pg 407]have added that pain is the exception in the
world, and finite free will is the cause of the trouble. Pain is made
the means of developing character, and, when it has accomplished
its purpose, pain will pass away.

Jackson, James Martineau, 390—“All is well, says an American


preacher, for if there is anything that is not well, it is well that it is
not well. It is well that falsity and hate are not well, that malice and
envy and cruelty are not well. What hope for the world or what trust
in God, if they were well?” Live spells Evil, only when we read it the
wrong way. James Russell Lowell, Letters, 2:51—“The more I learn
... the more my confidence in the general good sense and honest
intentions of mankind increases.... The signs of the times cease to
alarm me, and seem as natural as to a mother the teething of her
seventh baby. I take great comfort in God. I think that he is
considerably amused with us sometimes, and that he likes us on the
whole, and would not let us get at the matchbox so carelessly as he
does, unless he knew that the frame of his universe was fireproof.”

Compare with all this the hopeless pessimism of Omar Kháyyám,


Rubáiyát, stanza 99—“Ah Love! could you and I with Him conspire
To grasp this sorry scheme of things entire, Would not we shatter it
to bits—and then Remould it nearer to the heart's desire?” Royce,
Studies of Good and Evil, 14, in discussing the Problem of Job,
suggests the following solution: “When you suffer, your sufferings
are God's sufferings, not his external work, not his external penalty,
not the fruit of his neglect, but identically his own personal woe. In
you God himself suffers, precisely as you do, and has all your
concern in overcoming this grief.” F. H. Johnson, What is Reality,
349, 505—“The Christian ideal is not maintainable, if we assume that
God could as easily develop his creation without conflict....
Happiness is only one of his ends; the evolution of moral character is
another.” A. E. Waffle, Uses of Moral Evil: “(1) It aids development
of holy character by opposition; (2) affords opportunity for
ministering; (3) makes known to us some of the chief attributes of
God; (4) enhances the blessedness of heaven.”

4. To Providence and Redemption.

Christianity is essentially a scheme of supernatural


love and power. It conceives of God as above the
world, as well as in it,—able to manifest himself, and
actually manifesting himself, in ways unknown to
mere nature.

But this absolute sovereignty and transcendence,


which are manifested in providence and redemption,
are inseparable from creatorship. If the world be
eternal, like God, it must be an efflux from the
substance of God and must be absolutely equal with
God. Only a proper doctrine of creation can secure
God's absolute distinctness from the world and his
sovereignty over it.

The logical alternative of creation is therefore a


system of pantheism, in which God is an impersonal
and necessary force. Hence the pantheistic dicta of
Fichte: “The assumption of a creation is the
fundamental error of all false metaphysics and false
theology”; of Hegel: “God evolves the world out of
himself, in order to take it back into himself again in
the Spirit”; and of Strauss: “Trinity and creation,
speculatively viewed, are one and the same,—only
the one is viewed absolutely, the other empirically.”

Sterrett, Studies, 155, 156—“Hegel held that it belongs to God's


nature to create. Creation is God's positing an other which is not an
other. The creation is his, belongs to his being or essence. This
involves the finite as his own self-posited object and self-revelation.
It is necessary for God to create. Love, Hegel says, is only another
expression of the eternally Triune God. Love must create and love
another. But in loving this other, God is only loving himself.” We
have already, in our discussion of the theory of creation from
eternity, shown the insufficiency of creation to satisfy either the love
or the power of God. A proper doctrine of the Trinity renders the
hypothesis of an eternal creation unnecessary and irrational. That
hypothesis is pantheistic in tendency.

[pg 408]
Luthardt, Compendium der Dogmatik, 97—“Dualism might be called
a logical alternative of creation, but for the fact that its notion of two
gods in self-contradictory, and leads to the lowering of the idea of
the Godhead, so that the impersonal god of pantheism takes its
place.” Dorner, System of Doctrine, 2:11—“The world cannot be
necessitated in order to satisfy either want or over-fulness in God....
The doctrine of absolute creation prevents the confounding of God
with the world. The declaration that the Spirit brooded over the
formless elements, and that life was developed under the continuous
operation of God's laws and presence, prevents the separation of
God from the world. Thus pantheism and deism are both avoided.”
See Kant and Spinoza contrasted in Shedd, Dogm. Theol., 1:468,
469. The unusually full treatment of the doctrine of creation in this
chapter is due to a conviction that the doctrine constitutes an
antidote to most of the false philosophy of our time.

5. To the Observance of the Sabbath.

We perceive from this point of view, moreover, the


importance and value of the Sabbath, as
commemorating God's act of creation, and thus
God's personality, sovereignty, and transcendence.

(a) The Sabbath is of perpetual obligation as God's


appointed memorial of his creating activity. The
Sabbath requisition antedates the decalogue and
forms a part of the moral law. Made at the creation,
it applies to man as man, everywhere and always, in
his present state of being.
Gen. 2:3—“And God blessed the seventh day, and hallowed it;
because that in it he rested from all his work which God had created
and made.” Our rest is to be a miniature representation of God's
rest. As God worked six divine days and rested one divine day, so
are we in imitation of him to work six human days and to rest one
human day. In the Old Testament there are indications of an
observance of the Sabbath day before the Mosaic legislation: Gen.
4:3—“And in process of time [lit. “at the end of days”] it came to
pass that Cain brought of the fruit of the ground an offering unto
Jehovah”; Gen. 8:10, 12—Noah twice waited seven days before
sending forth the dove from the ark; Gen. 29:27, 28—“fulfil the
week”; cf. Judges 14:12—“the seven days of the feast”; Ex. 16:5—
double portion of manna promised on the sixth day, that none be
gathered on the Sabbath (cf. verses 20, 30). This division of days
into weeks is best explained by the original institution of the Sabbath
at man's creation. Moses in the fourth commandment therefore
speaks of it as already known and observed: Ex. 20:8—“Remember
the Sabbath day to keep it holy.”

The Sabbath is recognized in Assyrian accounts of the Creation; see


Trans. Soc. Bib. Arch., 5:427, 428; Schrader, Keilinschriften, ed.
1883:18-22. Professor Sayce: “Seven was a sacred number
descended to the Semites from their Accadian predecessors. Seven
by seven had the magic knots to be tied by the witch; seven times
had the body of the sick man to be anointed by the purifying oil. As
the Sabbath of rest fell on each seventh day of the week, so the
planets, like the demon-messengers of Anu, were seven in number,
and the gods of the number seven received a particular honor.” But
now the discovery of a calendar tablet in Mesopotamia shows us the
week of seven days and the Sabbath in full sway in ancient Babylon
long before the days of Moses. In this tablet the seventh, the
fourteenth, the twenty-first and the twenty-eighth days are called
Sabbaths, the very word used by Moses, and following it are the
words: “A day of rest.” The restrictions are quite as rigid in this
tablet as those in the law of Moses. This institution must have gone
back to the Accadian period, before the days of Abraham. In one of
the recent discoveries this day is called “the day of rest for the
heart,” but of the gods, on account of the propitiation offered on
that day, their heart being put at rest. See Jastrow, in Am. Jour.
Theol., April, 1898.

S. S. Times, Jan. 1892, art. by Dr. Jensen of the University of


Strassburg on the Biblical and Babylonian Week: “Subattu in
Babylonia means day of propitiation, implying a religious purpose. A
week of seven days is implied in the Babylonian Flood-Story, the rain
continuing six days and ceasing on the seventh, and another period
of seven days intervening between the cessation of the storm and
the disembarking of Noah, the dove, swallow and raven being sent
out again on the seventh day. Sabbaths are called days of rest for
the heart, days of the completion of labor.” Hutton, Essays, 2:229
—“Because there is in God's mind a spring of eternal rest as well as
of creative energy, we are enjoined to respect the law of rest as well
as the law of labor.” We [pg 409]may question, indeed, whether
this doctrine of God's rest does not of itself refute the theory of
eternal, continuous, and necessary creation.
(b) Neither our Lord nor his apostles abrogated the
Sabbath of the decalogue. The new dispensation
does away with the Mosaic prescriptions as to the
method of keeping the Sabbath, but at the same
time declares its observance to be of divine origin
and to be a necessity of human nature.

Not everything in the Mosaic law is abrogated in Christ. Worship and


reverence, regard for life and purity and property, are binding still.
Christ did not nail to his cross every commandment of the
decalogue. Jesus does not defend himself from the charge of
Sabbath-breaking by saying that the Sabbath is abrogated, but by
asserting the true idea of the Sabbath as fulfilling a fundamental
human need. Mark 2:27—“The Sabbath was made [by God] for
man, and not man for the Sabbath.” The Puritan restrictions are not
essential to the Sabbath, nor do they correspond even with the
methods of later Old Testament observance. The Jewish Sabbath
was more like the New England Thanksgiving than like the New
England Fast-day. Nehemiah 8:12, 18—“And all the people went
their way to eat, and to drink, and to send portions, and to make
great mirth.... And they kept the feast seven days; and on the eighth
day was a solemn assembly, according unto the ordinance”—seems
to include the Sabbath day as a day of gladness.

Origen, in Homily 23 on Numbers (Migne, II:358): “Leaving


therefore the Jewish observances of the Sabbath, let us see what
ought to be for a Christian the observance of the Sabbath. On the
Sabbath day nothing of all the actions of the world ought to be
done.” Christ walks through the cornfield, heals a paralytic, and
dines with a Pharisee, all on the Sabbath day. John Milton, in his
Christian Doctrine, is an extreme anti-sabbatarian, maintaining that
the decalogue was abolished with the Mosaic law. He thinks it
uncertain whether “the Lord's day” was weekly or annual. The
observance of the Sabbath, to his mind, is a matter not of authority,
but of convenience. Archbishop Paley: “In my opinion St. Paul
considered the Sabbath a sort of Jewish ritual, and not obligatory on
Christians. A cessation on that day from labor beyond the time of
attending public worship is not intimated in any part of the New
Testament. The notion that Jesus and his apostles meant to retain
the Jewish Sabbath, only shifting the day from the seventh to the
first, prevails without sufficient reason.”

According to Guizot, Calvin was so pleased with a play to be acted in


Geneva on Sunday, that he not only attended but deferred his
sermon so that his congregation might attend. When John Knox
visited Calvin, he found him playing a game of bowls on Sunday.
Martin Luther said: “Keep the day holy for its use's sake, both to
body and soul. But if anywhere the day is made holy for the mere
day's sake, if any one set up its observance on a Jewish foundation,
then I order you to work on it, to ride on it, to dance on it, to do
anything that shall reprove this encroachment on the Christian spirit
and liberty.” But the most liberal and even radical writers of our time
recognize the economic and patriotic uses of the Sabbath. R. W.
Emerson said that its observance is “the core of our civilization.”
Charles Sumner: “If we would perpetuate our Republic, we must
sanctify it as well as fortify it, and make it at once a temple and a
citadel.” Oliver Wendell Holmes: “He who ordained the Sabbath
loved the poor.” In Pennsylvania they bring up from the mines every
Sunday the mules that have been working the whole week in
darkness,—otherwise they would become blind. So men's spiritual
sight will fail them if they do not weekly come up into God's light.

(c) The Sabbath law binds us to set apart a seventh


portion of our time for rest and worship. It does not
enjoin the simultaneous observance by all the world
of a fixed portion of absolute time, nor is such
observance possible. Christ's example and apostolic
sanction have transferred the Sabbath from the
seventh day to the first, for the reason that this last
is the day of Christ's resurrection, and so the day
when God's spiritual creation became in Christ
complete.

No exact portion of absolute time can be simultaneously observed by


men in different longitudes. The day in Berlin begins six hours before
the day in New York, so that a whole quarter of what is Sunday in
Berlin is still Saturday in New York. Crossing the 180th degree of
longitude from West to East we gain a day, and a seventh-day [pg
410]Sabbatarian who circumnavigated the globe might thus return
to his starting point observing the same Sabbath with his fellow
Christians. A. S. Carman, in the Examiner, Jan. 4, 1894, asserts that
Heb. 4:5-9 alludes to the change of day from the seventh to the
first, in the references to “a Sabbath rest” that “remaineth,” and to
“another day” taking the place of the original promised day of rest.
Teaching of the Twelve Apostles: “On the Lord's Day assemble ye
together, and give thanks, and break bread.”

The change from the seventh day to the first seems to have been
due to the resurrection of Christ upon “the first day of the week”
(Mat. 28:1), to his meeting with the disciples upon that day and
upon the succeeding Sunday (John 20:26), and to the pouring out of
the Spirit upon the Pentecostal Sunday seven weeks after (Acts 2:1
—see Bap. Quar. Rev., 185:229-232). Thus by Christ's own example
and by apostolic sanction the first day became “the Lord's day”
(Rev. 1:10), on which believers met regularly each week with their
Lord (Acts 20:7—“the first day of the week, when we were gathered
together to break bread”) and brought together their benevolent
contributions (1 Cor. 16:1, 2—“Now concerning the collection for the
saints ... Upon the first day of the week let each one of you lay by
him in store, as he may prosper, that no collections be made when I
come”). Eusebius, Com. on Ps. 92 (Migne, V:1191, C): “Wherefore
those things [the Levitical regulations] having been already rejected,
the Logos through the new Covenant transferred and changed the
festival of the Sabbath to the rising of the sun ... the Lord's day ...
holy and spiritual Sabbaths.”

Justin Martyr, First Apology: “On the day called Sunday all who live
in city or country gather together in one place, and the memoirs of
the apostles or the writings of the prophets are read.... Sunday is
the day on which we all hold our common assembly, because it is
the first day on which God made the world and Jesus our Savior on
the same day rose from the dead. For he was crucified on the day
before, that of Saturn (Saturday); and on the day after that of
Saturn, which is the day of the Sun (Sunday), having appeared to
his apostles and disciples he taught them these things which we
have submitted to you for your consideration.” This seems to
intimate that Jesus between his resurrection and ascension gave
command respecting the observance of the first day of the week. He
was “received up” only after “he had given commandment through
the Holy Spirit unto the apostles whom he had chosen” (Acts 1:2).

The Christian Sabbath, then, is the day of Christ's resurrection. The


Jewish Sabbath commemorated only the beginning of the world; the
Christian Sabbath commemorates also the new creation of the world
in Christ, in which God's work in humanity first becomes complete.
C. H. M. on Gen. 2: “If I celebrate the seventh day it marks me as
an earthly man, inasmuch as that day is clearly the rest of earth—
creation-rest; if I intelligently celebrate the first day of the week, I
am marked as a heavenly man, believing in the new creation in
Christ.” (Gal. 4:10, 11—“Ye observe days, and months, and seasons,
and years. I am afraid of you, least by any means I have bestowed
labor upon you in vain”; Col. 2:16,17—“Let no man therefore judge
you in meat, or in drink, or in respect of a feast day or a new moon
or a sabbath day: which are a shadow of the things to come; but the
body is Christ's.”) See George S. Gray, Eight Studies on the Lord's
Day; Hessey, Bampton Lectures on the Sunday; Gilfillan, The
Sabbath; Wood, Sabbath Essays; Bacon, Sabbath Observance;
Hadley, Essays Philological and Critical, 325-345; Hodge, Syst.
Theol., 3: 321-348; Lotz, Quæstiones de Historia Sabbati; Maurice,
Sermons on the Sabbath; Prize Essays on the Sabbath; Crafts, The
Sabbath for Man; A. E. Waffle, The Lord's Day; Alvah Hovey, Studies
in Ethics and Religion, 271-320; Guirey, The Hallowed Day; Gamble,
Sunday and the Sabbath; Driver, art.: Sabbath, in Hastings' Bible
Dictionary; Broadus, Am. Com. on Mat. 12:3. For the seventh-day
view, see T. B. Brown, The Sabbath; J. N. Andrews, History of the
Sabbath. Per contra, see Prof. A. Rauschenbusch, Saturday or
Sunday?
Section II.—Preservation.

I. Definition of Preservation.

Preservation is that continuous agency of God by


which he maintains in existence the things he has
created, together with the properties and powers
with which he has endowed them. As the doctrine of
creation is [pg 411] our attempt to explain the
existence of the universe, so the doctrine of
Preservation is our attempt to explain its
continuance.

In explanation we remark:

(a) Preservation is not creation, for preservation


presupposes creation. That which is preserved must
already exist, and must have come into existence by
the creative act of God.
(b) Preservation is not a mere negation of action, or
a refraining to destroy, on the part of God. It is a
positive agency by which, at every moment, he
sustains the persons and the forces of the universe.

(c) Preservation implies a natural concurrence of God


in all operations of matter and of mind. Though
personal beings exist and God's will is not the sole
force, it is still true that, without his concurrence, no
person or force can continue to exist or to act.

Dorner, System of Doctrine, 2:40-42—“Creation and preservation


cannot be the same thing, for then man would be only the product
of natural forces supervised by God,—whereas, man is above nature
and is inexplicable from nature. Nature is not the whole of the
universe, but only the preliminary basis of it.... The rest of God is
not cessation of activity, but is a new exercise of power.” Nor is God
“the soul of the universe.” This phrase is pantheistic, and implies
that God is the only agent.

It is a wonder that physical life continues. The pumping of blood


through the heart, whether we sleep or wake, requires an
expenditure of energy far beyond our ordinary estimates. The
muscle of the heart never rests except between the beats. All the
blood in the body passes through the heart in each half-minute. The
grip of the heart is greater than that of the fist. The two ventricles of
the heart hold on the average ten ounces or five-eighths of a pound,
and this amount is pumped out at each beat. At 72 per minute, this
is 45 pounds per minute, 2,700 pounds per hour, and 64,800 pounds
or 32 and four tenths tons per day. Encyclopædia Britannica, 11:554
—“The heart does about one-fifth of the whole mechanical work of
the body—a work equivalent to raising its own weight over 13,000
feet an hour. It takes its rest only in short snatches, as it were, its
action as a whole being continuous. It must necessarily be the
earliest sufferer from any improvidence as regards nutrition, mental
emotion being in this respect quite as potential a cause of
constitutional bankruptcy as the most violent muscular exertion.”

Before the days of the guillotine in France, when the criminal to be


executed sat in a chair and was decapitated by one blow of the
sharp sword, an observer declared that the blood spouted up several
feet into the air. Yet this great force is exerted by the heart so
noiselessly that we are for the most part unconscious of it. The
power at work is the power of God, and we call that exercise of
power by the name of preservation. Crane, Religion of To-morrow,
130—“We do not get bread because God instituted certain laws of
growing wheat or of baking dough, he leaving these laws to run of
themselves. But God, personally present in the wheat, makes it
grow, and in the dough turns it into bread. He does not make
gravitation or cohesion, but these are phases of his present action.
Spirit is the reality, matter and law are the modes of its expression.
So in redemption it is not by the working of some perfect plan that
God saves. He is the immanent God, and all of his benefits are but
phases of his person and immediate influence.”
II. Proof of the Doctrine of Preservation.

1. From Scripture.

In a number of Scripture passages, preservation is


expressly distinguished from creation. Though God
rested from his work of creation and established an
order of natural forces, a special and continuous
divine activity is declared to be put forth in the
upholding of the universe and its [pg 412] powers.
This divine activity, moreover, is declared to be the
activity of Christ; as he is the mediating agent in
creation, so he is the mediating agent in
preservation.

Nehemiah 9:6—“Thou art Jehovah, even thou alone; thou hast made
heaven, the heaven of heavens, with all their host, the earth and all
things that are thereon, the seas and all that is in them, and thou
preservest them all”; Job 7:20—“O thou watcher [marg.
“preserver”] of men!”; Ps. 36:6—“thou preservest man and beast”;
104:29, 30—“Thou takest away their breath, they die, And return to
their dust. Thou sendest forth thy Spirit, they are created, And thou
renewest the face of the ground.” See Perowne on Ps. 104—“A
psalm to the God who is in and with nature for good.” Humboldt,
Cosmos, 2:413—“Psalm 104 presents an image of the whole
Cosmos.” Acts 17:28—“in him we live, and move, and have our
being”; Col. 1:17—“in him all things consist”; Heb. 1:2, 3
—“upholding all things by the word of his power.” John 5:17—“My
Father worketh even until now, and I work”—refers most naturally to
preservation, since creation is a work completed; compare Gen. 2:2
—“on the seventh day God finished his work which he had made;
and he rested on the seventh day from all his work which he had
made.” God is the upholder of physical life; see Ps. 66:8, 9—“O
bless our God ... who holdeth our soul in life.” God is also the
upholder of spiritual life; see 1 Tim. 6:13—“I charge thee in the
sight of God who preserveth all things alive” (ζωογονοῦντος τὰ
πάντα)—the great Preserver enables us to persist in our Christian
course. Mat. 4:4—“Man shall not live by bread alone, but by every
word that proceedeth out of the mouth of God”—though originally
referring to physical nourishment is equally true of spiritual
sustentation. In Ps. 104:26—“There go the ships,” Dawson, Mod.
Ideas of Evolution, thinks the reference is not to man's works but to
God's, as the parallelism: “There is leviathan” would indicate, and
that by “ships” are meant “floaters” like the nautilus, which is a
“little ship.” The 104th Psalm is a long hymn to the preserving power
of God, who keeps alive all the creatures of the deep, both small and
great.

2. From Reason.

We may argue the preserving agency of God from


the following considerations:
(a) Matter and mind are not self-existent. Since they
have not the cause of their being in themselves, their
continuance as well as their origin must be due to a
superior power.

Dorner, Glaubenslehre: “Were the world self-existent, it would be


God, not world, and no religion would be possible.... The world has
receptivity for new creations; but these, once introduced, are
subject, like the rest, to the law of preservation”—i. e., are
dependent for their continued existence upon God.

(b) Force implies a will of which it is the direct or


indirect expression. We know of force only through
the exercise of our own wills. Since will is the only
cause of which we have direct knowledge, second
causes in nature may be regarded as only secondary,
regular, and automatic workings of the great first
Cause.

For modern theories identifying force with divine will, see Herschel,
Popular Lectures on Scientific Subjects, 460; Murphy, Scientific
Bases, 13-15, 29-36, 42-52; Duke of Argyll, Reign of Law, 121-127;
Wallace, Natural Selection, 363-371; Bowen, Metaphysics and Ethics,
146-162; Martineau, Essays, 1:63, 265, and Study, 1:244—“Second
causes in nature bear the same relation to the First Cause as the
automatic movement of the muscles in walking bears to the first
decision of the will that initiated the walk.” It is often objected that
we cannot thus identify force with will, because in many cases the
effort of our will is fruitless for the reason that nervous and muscular
force is lacking. But this proves only that force cannot be identified
with human will, not that it cannot be identified with the divine will.
To the divine will no force is lacking; in God will and force are one.

We therefore adopt the view of Maine de Biran, that causation


pertains only to spirit. Porter, Human Intellect, 582-588, objects to
this view as follows: “This implies, first, that the conception of a
material cause is self-contradictory. But the mind recognizes in itself
spiritual energies that are not voluntary; because we derive our
notion of cause from will, it does not follow that the causal relation
always involves will; it [pg 413]would follow that the universe, so
far as it is not intelligent, is impossible. It implies, secondly, that
there is but one agent in the universe, and that the phenomena of
matter and mind are but manifestations of one single force—the
Creator's.” We reply to this reasoning by asserting that no dead
thing can act, and that what we call involuntary spiritual energies
are really unconscious or unremembered activities of the will.

From our present point of view we would also criticize Hodge,


Systematic Theology, 1:596—“Because we get our idea of force from
mind, it does not follow that mind is the only force. That mind is a
cause is no proof that electricity may not be a cause. If matter is
force and nothing but force, then matter is nothing, and the external
world is simply God. In spite of such argument, men will believe that
the external world is a reality—that matter is, and that it is the cause
of the effects we attribute to its agency.” New Englander, Sept.
1883:552—“Man in early time used second causes, i. e., machines,
very little to accomplish his purposes. His usual mode of action was
by the direct use of his hands, or his voice, and he naturally ascribed
to the gods the same method as his own. His own use of second
causes has led man to higher conceptions of the divine action.”
Dorner: “If the world had no independence, it would not reflect God,
nor would creation mean anything.” But this independence is not
absolute. Even man lives, moves and has his being in God (Acts
17:28), and whatever has come into being, whether material or
spiritual, has life only in Christ (John 1:3, 4, marginal reading).

Preservation is God's continuous willing. Bowne, Introd. to Psych.


Theory, 305, speaks of “a kind of wholesale willing.” Augustine: “Dei
voluntas est rerum natura.”Principal Fairbairn: “Nature is spirit.”
Tennyson, The Ancient Sage: “Force is from the heights.” Lord
Gifford, quoted in Max Müller, Anthropological Religion, 392—“The
human soul is neither self-derived nor self-subsisting. It would
vanish if it had not a substance, and its substance is God.” Upton,
Hibbert Lectures, 284, 285—“Matter is simply spirit in its lowest form
of manifestation. The absolute Cause must be that deeper Self which
we find at the heart of our own self-consciousness. By self-
differentiation God creates both matter and mind.”

(c) God's sovereignty requires a belief in his special


preserving agency; since this sovereignty would not
be absolute, if anything occurred or existed
independent of his will.

James Martineau, Seat of Authority, 29, 30—“All cosmic force is


will.... This identification of nature with God's will would be
pantheistic only if we turned the proposition round and identified
God with no more than the life of the universe. But we do not deny
transcendency. Natural forces are God's will, but God's will is more
than they. He is not the equivalent of the All, but its directing Mind.
God is not the rage of the wild beast, nor the sin of man. There are
things and beings objective to him.... He puts his power into that
which is other than himself, and he parts with other use of itby
preëngagement to an end. Yet he is the continuous source and
supply of power to the system.”

Natural forces are generic volitions of God. But human wills, with
their power of alternative, are the product of God's self-limitation,
even more than nature is, for human wills do not always obey the
divine will,—they may even oppose it. Nothing finite is only finite. In
it is the Infinite, not only as immanent, but also as transcendent,
and in the case of sin, as opposing the sinner and as punishing him.
This continuous willing of God has its analogy in our own
subconscious willing. J. M. Whiton, in Am. Jour. Theol., Apl.
1901:320—“Our own will, when we walk, does not put forth a
separate volition for every step, but depends on the automatic action
of the lower nerve-centres, which it both sets in motion and keeps to
their work. So the divine Will does not work in innumerable separate
acts of volition.” A. R. Wallace: “The whole universe is not merely
dependent on, but actually is, the will of higher intelligences or of
one supreme intelligence.... Man's free will is only a larger artery for
the controlling current of the universal Will, whose time-long
evolutionary flow constitutes the self-revelation of the Infinite One.”
This latter statement of Wallace merges the finite will far too
completely in the will of God. It is true of nature and of all holy
beings, but it is untrue of the wicked. These are indeed upheld by
God in their being, but opposed by God in their conduct.
Preservation leaves room for human freedom, responsibility, sin, and
guilt.

All natural forces and all personal beings therefore give testimony to
the will of God which originated them and which continually sustains
them. The physical universe, indeed, is in no sense independent of
God, for its forces are only the constant willing [pg 414]of God,
and its laws are only the habits of God. Only in the free will of
intelligent beings has God disjoined from himself any portion of force
and made it capable of contradicting his holy will. But even in free
agents God does not cease to uphold. The being that sins can
maintain its existence only through the preserving agency of God.
The doctrine of preservation therefore holds a middle ground
between two extremes. It holds that finite personal beings have a
real existence and a relative independence. On the other hand it
holds that these persons retain their being and their powers only as
they are upheld by God.
God is the soul, but not the sum, of things. Christianity holds to
God's transcendence as well as to God's immanence. Immanence
alone is God imprisoned, as transcendence alone is God banished.
Gore, Incarnation, 136 sq.—“Christian theology is the harmony of
pantheism and deism.” It maintains transcendence, and so has all
the good of pantheism without its limitations. It maintains
immanence, and so has all the good of deism without its inability to
show how God could be blessed without creation. Diman, Theistic
Argument, 367—“The dynamical theory of nature as a plastic
organism, pervaded by a system of forces uniting at last in one
supreme Force, is altogether more in harmony with the spirit and
teaching of the Gospel than the mechanical conceptions which
prevailed a century ago, which insisted on viewing nature as an
intricate machine, fashioned by a great Artificer who stood wholly
apart from it.” On the persistency of force, super cuncta, subter
cuncta, see Bib. Sac., Jan. 1881:1-24; Cocker, Theistic Conception of
the World, 172-243, esp. 236. The doctrine of preservation therefore
holds to a God both in nature and beyond nature. According as the
one or the other of these elements is exclusively regarded, we have
the error of Deism, or the error of Continuous Creation—theories
which we now proceed to consider.

III. Theories which virtually deny the doctrine of


Preservation.

1. Deism.
This view represents the universe as a self-sustained
mechanism, from which God withdrew as soon as he
had created it, and which he left to a process of self-
development. It was held in the seventeenth and
eighteenth centuries by the English Herbert, Collins,
Tindal, and Bolingbroke.

Lord Herbert of Cherbury was one of the first who formed deism into
a system. His book De Veritate was published in 1624. He argues
against the probability of God's revealing his will to only a portion of
the earth. This he calls “particular religion.”Yet he sought, and
according to his own account he received, a revelation from heaven
to encourage the publication of his work in disproof of revelation. He
“asked for a sign,” and was answered by a “loud though gentle
noise from the heavens.” He had the vanity to think his book of such
importance to the cause of truth as to extort a declaration of the
divine will, when the interests of half mankind could not secure any
revelation at all; what God would not do for a nation, he would do
for an individual. See Leslie and Leland, Method with the Deists.
Deism is the exaggeration of the truth of God's transcendence. See
Christlieb, Modern Doubt and Christian Belief, 190-209. Melanchthon
illustrates by the shipbuilder: “Ut faber discedit a navi exstructa et
relinquit eam nautis.” God is the maker, not the keeper, of the watch.
In Sartor Resartus, Carlyle makes Teufelsdröckh speak of “An
absentee God, sitting idle ever since the first Sabbath at the outside
of the universe, and seeing it go.” Blunt, Dict. Doct. and Hist.
Theology, art.: Deism.
“Deism emphasized the inviolability of natural law, and held to a
mechanical view of the world” (Ten Broeke). Its God is a sort of
Hindu Brahma, “as idle as a painted ship upon a painted ocean”—
mere being, without content or movement. Bruce, Apologetics, 115-
131—“God made the world so good at the first that the best he can
do is to let it alone. Prayer is inadmissible. Deism implies a Pelagian
view of human nature. Death redeems us by separating us from the
body. There is natural immortality, but no resurrection. Lord Herbert
of Cherbury, the brother of the poet George Herbert of Bemerton,
represents the rise of Deism; Lord Bolingbroke its decline. Blount
assailed the divine Person of the founder of the faith; Collins its
foundation in prophecy; Woolston its miraculous attestation; Toland
its canonical literature. Tindal took more general ground, and sought
to show that a special revelation was unnecessary, impossible,
unverifiable, the religion of nature being sufficient and superior to all
religions of positive institution.”

[pg 415]
We object to this view that:

(a) It rests upon a false analogy.—Man is able to


construct a self-moving watch only because he
employs preëxisting forces, such as gravity, elasticity,
cohesion. But in a theory which likens the universe to
a machine, these forces are the very things to be
accounted for.
Deism regards the universe as a “perpetual motion.” Modern views
of the dissipation of energy have served to discredit it. Will is the
only explanation of the forces in nature. But according to deism, God
builds a house, shuts himself out, locks the door, and then ties his
own hands in order to make sure of never using the key. John Caird,
Fund. Ideas of Christianity, 114-138—“A made mind, a spiritual
nature created by an external omnipotence, is an impossible and
self-contradictory notion.... The human contriver or artist deals with
materials prepared to his hand. Deism reduces God to a finite
anthropomorphic personality, as pantheism annuls the finite world or
absorbs it in the Infinite.” Hence Spinoza, the pantheist, was the
great antagonist of 16th century deism. See Woods, Works, 2:40.

(b) It is a system of anthropomorphism, while it


professes to exclude anthropomorphism.—Because
the upholding of all things would involve a
multiplicity of minute cares if man were the agent, it
conceives of the upholding of the universe as
involving such burdens in the case of God. Thus it
saves the dignity of God by virtually denying his
omnipresence, omniscience, and omnipotence.

The infinity of God turns into sources of delight all that would seem
care to man. To God's inexhaustible fulness of life there are no
burdens involved in the upholding of the universe he has created.
Since God, moreover, is a perpetual observer, we may alter the
poet's verse and say: “There's not a flower that's born to blush
unseen And waste its sweetness on the desert air.” God does not
expose his children as soon as they are born. They are not only his
offspring; they also live, move and have their being in him, and are
partakers of his divine nature. Gordon, Christ of To-day, 200—“The
worst person in all history is something to God, if he be nothing to
the world.”See Chalmers, Astronomical Discourses, in Works, 7:68.
Kurtz, The Bible and Astronomy, in Introd. to History of Old
Covenant, lxxxii-xcviii.

(c) It cannot be maintained without denying all


providential interference, in the history of creation
and the subsequent history of the world.—But the
introduction of life, the creation of man, incarnation,
regeneration, the communion of intelligent creatures
with a present God, and interpositions of God in
secular history, are matters of fact.

Deism therefore continually tends to atheism. Upton, Hibbert


Lectures, 287—“The defect of deism is that, on the human side, it
treats all men as isolated individuals, forgetful of the immanent
divine nature which interrelates them and in a measure unifies them;
and that, on the divine side, it separates men from God and makes
the relation between them a purely external one.” Ruskin: “The
divine mind is as visible in its full energy of operation on every lowly
bank and mouldering stone as in the lifting of the pillars of heaven
and settling the foundations of the earth; and to the rightly
perceiving mind there is the same majesty, the same power, the
same unity, and the same perfection manifested in the casting of the
clay as in the scattering of the cloud, in the mouldering of dust as in
the kindling of the day-star.” See Pearson, Infidelity, 87; Hanne, Idee
der absoluten Persönlichkeit, 76.

2. Continuous Creation.

This view regards the universe as from moment to


moment the result of a new creation. It was held by
the New England theologians Edwards, Hopkins, and
Emmons, and more recently in Germany by Rothe.

[pg 416]

Edwards, Works, 2:486-490, quotes and defends Dr. Taylor's


utterance: “God is the original of all being, and the only cause of all
natural effects.” Edwards himself says: “God's upholding created
substance, or causing its existence in each successive moment, is
altogether equivalent to an immediate production out of nothing at
each moment.”He argues that the past existence of a thing cannot
be the cause of its present existence, because a thing cannot act at
a time and place where it is not. “This is equivalent to saying that
God cannot produce an effect which shall last for one moment
beyond the direct exercise of his creative power. What man can do,
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!

ebookbell.com

You might also like