Python Programming For Beginners 2 Books In 1 The Ultimate Stepbystep Guide To Learn Python Programming Quickly With Practical Exercises Mark Reed pdf download
Python Programming For Beginners 2 Books In 1 The Ultimate Stepbystep Guide To Learn Python Programming Quickly With Practical Exercises Mark Reed pdf download
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
https://ebookbell.com/product/programming-for-beginners-2-books-
in-1-linux-for-beginners-sql-for-beginners-matthew-python-11165060
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
https://ebookbell.com/product/python-for-beginners-2-books-
in-1-coding-for-beginners-using-python-python-crash-course-mark-
matthes-11698658
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
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
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
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:
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 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:
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:
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.
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.
[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.
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).
I. Definition of Preservation.
In explanation we remark:
1. From Scripture.
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.
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.
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.
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:
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.
2. Continuous Creation.
[pg 416]
ebookbell.com