PYTHON PROGRAMMING For Beginners The Easy and Complete Step-By-Step BooxRack
PYTHON PROGRAMMING For Beginners The Easy and Complete Step-By-Step BooxRack
INTRODUCTION
CHAPTER 14: MISTAKES YOU CAN MAKE WHEN PROGRAMMING WITH PYTHON
AND HOW TO AVOID THEM
MISTAKES THAT ARE PRAGMATIC
Python code and interactive prompt
Print statements
Automatic extensions with Windows
File icon on Windows
Imports
Blank lines
MISTAKES WITH CODE
Colons
Variable initialization
Column 1
Indentions
Parentheses and function calls
Paths and extensions
C language with Python
MISTAKES WITH PROGRAMMING
Module search paths
Specific types
Immutable types
While and range in loops
Results from functions
Conversions
Cyclic data structures
CHAPTER 20: GET TO KNOW HOW TO PROGRAM-A CLOSER LOOK AT THE TKINTER
TUTORIAL
BENEFITS OF TKINTER IN STUDYING PYTHON LANGUAGE
ADVANTAGES OF TKINTER
DISADVANTAGES OF TKINTER
CREATING AN EMPTY WINDOW
WIDGETS
Label Widget
Frame Widget
Button Widget
Entry Widget
Radio Button Widget
Check Button Widget
Canvas Widget
Scale Widget
CONCLUSION
Introduction
Python programming sounds scary but it really isn’t. The hardest part is in
choosing which of the languages you want to learn because there are so many
to choose from. Python is one of the easiest of all of computer programming
languages; indeed, pretty much everything you need is right there, at your
disposal. All you need to do is learn how to use what the program gives you
to write programs.
Python is simple; much simpler than many of the other languages and once
you have learned it you will find it much easier to move on to more advanced
Python or to another language altogether. Python provides you with the
framework and libraries that you need to do just about anything that you want
to do. If that weren’t enough, Python also has a very large community full of
people who just want to help you and put you in the right place.
There are a lot of great coding languages out there that you can work with,
but none of them can compare to working with Python. Make sure that you
read through this guidebook carefully so you can learn how to write some of
your own codes with this amazing language today.
Chapter 1: Introduction to Python
What is Python
Python is a high level language and one of the most readable languages in
this category. It is designed to be learned and used easily. Python programs
use nearly regular English statements and simple syntax.
As a beginner and someone who has never done anything with coding in the
past, Python is one of the best coding languages to work with. Python has
long been considered a beginner's language because it is so easy to learn and
you will be able to understand it right from the beginning. This is just one of
the many reasons why you should choose to work with Python. You will also
like there is a large active community devoted to this programming language
and what’s good is that it’s open source so you can get started without
literally having to pay anything. This language will also work on any
operating system so it won’t matter which computer you want to use the
language on.
Despite being the coding language that beginners like to work with, this
doesn't mean that there aren't a lot of advantages that come with working with
this language. Python on its own is capable of writing great codes in the
process, and you can also combine it with a few other languages so that you
can create as many strings of code that you like. Now, let's take some time to
look at Python and all the things that you need to know to get started on using
this coding language.
Python uses short and simple codes which makes programming work faster
and more efficient. It is loaded with built-in features and modules and has
one of the most extensive libraries.
Python is an interactive language. You can use the Python prompt to type
codes and produce instant feedback from the interpreter.
Python is a powerful and versatile language. You can use it to develop office
productivity tools that will automate repetitive tasks or simplify complicated
jobs. You can also use it to write large web applications, powerful games,
and GUIs.
Python easily integrates with other languages such as Java, C, C++, ActiveX,
and COM. Its support for automatic garbage collection makes it a memory-
friendly programming language.
Although it derived many of its syntax and structure from C, Python differs
significantly from C in two major aspects: the use of whitespaces or
indentation to structure blocks of codes and dynamic typing. While C uses
curly braces {} and a semi-colon to mark a group of statements, Python uses
indentation to indicate code blocks. In C, a variable is always declared and
tied to a specific data type before it can be used. In Python, a variable is not
declared and can be reassigned anytime.
For windows users, you can use this link to find your preferred version:
https://www.python.org/downloads/
https://www.python.org/downloads/mac-osx/
Top companies like Google, Disney, Nokia, IBM, and Yahoo! use Python.
Python programmers and developers are among the highest-paid computer
professionals in the world today and among the most in-demand. Hence,
learning Python will greatly enhance your job prospects now and in the
coming years.
Python can wrap itself around just about any computing task you can throw at
it. With a vast jungle of programming languages available today, why should
you choose Python?
For advanced users, the Python source code is also available from that
location which allows for the modification and/or custom compiling of
Python to suit specific applications. Aside from having Python installed, all
that is needed to start programming is a text editor. The process can be
streamlined and made easier with a Python friendly IDE, but it is not
required.
Next, Python is incredibly easy to use and extremely powerful. While Python
code can be compiled and packaged into an executable, it is typically used as
an interpreted scripting language. As such, housekeeping chores such as
memory management are handled by the interpreter, freeing the programmer
to focus on function.
Python also uses very simple 'readable' syntax which is similar in format to
other languages. Someone new to programming can be creating simple
programs within a few minutes. Those with programming experience in other
modern languages (like C/C++) will find the syntax familiar, facilitating a
quick jump into more complex tasks.
Free
Another benefit of going with Python is that it is free to use. There are some
computer coding languages that you would have to pay for so you can use
them and this can be quite expensive especially if you want to learn how to
use more than one of them.
Fast
Even though this language is easy enough for any beginner to learn, Python is
still considered one of the high-level languages that you can learn about. This
means that when you make a program and generate your own codes by using
Python, you will see that the execution is nice and quick. There are some
coding languages that are harder to work with or can’t go as fast as you want
them to, but this is a problem you won’t have when using Python.
You can work with the Python language no matter which platform you would
like to use it on. Linux is the operating system that a lot of people will choose
to go with but you can still work with Python even if you are on a Windows
or Mac computer. This is great news because it means that you can actually
use Python without having to make any major changes to your current setup.
Once you start to get familiar with Python, you will notice that it comes with
a large library. This is good news for beginners because the library is what
contains all the functions, codes and other things that you need to make the
language work for you. This library will help make sure that you can do some
useful things when trying to make your own code.
A large community
Whether you have worked with coding language in the past or not, it is nice
to know that there is a large community of Python users that will help you out
if you ever get stuck. Any time that you need some ideas like a new project or
if you just have a question, or if you want to learn something new, there is a
library of information to provide you with the information that you need to
help you get started.
There are a ton of people, both beginners, and experts, who use the Python
language over other programming languages because unlike those, it is
simple and easy to work with. Whether or not you have worked with a coding
language in the past, you will find that Python may just be the answer that
you’ve been looking for.
Basically, Python is the go-to programming language for just about anything
you want to do. It’s a small language, it is very close to the English language
and it contains hundreds of libraries for you to choose from. Apart from all
that, why would you use Python? Here are three reasons:
Libraries
Python has been in existence for almost 27 years and in that time an awful lot
of code has been written. Because it is open source, this code is made
available to every programmer to use. You can install it on your own system
and use it in your projects or you can modify it for your own use. All of this
code is installed in libraries and there are libraries that cover just about
anything you want, from manipulating an image right up to the automating a
server.
Community
Python has one of the largest programming communities and there are groups
just about everywhere. Major conferences are held regularly on virtually
every continent in the world, with the exception of Antarctica. There are
workshops, online and offline and there are plenty of forums where you can
go for help and to join in with other programmers. When you begin to learn
Python, it is advisable that you join a couple of these forums and become
active in them. That way, when you need help, you’ll get it.
Chapter 2: A Brief History of Programming
Since the dawn of computers, we humans have been tasked to make them
useful. To accomplish that, a broad range of programming tools have been
developed over the years to turn our instructions into a machine readable
code that a computer can execute.
Programming with these tools was far easier than using assembly language,
allowing more complex programs to be written by a larger number of people.
In the 1970's, Pascal and C evolved into the major development tools as they
provided relatively simple, structured programming languages that compiled
efficient code.
Structured languages did not use the goto statement common in earlier
languages like basic. Instead, program flow relied on conditional statements,
loops, and functions or procedures. This feature allowed programs to be
developed with standalone reusable routines, which greatly lowered
development and debugging time.
The next big advancement came in the 1980’s when object oriented
languages, starting with C++, began to predominate.
While these tools offer immense power and capabilities to the programmer,
many of them are still relatively difficult to use and because they are
compiled languages, they tend to be machine specific in their
implementation.
As such, they are great for systems level programming tasks (like
programming an operating system), or developing highly complex
commercial applications that need to be compact with fast execution.
However, their nuances and complexity can make developing simple
applications by an average user daunting.
They also tend to be very structurally strict and rely on the programmer to
handle all the housekeeping chores like memory management.
As computer use and popularity grew beyond the 1980's, the need for simple,
easy to use, cross platform programming languages grew. Out of that need,
Python was created.
Like all programming languages, Python has its set of rules and structures
that programs must follow.
Where possible I will also guide you on where to get additional information
so you can continue expanding upon what you learn here in the future.
Chapter 3: The Difference Between Python 2 and 3
There are many coding languages out there that you can use. Some of them
are pretty basic to learn, and some have a bit more power behind them. Many
people have at least interacted with Java or JavaScript when they go to a
website, especially one that has a pop-up of any kind. If you have worked
with a Windows computer, you may have experimented with some of the
languages that are found on there. Or maybe you are coming to this
guidebook as a completely new beginner to all things coding and you want to
know where to start.
The options can seem pretty overwhelming when you start. All the many
languages are going to follow their own rules on how to write the codes and
what you are able to do with the code as well. But if you are looking for a
coding language that has a ton of power for a beginner, one that can easily
stop and avoid others, one that offers you many choices and allows you to
implement it with many other coding languages at the same time, then Python
is the right choice for you.
Beginners and more advanced coders alike love working with the Python
coding language. There are many benefits, but the primary part is that it was
developed with the beginner in mind. In the last few decades, there has really
been a push in much of the world of technology to start making it easier to
get more people to come in and join the fun. They see that there are benefits
to inviting more people. More games can be created, more bugs fixed in
programs, and just more innovation compared to the times when only a few
people even had any idea how to code in the first place.
In this guidebook, we are going to spend some time exploring the world of
Python, looking at what this coding language is all about, and helping you to
write some of your own codes by the time that you are done. Don’t be scared
about this coding language. While there are a lot of people who may be
intimidated when they hear about coding because they worry it will be too
hard, you will quickly see a ton of examples of how Python works. Then you
will be ready to dive right in and see what your creativity and hard work can
do.
A common difference between the two is the print function. Python 2 didn’t
really use a lot of parentheses, that is, print () in this case. This change may
not seem like such a big deal, but it makes all the difference. The print
statements in Python 2 have been replaced with print (). When you write a
code that you want to print without the parenthesis in Python 2, the code goes
on to be readable and is translated. However, if you do this in Python 3, it
will report a syntax error. Python 2 does not have much of a problem when it
comes to this. The syntax in the two versions differs.
But what is syntax? Syntax is the set of rules used during the coding process.
One other difference is the integer division. Python 2 tends to round off the
division to the nearest number, while Python 3 tends to be more accurate
compared to the version it surpassed. If you are planning on porting Python 3
code into Python 2, you should be careful. A syntax error will not appear if
you make a mistake. Hence, you would want to be very careful. For example,
instead of using 3/2 in your script - that is if you are using Python 3, you
should consider implementing float 3/2.0 0r (3) /2.
Python 2 and 3 differ in how they represent their characters. Python 2 can use
both ASCII and Unicode strings. Python 3, on the other hand, uses Unicode
strings. In ASCII, the byte string is used which is represented as “str”. The
“Unicode” implies the Unicode string type. The “str” and “Unicode” are
subclasses of a common base class. If you want to create a string in Python 2,
you can write str(). If you want to create Unicode, it's the same - you will
write Unicode(). Python 3 has only one string which is named str – it is a
Unicode. The sequence of bytes is represented as a byte. There are instances
whereby bytes allows some systems that use ASCII. However, this is not true
in all cases.
Python 2 and 3 also differ in ranges. If you have been wondering what range
and xrange are, you are about to find out. If it is something you have heard
about it, but you would like to know more, you are going to get enlightened
on the matter through this brief explanation.
Python has two functions which are range and xrange. One crucial aspect to
keep in mind is that range and xrange function the same way, although they
are a bit different. The range function was used in Python 3, while xrange
was used in Python 2. However, the range function in Python 3 was removed
and it gave way to xrange, which is used in Python 2 since it has been found
to be faster. So, what is the difference between the range and xrange?
Range and xrange will provide you with a way to be able to come up with a
list of integers you can use in any way you want to use them. However,
xrange will return an xrange object, while range will return a Python list of
objects.
Now, if you are going to program your software using Python you will need
to begin your own graphical user interface better known as GUI for all your
codes. The built-in GUI for Python is known as Tkinter – it comes installed
in your Python software. After creating a GUI, it is time to make the next
move – build your own calculator.
After building your own calculator, you have to create a GUI for your
calculator and then move on to enter the main code. Still, on the main code,
you will need to submit a button command. All this may sound new or
overwhelming, but this is just a brief description of the programming process
while using the Python program. After entering the code, you will need to
process the input received from the user from a string into integers.
The next step is packaging and distribution. Any application which you
develop using Python will be in a Python package. However, if you use
packaging and distribution, you will be able to make your software
independent. Hence, you will be able to install it on any system.
Pynsist, on the other hand, creates a window installer which installs the
version of Python that you specify, hence installing your application. Pynsist
works differently as compared to freezing applications. It does not try to
freeze your application into an exe. Instead, it makes shortcuts which launch
the py files. Why is this relevant? Well, because of this, certain kind of bugs
are avoided.
The final release of Python 2.x came out in 2010 while version 3.0 was
released in 2008. Since then, there have been multiple stable releases
including version 3.3 that came out in 2012, version 3.4 in 2014, version 3.5
in 2015, and the current version 3.6 which was released in 2016.
In the recent past, there has been a debate within the Python community over
which Python version a beginner should learn. While it is no brainer that
Python 3 is the winner, there are good reasons why it pays to understand the
differences between it and its predecessor.
Python 2 is so entrenched in software used today that even the latest releases
of Linux still come with this version installed. Therefore, even when you
learn to code in Python 3, you will most likely encounter software that was
developed in Python 2.
Another important point to note is that many libraries in use today were
developed for Python 2. Some of the libraries you will need to use may not
be forward-compatible. Pygame, for instance, is a popular library for game
development with a lot of exercise code and tutorials available online. To use
this library with such code, you may need to switch to Python 2 then back to
Python 3.6+ to apply what you learn.
There are also some variations of each of the versions that you can choose as
well. Since the Python code is completely open sourced, it is possible for all
developers to come in and make changes and updates as well. These
developers can provide a lot of different options when it comes to the features
and more on the system. If you like one of these versions more than the other,
still consider looking at the different versions to make sure you get the right
one.
How is Python 3 Better Than Python 2?
If you already have Python 2 and like using it, it may be time to learn how to
adjust to Python 3. These two versions are pretty similar so you will find that
there are a lot of similarities between the two.
Setting up Python in Windows
Now it is time to take the Python code and install it in the different operating
systems that you may want to use. First up is to work with the Windows
system. To install Python on your Windows machine, you will need to have
an internet connection to download the installation files and about 100 MB of
disk space.
You will
need to set
up a
launcher for
all users. Be
sure that the option to install the launcher is checked. The option to add
Python to PATH should also be checked. Click on “Install Now” to begin
the setup.
The Python Installer typically checks your computer for any previous
versions of Python that may already be installed. If you see the “Upgrade
Now” message instead of “Install Now” and no checkboxes at the bottom of
the window, it means that an older version is installed and can be upgraded.
Once you see the “Setup was successful” message, click the close button to
exit setup.
Step 4: Verify Python Installation
It is not uncommon to see the “Setup was successful” message even when
the installation encountered problems. To verify that Python 3 is installed on
your Windows computer, follow these steps:
3. If the installation was actually successful, the first line of the text inside the
command prompt should be “Python” and the version number, in this case
3.7.1.
When you type the code print Type exit() and press Enter to terminate Python
and close the command prompt window. Python is now installed on your
Windows computer and you are ready to begin programming.
You can verify the installation by running this code on your terminal:
$ brew doctor
If Homebrew is properly installed, the command should return the message
“Your system is ready to brew.”
Step 2: Install Xcode
You will need to install GCC before you can install Python 3 on your Mac.
GCC comes with the Command Line Tools Xcode, or can be installed via the
OSX-GCC-Installer. If Xcode is already installed on your system, you can
skip this step.
Open your terminal or emulator and type this command to install Xcode:
$ xcode-select --install
Several confirmation commands may pop up because Xcode is a big
program. Accept through them all and be patient as all the package files are
downloaded, installed, and configured.
$ python3 --version
Python 3.7.1
To run Python 3 from the terminal, use python3 command. It should display
the version of Python as well as a few other details. Terminate the Python 3
shell using exit() or by pressing Ctrl+D.
You will notice that when you use the python command on the terminal, it
will run the Python 2 shell.
Installing Python on Linux
Just like Mac OS X, every version of Linux comes with Python out-of-the-
box. New versions of Ubuntu and Debian Linux come with both Python 2
and 3 pre-installed.
The first thing you should do is to make sure that your version of Advanced
Packaging Tool is up to date. Open the terminal and use these command:
$ python3
Since Mint and Ubuntu use the same package management system, you can
install the latest version of Python using this command:
$ idle
Setting Up Environment Variables
In Mac OS, PATH details are handled by the package installer. This
means that the directory to the Python interpreter must be added to
be able to invoke the interpreter from any directory.
In this section, we will cover how you can modify PATH and environment
variables.
Setting up PATH in Windows
If you changed the installation directory of Python or if for some reason you
cannot invoke the Python interpreter from the command prompt, you may
need to check its PATH variable. Open command prompt and type:
%path%;C:\Python
Press Enter. C:\Python is the default Python directory. If you chose a
different directory during setup, substitute this location for the location you
used during setup.
Setting PATH in Mac and Linux
Since both Mac OS and Linux are UNIX-based operating systems, the
procedure for adding the Python directory to the PATH is almost similar.
In Mac, using the sh or ksh shell, type the following command and press
enter.
PATH = "$PATH:usrlocal/bin/python3"
Using the csh shell, use this command:
export PYTHONPATH=usrlocal/bin/python3.7
Remember to substitute the directory name in the command you use with the
Python 3 installation directory.
Installing Pip
An installation of Python is not complete until the most essential third-party
packages – pip and setup tools are also installed. These two tools make it
easier to download and install and to uninstall any Python packages and tools
with a single command. They are also instrumental in adding network
installation features to the Python development environment with minimal
effort. Note that the latest versions of Python 3 have pip installed by default.
To check the status of pip installation, use this command:
$ command -v pip
On Linux and Mac OS, use pip3 to check the installation of pip for Python 3
and pip for Python 2.
Chapter 5: Getting Started with Python
One thing we do need to do first though, is to install the interpreter and IDE. I
should probably also tell you what those words mean…
The good news is that interpreters are easy to come by for Python because
it’s a popular language. A lot of HP computers actually come with Python
already installed for instance while there is an interpreter also available from
the Windows 10 Store. Max OSX comes with versions of Python too from
10.3 (Panther) and upwards.
If you decide to install an interpreter the old fashioned way though– which is
probably the best way to go ahead– then you will want to download either
Python 2 or Python 3. Each version has its own pros and cons but it’s worth
sticking with 3 for now. We’ll talk about the pros and cons of each later on
but suffice to say that Python 3 is the most recent version (released in 2008)
but is also undergoing development still. For the most part, the two versions
are very similar so if you decide to switch later on you’ll be able to do so
without too much trouble. Just to confuse matters by the way, these two
versions are often called 2.x and 3.x…
The Installation Process
Once you have the installation file, double click on it and Python will install
completely on its own!
But once that’s done, you might find things are still a little confusing. At this
point you have something called the‘Python Command Line’ and‘Python
GUI’ on your computer. If you open these, neither has any option to‘run’ an
app or to do any of the things you might associate with programming.
And this is where getting the IDE with a compiler built in becomes
necessary.
There are actually a few different IDEs you can use and you can find a
selection of those here:
https://wiki.python.org/moin/IntegratedDevelopmentEnvironments.
Some of these IDEs are free, while others will cost you money. One example
is Wing IDE 5, which you can download from Steam for a free five-day trial.
If you choose to pay for it though it is going to be a little pricey starting at
over $70! Other options include NetBeans, LiClipse, Komodo, PyCharm and
more. PyCharm is free and open source and is a very popular option among
many.
At this point, you are probably ready to get started with some of your own
coding with Python. You want to get the program downloaded so you can
learn how to make some of your own amazing codes. But before you can do
this, you need to make sure that all the right components are downloaded on
your computer. The good news is that since Python is compatible with all the
operating systems currently in use, you just need to start by turning on your
personal computer and then go to the next step.
Since this coding language is open sourced and completely free, all you have
to do is to visit the Python website, at www.python.com, to get started.
There are a few different versions to go with, so you should pick out the one
that you think you can use. There are versions available for each operating
system so make sure to look at this as well before choosing the version that
you want to work with. Once you decide on which version would work best
for your computer, you just need to click on the prompts that show up and do
as instructed to get it downloaded on your computer.
While you are waiting for the Python program to finish downloading, there
are also a few other tools that you will need that can help with writing these
codes. First, you have to make sure that you downloaded a text editor as well.
This text editor is the tool which you will use to write out the codes that you
want to make. You will also need an IDE or an ‘Integrated Development
Environment’ which you can use to read and execute the codes that you want.
Let’s start with the text editor. It is not necessary that you go with a program
that is too complicated to make this work. The notepad text editor found on a
Windows computer or some other program will work just fine. There are a lot
of options that you can choose from here, but Notepad or something similar
is free, so it is a good option for you to work with.
Then you also need to take some time to work with the IDE. If you don't add
this to your computer, it will be impossible to write out or execute the code
you want to work on. There are a few different options when it comes to the
IDE, so do some shopping around to see which kind will offer all the features
that you are looking for. There is one IDE that is available, and you can get it
through Python so that you can keep things simple, but there are also other
options available if you need more choices.
Once you have downloaded the Python program as well as the IDE and the
text editor that you want to work with it is time to work on writing your own
code. The process is simple, but we do need to look at a few things first and
learn some of the basics so that you can start to write your own Python code
in no time.
As you get started with writing your own codes in this language, you will
start to see that there are many parts that come with them. Being able to
understand how these basic parts work will help you to write the codes that
are needed in your program. This section will quickly go over some of the
basics that you need to know before you start working with Python.
function, and you can always change up the statements that are inside the
code to figure out how you want to execute them later.
Running Python Programs
To run a Python program, the script has to be sent to the interpreter for
execution. There are several ways to do this.
RESTART: fullfilepathcylinder.py
785.3981633974483
Alternatively, the script can be executed by sending it to the interpreter with a
terminal shell.
Mac/Linux:
python3 cylinder.py
Windows:
py cylinder.py
you should get an output of
785.3981633974483
The file can also be executed from outside the file directory, but the full path
of the script must be included in the call.
Python3 fullpathtofilecylinder.py
Using IDLE
In the script mode, Python runs scripts or programs saved with .py extension.
Features of IDLE
IDLE is a huge improvement from the command line interface. Here are
some of its features:
Python Shell
smart indent
auto-completion
syntax highlighting
integrated debugger
The Python Shell
The Python Shell allows users to access the different features of IDLE
through its drop down menu. It is what you will use to work interactively
with Python. Just type and enter a statement and Python will display the
output immediately on the screen. Unlike the command line interface, Python
Shell allows users to scroll back to previously entered commands and copy
paste a selected command on the current prompt.
You can also use the Python Shell as a basic calculator by typing and
entering a mathematical expression on the >>> prompt.
You’re going to need a few different things to get your Python setup going.
Firstly, you’re going to need to install Python itself or check to see if it’s
already installed.
Verifying the install is pretty simple. In Windows, press the Windows key
and search for “Python.” If it’s there, it’ll pop up in the list of applications.
Regardless, if you don’t have Python, you obviously are going to need to,
well, get Python.
The reason that we’re doing this is that almost all legacy code you’ll
encounter and, indeed, a lot of the code being written today, is written in
Python 2. Python 3 very well may be the future, but it’s not the current. If
you run into an event where you need to work with Python 3, it’s super easy
to transfer your skills over to Python 3 anyway. Pay careful attention to the
installation process on Windows, and if there’s an option to create PATH
variables, ensure that it’s selected. PATH variables are what allow you to
launch a program from the command line and perform certain actions with it.
Once you have Python installed, we’re going to need to install a text editor
from which we’ll work with Python. You may be tempted to work with the
Python IDLE, but this isn’t the best idea. It’s much better to get a text editor,
if only for the reason that 1) you learn the environment and can work with
numerous different programming languages from within it, and 2) you can
grab plugins which will make your job as a programmer much easier.
Whether you’re doing this for a career or a hobby, you’re a programmer now.
And very, very few developers use the Python IDLE. Some prefer emacs;
some prefer vim, some use Sublime Text, others use Notepad++.
For this book, we’re going to be using something called Atom. You can grab
this from their website (atom.io). The reason that we’re using Atom is that
it’s super simple to set up, can be used on any major platform, and is
incredibly customizable and extensible. It’s a great starting point for text
editors.
If you have a friend who’s trying to get you into programming and saying
“no, you have to use insert text editor here!”, Then there’s nothing wrong
with appeasing them. Text editors are just environments to write code. But if
you’re new and scared of what the world of programming may hold, Atom is
a very safe choice.
Anyway, you go to atom.io and just head to their downloads page and grab a
copy of the software. Install it, and you’re ready to go.
The other reason we’re not using the IDLE is that it teaches you to use a
crutch. I want you to learn how to launch Python code using the command
line because it’s just frankly essential knowledge to have. In this way, you
also need to know how to navigate and perform basic commands within the
command line. In Mac and Linux, this command line is called Terminal. In
Windows, you won’t be using the standard command line - instead, you’ll be
using the PowerShell, which you can find by simply searching for
PowerShell in the start menu.
If you don’t have basic knowledge of file system navigation via command
line, then frankly you need to learn it. It’s beyond the scope of this book, and
I’m not going to cover it in here because there’s precious time to be spent
teaching other things.
Create a new folder where you’d like to store your code. Then open Atom
and right click the sidebar to the left. Click the object that says “Add Project
Folder,” then choose the folder that you just created. Then left-click the
project folder on the sidebar. It’s now the existing folder. Right click
anywhere on the sidebar and click “New File.”
On the dialog that says “Enter the path [...]” you can just enter a filename.
We’re going to call this file ch1.py. Technically, you could call it anything
you like. It isn’t like Java where the filename has to correspond to something
in the code. But for simplicity’s sake, yes, we’re calling it ch1.py.
Then save the file. The shortcut for this, if you don’t know it, is Ctrl+S.
Head back to your Terminal/PowerShell. Navigate to the folder which has the
ch1.py file, then execute it by typing the following: Python ch1.py
hello world
If that’s how it came out, then awesome. You just wrote your first Python
program. How proud are you? I’m pretty proud of you. Now we’re going to
work on some more important concepts like variables and math.
Simple: we type:
print(“Hello World”)
Note that we’re using lower case for the word‘print’. This is important as
otherwise Python might think we’re referring to a variable– more on that
later!
Oh and one more note is that this may not work if you’re using other versions
of Python. If you get an error, try this instead: print “Hello World”
If this works, then you might want to go back and reinstall a newer version of
Python– at least the most recent Python 2!
But of course a program needs to be more than one line long… so how can
we do that?
Note that you do need to save your script before you can run it however.
Oh and if you want to do this quicker next time, you can simply hit‘F5’ to run
your code!
Chapter 7: Python Numbers
In the beginner’s guide, you learned what operators you could use in Python
so that you could do mathematical problems.
Say you want to know how much you weigh against something else such as a
pile of bricks. For the sake of worrying, we are going to assume that every
brick is going to weigh about ten pounds which is 4.5 kilograms.
But, that cannot be placed into Python like that, so we are going to change the
code up a little so that we can enter it into the program which is then going to
do the calculations for us.
Example
In Elementary school, we all learned the basic operators that are used when
we are trying to do calculations for math. In Python, these are going to be
similar to the same ones that we learned in school, except there is going to be
a little bit of a difference so that the program can read the code properly and
does not do the wrong calculation.
Example
4.0
2.0
When you are using the version 2.x for Python, a single forward slash is
going to be used for single integers and long expressions.
True division is going to be found when you are having to divide floating
point numbers or complex numbers.
In order to fix this “problem” you are going to need to use a new function so
that the normal division sign is not going to give you an error through Python
which will result in your answer being rounded down. The function you are
going to use is: round( [ math ] – 0.8) Order of Operations
Once again, the math that we learned in the lower grade schools is going to
come into play when we are figuring out how Python is going to determine
which part of the expression it is going to evaluate first.
But, the parentheses, no matter where they fall in the expression, are going to
take precedence and be the first thing that is going to be evaluated.
Output Formation
Just like when we do math in the real world, the math that we do in Python is
not always going to be dealing with whole numbers.
There are going to be times that we are going to have to deal with complex
decimal points.
Example
When dealing with decimals like this, Python is going to automatically print
out to ten decimal places.
In case you only want a couple of decimal places, you are going to use the
function round().
Round() is going to allow you to choose how many decimal places you want
the number to be printed out to so that you do not have to deal with such a
large number.
Example
142.83
Using the same function, you are going to be able to get it to print out the
decimal to the number of places that you want it to print before you ever get
the long and complicated number.
Example
Not only are you getting the function to round up to the number of decimals
that you are wanting to see, but you are also using a function known as
nesting.
Nesting is going to occur when you place two functions inside of each other.
Everything is going to work as it would have if you hadn’t placed them
together.
If you do not want to use nesting, you can still write out the equation using
several different variables so that the equation turns out to be longer, but it is
going to do the same thing.
Example
In the beginner’s guide, you learned the different operators that are used
when you are doing comparisons with integers in Python. Now, let’s examine
how they appear when you look at the code in Python.
Example
Res = 50 == 15;
Res = 50 != 15 ;
As you learned before, strings are among one of the more popular types that
you are going to use with Python. Strings are typically created so that they
can encase a set of characters within a set of quotes.
The single quotes are going to be treated just like double quotes are treated.
It is vitally important that you remember to end with the same set of quotes
that you begin with. Do not mix and match quotes or else you are going to
receive an error message.
Strings
Triple quotes are going to be the easiest way that you are going to be able to
set the definition of a string.
The only time that you are going to use string concentration is when your
string is a thousand characters or more.
Example
Print “peanut butter” + “jelly” + “peanut butter” #this type of coding should
not ever be done!
At the point in time that Python is not supporting a specific character type, it
is then treated like a string that may or may not have a substring that is
attached to it.
When you want to get into the substring, you are going to need to use a set of
brackets ( [ ] ) in order to ensure that the string is cut along the correct index
so that the substring is created properly.
Example
#!/usr/bin/python
Output
Variable 1 [1]: h
Variable 2 [ 3: 6]: an t
It may not make much sense by the example, but it is going to be more
helpful when you are trying to create your substrings.
It is also going to make more sense after you have made the string yourself
because it is going to be your own creation.
Updating
When you are going through your strings and notice that something needs to
be changed, you are going to be able to do this without having to rewrite the
entire string over.
Any new value that you want to move or reassign is going to be placed into a
new string or it is going to be changed to a different value of your choosing.
Example
#!/usr/bin/python
Output
When you want something to happen with the string that you have created
but there is not a specific function for it, then you are going to need to do a
special operation so that you can complete the expression that you are
wanting to do.
Repetition – a new string will be created but it is going to be the same string
that has already been made. (*) Slice – the string is going to be cut at a
specific character depending on what index is indicated ( [ ] ) Range slice –
the characters are going to be chosen between the set range ( [ : ] )
Special characters are going to come with special rules and that includes
using triple quotes.
Some other special characters that are going to use triple quotes are tabs as
well as new lines.
Triple quotes are going to use either three single quotes or a three sets of
double quotes.
Example
#!/usr/bin/python
Para_str = “””I am going to type for a long time so that it makes it seem like
it is going to be a very long piece of script. In this script the characters that I
am going to use are \t which is going to insert a tab wherever I place that
character. New lines can also be added to this script by using [ \ n ] or by
typing in new line so that the variable shows up where it needs to. “””
Python is going to execute the code above just like any other piece of code
that it encounters. When it does, it is going to not insert the functions that are
inside of the script. Instead, it is going to put the correct object in. So, where
there is a tab, a tab is going to be placed in it.
Example
Output
D: \ anywhere
Example
#!/usr/bin/python
Output
D:\\ anywhere
Chapter 9: Python Basic Syntax Rules, Variables
and Values
Introducing Variables
Well, if you think back to your high school math, then you may actually
recall using variables back then. And variables in Python work in the exact
same way.
So if you cast your mind back to your school math days, then you may recall
seeing things like this written: 10 + x = 13
Find x.
This works in just the same way in Python except there’s no‘finding’ of x
involved. Instead, we’re telling Python what x is and then referring to it later.
So how do we do this? Pretty simply actually: x = 3
MyVariable = 3
So let’s open up the script mode and try using this in part of a little program.
Just write: MyVariable = 3
print(MyVariable) Now save the program and go to run it. When you do this,
you’ll find that it simply outputs the value of the variable– which in this case
is“3”.
We haven’t actually explained what‘print’ does yet but by now you should
have been able to work it out. This is simply a command that writes text to
the screen and you can make it anything you want it to be by using quotation
marks as we did when we wrote“Hello World”.
But you may have noticed that we didn’t need to use the quotation marks
when using the variable. That’s because the quotations marks are only there
to say‘write this text exactly’.
Integers, Strings and Floats
The variable MyVariable contains the number 3 with no decimal places. Thus
we call it an integer. In other words, we name our variables after the data they
contain. So seeing as the number‘3.72’ is a float, we would call a variable
that contained that number a float as well!
So far so easy… But things are about to get significantly more complicated as
there are a lot more types of variable and it will pay to at least be familiar
with most of these…
The integer and the float are both considered‘number variables’. That means
that they contain numerical data.
Actually though, there are also two more types of variable. These are
the‘long’ and the‘complex’. You’ll use these two less often but essentially
longs are used when you need really long numbers and complexes are used
when you need very complex numbers.
All of the variables we have looked at so far have one thing in common– they
hold one piece of data or a single value. There are also other types of
variables however that contain more than one piece of data. So if we think of
our strings, integers and floats as boxes, then these variables are more like
filing cabinets, folders or bookshelves.
The standard data types available when using Python then are: Numbers
Integers
Floats
Longs
Complexes
At any point in our program and then‘x’ will be created with the value‘3’. In
Java though (another popular programming language), x would first have to
be created with a statement like: Int x;
x = 3;
Part of the reason for this is that other programming languages use a much
wider range of variables– such a‘Booleans’ which can only equal one or zero.
Because Python only has a few types of variable, it doesn’t need as much
structure.
Python affords us a little more flexibility and saves time by removing the
need for defining variables but it can also lead to more confusion in larger
programs. When writing lots of code, it can be useful to keep a note of what
all your variables are called and what they do!
So if you are using a string to refer to a user’s name, then what should you
call it? A good option would be: UserName or Name. This will make life
much easier than if you call it Rabbit1112…
Another tip is to try and choose variables that read well as though they were
written in English when they’re inserted into the code. We’ll touch on this
more in future.
Using Comments
To make finding your way around just that little bit simpler, note that you can
also use comments.‘Comments’ are lines of plain English that you can insert
into your code. The compiler will ignore these lines when you run your
program but it means you can add instructions, notes and references for
yourself or other members of your team.
To insert a comment, simply precede your line with a‘#’ symbol. The
comment will then extend to the very end of the physical line. If you’re
coding using IDLE, then the comment will instantly change to a red font
when you get it right:
Think ahead while writing your programs as taking a little time to keep your
code clean now can save you a real headache later on!
Hello World Program
First off, start your command line terminal and initiate the Python interpreter
by typing "python" and pressing enter. You should see a prompt with three
arrows meaning that the Python interpreter has been invoked.
This is a way to invoke the interpreter without having to pass a script file.
However, this approach does not save your program because the code is
interpreted and executed from the temporary memory.
To create a program we can save, we will have to save the line of code we
typed in a .py script file using a text editor.
Start your text editor and type the code as it appears, replacing the (enter your
name here) with your name. Choose a name to save your script as, such as
HelloWorld.py. The line of code on your editor should look like this:
print ("Hello World!") #This will display Hello World! text on the screen
print ('Hello World again!')
You have a line of text that you would like to send to an external file. In this
case the sentence is exported an external file called Star Wars.txt. The mode
used is w as we are writing the sentence to the file. You must use close at the
end to make sure the file is closed.
When you run the program nothing appears to happen, but if you look in the
same folder as the Python program you will find a text file called Star Wars
and if you open this file you will find the sentence.
Sometimes you want to write a program that automatically closes the file.
Write this program using the editing window.
You can also write a list (array) to an external file. In this case it is a good
idea to write the file as a csv file as the table can then be viewed within a
spreadsheet. To do this you must import the csv module.
The program below will take the list and export it to a csv file which can then
be viewed from within a spreadsheet. This will appear in the same folder as
the Python program. Write this program using the editing window.
Here is the output produced.
If you have already created a text file it is possible to read the text from this
file back into your program.
In the example shown below a notepad file has been created containing the
text Hello World. This has then been saved as Hello.txt. The program below
has been written to take the text from the external file and assign it to the
variable text. Write this program using the editing window.
If you have created the list using a csv file then by performing the reverse of
the operation shown earlier it is possible to read the csv file back into an
empty list.
First player 1 must throw the dice. If the player throws a 6 they have won the game. If no
throws the dice. This continues until one of the players throws a 6 and wins the game.
(a) Develop a program that writes the instructions shown above to an external file called
(b) Develop the program so that the contents of the external file can be read back into the
stored using a variable called instructions.
2. (a) You have been asked to create a program using Python that asks the user their nam
band, their favorite singer and their favorite song. The program stores this information in
the information to an external file.
(b) You have been asked to create another program that can take the information stored i
produced in part a, and then import it back into a list. The program then displays the list a
table.
Chapter 11: Python Functions and Modules
Module
Modules in Python are going to enable you to organize your Python code in a
manner that makes sense.
The objects in a module are going to be named after things that you are going
to be able to bind and reference at a later date.
An easier way to think of it is that modules are similar to files that are full of
Python code. The module will ultimately define a variable, function, or class.
Syntax
Python’s interpreter is going to import the module but only if it has a path to
follow.
The search paths are going to be a directory list where the interpreter will
search to find the correct module before it is imported.
Example
#!/usr/bin/python
Help.print_func (“Tim”)
Output
You can import a module as many times as you want, but it is not going to
change the fact that it is only going to be loaded into the script once.
This was put into place by the creators of Python so that the execution of the
module does not happen each time that it is imported.
From…Import
A form statement in Python ensures that you can bring the attributes that you
want into the module from where it is stored.
Syntax
Example
This statement is not going to import the entire module, but it is going to
bring the module into the script.
Names can also be imported from the modules that are in your directory by
using a slightly different syntax.
This syntax makes it easy for all of the module to be imported into this space,
but, this function should be used sparingly.
Module location
After a module has been imported into the code of Python, it is going to be
searched for in a very specific order so that Python can ensure that it is
getting the correct module.
First it is going to search the directory that you are currently in.
The search path is going to be inside of the module under the variable of
sys.path.
The name of a variable is going to be the identifier that helps Python to find
the object.
Namespace is going to be the keys and their values that are going to be tied to
the object.
Statements in Python can be used to find variables but only if they are in the
local space or the global space.
Local namespaces will ultimately shadow the variables that are in the global
space.
Every function that you use in Python has its own namespace. The classes are
going to follow the rule that normal functions follow.
Python has the ability to guess where the variable is going to fall. When a
variable has a value that is assigned to it, then it is going to be placed in the
local space.
A global statement has to be used if you are wanting to put a value to a global
variable.
VarName is the signal that tells Python when a variable is global. When this
function is used, Python will not look in the local spaces for the function that
you are trying to locate.
Example
#! usrbin/python
Pennies = 100
Def AddMorePennies ( ):
#this comment is only to tell you that making the following comment part of
the code is going to fix the code so that it works properly.
#global pennies
Pennies = pennies +3
Print pennies
AddMorePennies ( )
Print pennies
Dir( ) function
This function was put into Python so that you can sort out your strings that
contain the names of the module that you are currently using.
Functions for globals ( ) and locals ( )
These functions are going to be used so that the global and local namespaces
are returned but it is going to depend the location in which they are located.
When you are working with the local ( ) function, it will give you the names
that are in the function for that particular location.
A globals ( ) function is going to return the names for the function in that
global location.
There is a dictionary that has all of the types for both of the functions listed.
Names are going to be pulled with the keys ( ) function.
Function reload ( )
Should you want to make the module be executed again, you are going to use
the function reload ( ).
This function is going to reload the module that was previously imported.
Syntax
Reload(module_name)
The module name is going to be what the module is named in the Python
directory. The string name is not going to be name that is placed in this space.
Example
Reload(South )
Python Packages
There is a hierarchy when it comes to the file directory and this is going to
end up defining applications that are in Python.
Example
Def Butter():
There are going to be two files that have been created with Python that are
going to be the same as the example above, however, you are going to have
to create a third file so that the correct file is being pulled for the script that
you are using.
Functions
Functions are going to be blocks of code that are reusable and are going to
only be put in place so that they can execute a single action.
Functions are going to use a higher degree of code that can be used.
Definition of a Function
There are rules that you have to follow in order to define a function properly.
A statement that has been returned is not going to have any arguments and is
going to be returned as none.
Expressions that are returned will end up exiting the function and therefore
sending the expression back to the caller.
The keyword def is going to start the block of code and then the name of the
function is going to be followed but a set of parentheses.
Each block of code is going to begin with a colon and will be indented at
least once space.
The parameters that are set up for the expression will be inside of the
parentheses.
Python has a default built in that is going to cause the parameters that you set
to be positional behavior. If you want them to be different, you are going to
need to ensure that you tell Python in which the order that the function is
defined.
Example
Def printme ( str ) :
“This is going to be the string that is placed into the function that I create”
Print str
Return
Function Calling
A function that has been defined will only set the parameters for it and then
give it its name.
At the point in time that you have set the structure for the block of code, you
are going to be able to execute it by creating another function or by using
Python directly in a prompt that is provided by the program.
Example
Print str
Return;
Output
This will be where the first definition is going to go.
Example
Return
Asection = [ 2, 4, 6 ];
Nameme( asection ) ;
Output
In this fast-paced life where time is of the essence and planning days down to
the last detail is almost mandatory in order to keep up to date with busy
schedules, the ability to program the date and time is a very important tool
and can have many useful applications.
In order to use the built-in clock functions of Python, a user has to import
built in functions from the "datetime" module (notice the italic "from" - it is
an import part of the code as you will discover in the worked examples).
Some functions that may be imported are: date, time, datetime, and timedelta.
Each of these functions have their own unique outputs and allow a user to
interact with Python in different ways.
There are 4 easy ways of presenting date and time:
Worked Example:
Notice that after "Type 1" a function is not defined yet the code is accepted.
This exemplifies that the datetime module does not require a defined function
to return the desired output.
Input Code:
Output returned:
After learning about the possibility of date and time programming, a user
might start to wonder how to program it so that only certain aspects of output
are returned.
Time and dates can be formatted using a set of predefined string and control
codes
The control codes used to format days & dates are:
Strftime(): - function that takes a control string and replaces whatever the
control code is (eg.%Y) within the value that is in the date/time
%c – locale's date & time (will change depending on locale in the world)
%M - Minutes
%s – Seconds
The day of the week and the current date and the time
Worked Example:
Input Code:
Output returned:
Do you recall the introduction to arithmetic we did earlier? It gets better than
simple maths – you can apply maths to your date calculations! (eg. time to
deadline or expiration)
Input Code:
Output returned:
What is a time lapse? A time lapse is a change in time from one instance or
situation to the next. Therefore, a "timedelta" is a class that shows a span of
time which can be used to perform time-based mathematics for future and
past events.
Worked Example:
Input Code:
Output Returned:
As you can see, the process for returning codes can be very simple if you set
up the code to return the basic outputs. However, it will become more
complicated as you start to shape the code to more specific outputs.
I hope you're ready to jump in the deep-end because that's where we're going
now with this second example:
Worked Example:
Output Returned:
Notice in the output that the numbers are not in a single, uniform line. This is
not user friendly and can become laborious to read.
Luckily for us, there is a trick we can employ to create uniformity in the
output. This is done by "padding" the input code to ensure all outputs are
aligned.
In above output, the longest month (September) has 9 letters. So let us pad
our months by 9 spaces. And, for the sake of enforcing the padding principle,
let us create a pad of 3 for our days.
Output Returned:
Before we end this chapter, we shall create a simple code. Follow along with
the logic and understand carefully how the inputs result in the outputs.
Input Code:
Output Returned:
Suggested exercise
Create a code to find a day that is special to you (eg. Anniversary, Holiday,
Christmas, etc)
Chapter 13: Lists and Tuples in Python
Lists
The lists in Python are going to be the most basic data structure because they
are going to fall in a sequence.
The elements that are inside of the list are all going to have a number that is
assigned to them. In other words, they all have a place that is assigned to
them.
Not only are they simple, but lists are going to be versatile.
When creating a list, the objects are going to be separated by a comma and all
of these objects are going to fall inside of a set of square brackets.
Example
The index for a list is going to start at zero and you are going to have the
ability to cut it so that you can create sub lists Getting values inside of your
list
When you want to get a value inside of the list so that you can slice it at a
specific index.
Example
Output
When you want to update elements in your list, you are going to use the slice
function so that you can add in the elements that you want to be added.
You are going to use the append() method so that the elements are added
where you want them to be added.
Example
#!/usr/bin/python
Print section [ 3 ]
Section [ 3 ] = 2060;
Print section [ 3 ]
Output
2002
Sometimes elements have to be deleted from the list that you have created.
Example
#!/usr/bin/python
Print secion1
Del section1 [ 3 ] ;
Print “the new list after the third index has been deleted : “
Print section1
Output
Tuples are going to be like lists in the fact that they are going to be a
sequence of objects, but, they are going to be immutable.
You can use a set of parentheses or not in order to make a tuple, all you need
to ensure is that you are using commas between the different objects that you
are wanting in your tuple.
Example
Tup2 = ( 5, 9, 7, 4, 2 )
Syntax
Tup1 = ( )
Tuples can also only contain a single element. To do this, you are going to
still insert a comma, but you are not going to add any other elements into the
list.
Example
Tup1 = ( 5, ) ;
Accessing values
Square brackets are going to be used so that the tuple can be sliced along the
correct index so that a single value or series of values can be pulled from the
tuple.
Example
#!/usr/bin/python
Tup2 = ( 5, 6, 8, 4, 3 , 1, 0) ;
Output
Tup1 [ 2 ]: 2002
Tup2 [ 2 : 6 ] : 6, 8, 4, 3, 1
Updating
Since tuples are immutable, you are not going to have the ability to update or
change them.
Parts of the tuple that exist are going to be able to be copied and made into a
new tuple instead.
Example
#!/usr/bin/python
Tup1 = ( 5, 9, 25) ;
Print tup3
Output
Just like you cannot change tuples, you are not able to delete elements
because that would be changing the tuple.
Instead, you are going to have to create an entirely different tuple without the
elements that you do not want in the tuple.
You will use the del function when you are wanting to get rid of an entire
tuple.
Example
$!/usr/bin/python
Print tup
Del tup;
Print tup
Output
Once the tuple has been deleted, you will receive an error that says that the
tup has not been defined.
Chapter 14: Mistakes you can make when
programming with python and how to avoid them
When you are using Python, it is easy to make mistakes. Some of these
mistakes cannot be avoided, but others are going to be able to avoid.
So, why not stop some of these mistakes before they happen. If you can avoid
some of the mistakes, then you are going to be saving yourself a headache
later.
Mistakes that are pragmatic
There are functions that can be placed into the script that you have created
and it will run a command for the system to follow.
These commands are not going to be as simple for Python to follow, it will
just be easier for you to enter the command into the prompt so that Python
has no question about what you are wanting it to do.
Print statements
Thanks to the interpreter, the results from any expression that you put into
Python is going to automatically be printed as it needs to be after it has been
evaluated by Python.
This is going to eliminate the need to enter in the entire print statement into
the prompt thus making the code look more cluttered.
Print statements are normally used so that the output can be displayed into the
file that you are working on.
If this is not done, then Notepad is going to save the file as a .txt file which is
going to cause problems later on when you are trying to launch the code in
Python.
WordPad and Word are going to end up formatting the code that you enter
into the program and therefore Python is not going to be able to take the code
due to the formatting.
IDLE is going to be one of the best programs that you are going to be able to
use.
Save all files that you create outside of Python with the all files option.
It is vitally important that you add the extension of .py when saving Python
files so that it can be run in Python when you are wanting to run it.
Python can be launched with a file on Windows, but this can end up causing
errors.
The window that is going to display the output will give an error in the
program. When you want to see these errors, you need to run your program in
a different manner.
Try using a command line in the system by using a program like IDLE.
Imports
With the interactive prompt, files can be imported, however this can only be
done once per Python session.
Imports are going to return a module that has been loaded into Python
already.
Python can be forced to rerun the file by using the reload ( ) function.
Blank lines
Any comments placed in your code, or any blank lines will be ignored when
the code is run through the program.
Blank lines tell the prompt that the statement is finished and that the enter key
is not going to be hit until the code is fully done.
The blank line that you put is going to terminate the statement before a new
statement can be started.
Statements are only going to be run one at a time in the order that you have
entered them.
Mistakes with code
Colons
A colon needs to be put at the end of headers that are going to be for
compound statements.
Variable initialization
Names are not going to be able to be used unless they have been given a
value first.
This stops mistakes that often happen when names are entered wrong and it
also stops the questions of where the program should start.
Column 1
When you are using code that is not nested, it is going to need to go in
column 1 which is going to be all the way to the left.
This also has to be used when you are using module files that have not been
nested but are being entered in the prompt that is interactive.
White space is treated like a blank line, unless it is being used for indention.
Indentions
Tabs and spaces are going to be different for the indentions. Do not mix
them!
Be sure that every program that you use with your code is going to end up
using the same method for the indentions.
If you mix and match the spaces and tabs, you could end up getting code that
is not going to be user friendly because Python did a different number of
spaces.
The safest method is to pick a method and a number and stick with it through
the code blocks.
The parentheses are what sets the function apart so that it can call the object
in question up properly which makes functions special operations that have
rules you have to follow.
When you are closing a file, you can use the close function without
parentheses, but it is not going to successfully close the file that you are
wanting to close like if you had added parentheses to the function.
Paths and extensions
File extensions and paths should be saved when you are entering command
lines for telling the system to do something rather than when you are trying to
import something into Python.
So, do not use import mod.py or any other version that would end up being
considered a system command.
Extensions that have other letters besides py are not going to be legal when it
comes to Python because Python is not going to understand what the file is
and therefore it is not going to make sense when it comes to being run in the
program.
The directory path is going to be used when the module is searching for
where the module is located, and this is not going to be used with an import
statement.
Dots can be used so that subdirectories can be accessed in the file path. But,
the path is going to have to be found when the module goes on its search.
When you use the wrong statement Python is going to do the wrong thing and
put the module in instead of what you are wanting it to put in.
The statements are not going to be terminated with semicolons. This should
only be done if you are using multiple statements in one line.
While loops should not be embedded. These statements are not going to be
where you want them to be and then the assignment in Python is not going to
be the expression that you were trying to get.
Mistakes with programming
Module searches are only going to be used when you are importing a module.
Specific types
This is known as a type specific function that is only going to work on the
type that it was set for.
The reverse method is only going to work on a list and no other data types.
Immutable types
When things are immutable, they are not going to be changed no matter what
you do to try and change them.
Even if you enter in the code that you think is going to change the data type,
it is not going to change it, it is going to give you an error instead.
This is going to make it quicker for you to get to the object that you are
looking for.
Range should not be used when you are using a for loop because Python is
going to do the indexing automatically.
When you want to call upon one of these functions, you are going to need to
assign your result to the proper value so that you get the proper result instead
of just modifying your list.
Conversions
Decimals in Python are going to be converted into a floating point so that the
floating point can be used to give you the proper answer.
The program is going to detect the cycle so that it does not have to go around
forever.
Chapter 16: Python Variables and Operators
Let’s start off with one important broad Python variable concept that might
take a little thinking to wrap your head around.
Python classes all variables as objects which are either mutable or immutable.
On the surface you would think that mutable means it can change and
immutable means it cannot change. But what good is a variable that cannot
change?
However, integers, floats, strings and others in python are all considered
immutable even though their values can in fact be changed.
For example if we went to the shell in IDLE and entered the following:
>>>X=10
>>X+=10
>>print(X)
we would get X=20, as expected.
What the interpreter actually does is create an object X in memory. When the
operation is performed to add 10 to X, a new object is created in memory
containing 20 and X is pointed to that.
The old value of 10 is no longer referenced and is discarded. This may seem
like a distinction without a difference until you combine this with the fact that
Python is managing memory on the fly as the script runs (unlike C/C++
where you as the programmer manage memory).
If you are doing a lot of functions, like string concatenation, that use
immutable objects then you are in fact doing memory intensive operations.
Operators, Operands and Operations
Let’s take a moment to reflect on what just happened there… You just wrote
your own program! You are now officially a‘programmer’… so
congratulations!
And the first and most obvious way to begin doing that is by using operators,
operands and operations. This means essentially that we’re going to be using
Python like a big calculator!
Doing this really couldn’t be easier either. If you want to do a sum in Python
for example, you simply type out a sum! So that means you might write: 10 +
2
Now just hit return in interactive mode and you’ll see the number‘12’ pop up
on the screen. Success!
10 – 2
But you will notice one unusual bit of behavior when you use division: the
result is always shown with a decimal point! So instead of saying 5 you
would see 5.0.
This is because the division operator return what is known as a‘float’ which
basically means a number with a decimal point. You can remember this by
thinking that a float has a decimal point that‘floats’ somewhere on the screen.
If you want a round number– an integer– then you need to use another type of
operator called‘floor division’ (the other kind is sometimes referred to
as‘true’ division). When we use floor division, we actually use two slashes
like so:‘//’.
First, letsconsider a few other bits of math. If we can have‘//’ then can we
have‘**’? Yesindeed but this actually does something different! This is
what’s referred to as‘times times’ but is more technically
called‘exponentiation’ and it basically means you’re performing the operation
multiple times. So: 5 ** 3
Actually means: 5 5 5
Think about this a little like being served drinks at a bar. When you’re
ordering, it’s always polite to ask for the most complicated drink first. So you
ask for the martini shaken and not stirred with the slice of lime, followed by
the beer. This is precedence.
In Python, precedence means that your interpreter (our bartender) is going to
carry out some of the functions before others. This doesn’t mean that you
have to carry out those particular functions first– actually it means the precise
opposite thing so it’s okay to write the operations in any order that you like.
1+3*4
What would the result be? It all depends on which operation is first. Because
if the multiplication comes first then you have 13. If the addition comes first
then you have 16!
So place your bets: which do you think it is? And the answer is that the
multiplication comes first! But as with any mathematical equations, we can
change the order by using parenthesis (brackets). Anything in brackets will
happen before anything else. And yes, you can have brackets inside other
brackets! But just to know the order that Python does things in automatically,
it is: (), **, *, /, +, -.
Okay so at this point, you have written hello and used Python like a fancy
calculator. That’s not terribly exciting but don’t worry– things are just about
to get a lot more impressive and useful! That’s because we’re going to be
introducing one of the main concepts that is used across all of programming:
variables.
Performing Operations on Variables
As we’ve already seen, we can set the value of a variable very simply like so
at the start of our code: MyNumber = 3
But if we later want to change the value of our number we can simply change
it again later on. For example: MyNumber = 3
print(MyNumber)
MyNumber = 4
print(MyNumber)
If you run this programthen it will simply output‘3’ and then‘4’. Like so:
But likewise, we can also change our variables using the very same
operations that we used in 4. For example: MyNumber1 = 3
MyNumber2 = 4
MyNumber3 = MyNumber1 + MyNumber2
print(MyNumber3)
Can you guess what this will output?
Or how about:
MyNumber1 = 3 * 2
MyNumber2 = 4
MyNumber1 = MyNumber2 – 3
MyNumber3 = MyNumber1 + MyNumber2
print(MyNumber3)
You can even let a variable refer to itself. For example, what do you think
this line of code does: MyNumber1 = MyNumber1 + 1
Essentially, this increases MyNumber1 by‘1’. So you are saying that the
value of the variable will become whatever it is right now plus one.
Right now this might all seem a little strange but as we go through and look
at the different commands you can use in Python it should start to make a lot
more sense!
The next question you might be wondering is whether or not you can also do
this kind of thing with strings? And the good news is that you can and it
actually works just the same! Of course you can’t multiply a string by a string
(because that doesn’t mean anything!) but what you can do is to add two
strings together to create a new one. For example: FirstName = “Bill”
LastName = “Gates”
FullName = FirstName + LastName
print(FullName)
You’ll see why all this is important soon!
(Actually, I wasn’t being strictly honest when I said you couldn’t multiply a
string. In fact, writing FirstName=“Bill” * 10 would make a string with the
value“BillBillBillBillBillBillBillBillBillBill”!)
Comparing Variables
We’re going to carry on with Ifand Then in a bit but before we do, there’s
one more thing to consider: comparing variables.
Sometimes it will be useful to look at one variable and then compare that to
another variable. For instance, we might want to compare a string to a stored
password if we’re asking someone to log in. Alternatively, we might be
trying to find out if someone is older or younger than a certain age.
For example:
Password = "guest"
Attempt = "guest"
if Attempt == Password:
print("Password Correct")
This essentially tests the imaginary password attempt against the true
password and only says‘correct’ when the two strings are the same. Notice
that we aren’t actually using the word‘next’ at any point. In some
programming languages (such as BASIC) you actually do write‘next’ but in
most it is implicit. Anything that comes after the colon is next, which is just
the same way that loops work! Python is nice and consistent and it’s actually
a very attractive and simple language to look at when you code with it well…
This is the same idea when you are working on classes. You want to place the
similar objects into the same class so that it is easier to find them later on.
The program will work more efficiently when these objects are similar, rather
than randomly placing unrelated objects into the same class.
If this is a new idea to you and you are just getting started with learning a
new coding language, objects and classes are a good place to start because
they will help you to learn more while also making sure that everything will
stay organized in the code that you are working on. As a programmer, it is
your job to learn how to create these classes and then get the objects to go
inside of them so that the code works the proper way.
How to create a new class?
Now that we had a little introduction to these objects and classes, it is time
for you to learn the steps on how to create your own class. You have to do
this because you will find that it is hard to get started with anything in Python
if don’t do this first. Once you are ready to create the statements that are
needed for these classes, you should create a new definition.
You need to place the right keyword first to get this going and then add the
name of the class (the name that you are giving to it) right afterward. This
will then be followed with a ‘superclass’ that you will place inside of
parenthesis. Another thing that you should consider is that at the end of your
first line in Python, you need to add a semicolon. Your code will work
without it, but this is considered a part of coding etiquette, so you have to
make sure that it is present.
Class definition
The first thing we will talk about is the class definition. This is where you
need to write out the object instantiation and then the class definition so that
your syntax is proper when put inside the code. These are important because
they are the part of the code that will tell your compiler what it should do and
which commands are important. If you want to invoke the new class
definition inside of the code, you just have to use the ‘object.attribute’ or the
‘object.method()’ function and it will work flawlessly.
Creating a class
By including a string inside the argument that will be printed with the class
A method can be called on the created class by declaring a class variable "c. "
below the class.
Don't worry if you are not following. This is an advanced use of Python and
is presented as an example for educational purposes
The output of the inheriting class program is similar to that of the normal
class output. The differences are:
Another class is created (eg. "c2 =") in the function that was defined
The parent class will be returned and then the information from the inheriting
class will be returned
Special attributes
The next thing that you can focus on in the above code is the special
attributes that you want the code to recognize for you. You may want to take
a closer look at these because they will add a lot to your code and will help
make it work better. These special attributes will give you some peace of
mind because you can know when the attribute will be seen and you can
make sure that it is used in the right way to prevent the code from getting
messed up. There are a lot of good attributes that can be used in Python, but
some of the ones that you really should pay attention to as a beginner include:
__bases__
__module__
This is where you are going to find the name of the module, and it will also
hold your classes.
__name__
__doc__
This is where you are going to find the reference string inside the document
for your class.
__dict__
This is going to be the variable for the dict. Inside the class name.
How to access members of a class
Now we need to look at how you are able to access members of a class. To
make sure that your text editor and compiler are able to recognize a class and
execute the parts that you want, you must make sure that this code is properly
set up to access all the members of that class. You will be happy to know that
there are a few options you can use to make this happen, and all of them will
work out well, but the ‘accessor’ method is the most popular and the most
efficient one to work with.
To help you understand how this works, let’s take a look at the following
code to make it easier.
#set accessor function use to assign values to the fields or member vars def
setItsAge(self, itsAge): self.itsAge = itsAge
As you can see, classes and objects are really easy to work with. These are
some of the best ways you can use to take care of the information that is
inside of your code. You can create the class and then add the objects that
you want and then match it into the class that you created. This will keep
your coding nice and organized just like the way that you want it, and it also
makes sure the program will actually work.
Chapter 18: Python Dictionaries
A dictionary in Python is an unordered collection of items separated by
commas and enclosed in curly braces. Unlike other compound data types
such as a list and a tuple which have only one value for an element, a
dictionary has a pair of key and value separated by a colon. An empty
dictionary without values will have empty curly braces.
The values of a dictionary may be any data type, but the data type of the keys
must be immutable such as numbers, strings, or tuples. Dictionaries in Python
are optimized to retrieve paired values using the element key.
Creating a dictionary
empty_dict = {}
print (integerkey_dict)
print (mixedkey_dict)
Accessing elements of a dictionary
While we used indexes to access the values of strings, tuples, and lists, with
dictionaries, we use keys. To access an element in a dictionary, we use a key
inside a square bracket or the get() method.
print (my_dict["name"])
print (my_dict.get('age'))
work = my_dict.get("occupation")
print (work)
If you use the square bracket method to access a key does not exist in the
dictionary, it will return an KeyError but if you use the get() method it will
return None instead.
Because a dictionary is a mutable data type, you can add new or delete or
update existing elements.
Exercise33: Deleting and updating dictionary elements
student["age"] = 30
student["sex"] = "Male"
del student["grade"]
You can update the value of a key in the dictionary by assigning it a new
value using the traditional = operator.
You can create a new key:value pair by assigning a non-existent key a new
value as in student["sex"] = "Male".
You can remove an individual dictionary element using the del operator.
You can also remove all the contents of a dictionary in a single operation
using the dict.clear() method statement. You can also delete the entire
dictionary by using del dictionary operation where dictionary is the name of
the dictionary.
Here is a table summarizing the built-in methods and functions you can use to
manipulate a dictionary in Python.
Function Description
len(dict) Returns the total length of the dictionary (the number of item
dictionary)
The next table is a presentation of the methods that you can use to manipulate
the elements of a dictionary:
Methods Description
dict.fromkeys(
You cannot enter more than one key in a dictionary. This means you cannot
have duplicate keys in a single dictionary.
Unlike values, keys are immutable. This means you can use types such as
strings, tuples, and strings as keys, but you cannot define a key using
something like [“Key”).
Data type
To figure which data type you should use, you are going to need to look at
the application and determine how it is going to run with each data type.
In comparing two lists to see if there is anything similar between the two of
them, you are going to have to go through each element individually, but this
is going to take up too much of your time and you may end up forgetting
what you are trying to do.
This method should only be used on smaller lists. There is another method
that you can use for lists that have more entries so that it is more efficient and
less time consuming.
A set is going to help speed up the process when you are using it as a
function.
A dictionary is not going to be recommended when you are using a set since
sets are mutable, but a tuple is going to be the perfect choice for you.
Dictionaries that have to be used are going to convert your objects into the
tuple or list so that you can do the proper operation so that it can be converted
back to the form that it should be in for the program.
Methods such as this are going to be faster than attempting to duplicate the
string.
Chapter 19: Organization of the Python Code
Before we get into learning how to do some of the codes that you will need
for the rest of this guidebook, you need to learn a few of the different parts
that come with the Python code. The good news is, if this is the first coding
language you have worked with, then you will be pleasantly surprised by how
easy all the parts are in writing the code, and how much sense they can all
make.
The different parts that come with the Python code are pretty easy to use.
You will be able to find these in most of the codes that you decide to write in
Python. You can add several of them in, take some out, and make them work
for what you would like to see done inside your code. Let’s explore some of
the different most basic aspects that can come with your code writing, and
how to get started with it with your own codes right away!
Python Keywords
There are several different types of keywords that you can work with, and
you need to make sure that you are using them properly. They are supposed
to tell the compiler what you want it to do. If you place the keywords in the
wrong places, the compiler will be able to see the command but won’t know
how it is supposed to execute it. Basically, if you place the keyword into the
wrong place inside of your code, it is going to give you an error.
These keywords are there to tell the compiler what you would like it to do, so
you must make sure that you are placing them in the right spot and using
them in spots where they are needed. Make sure that you take the time to
learn more about these Python keywords and you know which ones you
should use. These keywords are going to come with the Python library, a
powerful tool that is going to help you to see some great results when you
write out your own codes.
Naming Your Identifiers
The next thing that we need to look at when it comes to the Python code are
the identifiers. Just like with the keywords, there are a lot of different
identifiers that you can choose from to add into your code as well. There are
a variety of names they come under, and each one will work in a different
manner. We will discuss each of these as we go along. Some of the names
that you may see them under include classes, variables, entities, and
functions.
The naming rules of these identifiers will be very important. They all follow
the same rules. But if you don’t name them properly, you will end up with the
compiler not bringing out the right part of the code, or encounter some other
issues along the way.
The first rule to remember is when you name these identifiers. You have
many options when you are naming your identifiers. For example, you can
rely on both uppercase and lowercase letters with naming, as well as any
number and the underscore symbol. You can also combine any of these
together. One thing to remember here is that you can’t start the name with a
number and spaces shouldn’t exist between the words that you write out. For
example, you can’t write out “3words” as a name, but you can write out
“words3” or “threewords.” Always check to ensure that you haven’t used any
of the keywords that we discussed above or you will end up with an error.
When you pick out the identifier name, you can follow the rules above, and
try to pick out a name that you can remember. Later on, when writing the
code, you will need to pull it back up, and if you give it a name that is
difficult to remember, you could run into problems or raise errors because
things aren’t showing up the way that you want them to. Outside of these
rules, you will be fine naming the identifiers anything that you want.
Control Flow with Python
The control flow in this language can be important. This control flow is there
to ensure that you write out the code the proper way. There are some types of
strings in your code that you may want to write out so that the compiler can
read them the right way. But if you write out the string in the wrong manner,
you are going to end up with errors in the system. We will take a look at
many codes in this guidebook that follow the right control flow for this
language, which can make it easier to know what you need to get done and
how you can write out codes in this language.
Working with Statements
Next on the list is the statements in Python. These statements are going to be
strings of code that you can write out, and things in the code that you want
the compiler to list out on the string. While you are writing out some of your
codes, you are giving the compiler instructions on what you would like it to
do.
Writing Comments in Your Code
At some point in your code writing, there may be a time when you will write
out an explanation or a little note inside of the code, explaining what you are
doing with that part of the code. These are little notes that other
programmers, as well as yourself, can look at in the code and then understand
what is happening. You may even use them to write out the title of the code
at the top. It is something that you can leave out of the code if you would
like, but it is a great way for you to explain what is going on inside the code.
Any of the comments that you want to write out in Python will be done with
the # symbol in front of it. So, you could write out something like #this is my
comment, and then press enter to go to the next line. This is going to let the
compiler know that you are writing a comment in this place, and that it
should skip that line of code and move on to the rest.
As you write through your code, you are able to add in as many of these
comments as you would like or need, as long as they are useful. The other
programmers who look through the code will benefit from them. However,
proper coding etiquette asks you to not put in any more comments than are
absolutely necessary to ensure that the code remains readable.
Exploring Variables
The next part of the code that we can explore is the variables. These are
pretty common in the code that you are writing. These variables are there to
help store the values that you add into the code, which can keep these
different parts as organized and nice as possible.
You can add in the values to the right of the variables just by using the equal
sign to make sure the right value is assigned to your variables. If you would
like, it is also possible to assign two or more values to the same variable,
simply by adding in those equal signs as well. Variables are pretty common
in the codes that you will write in this guidebook, and as you go through
some of the examples of codes, you will be able to see many incidences of
them.
Working with Operators
There are assignment operators that will assign a specific value to your
variable so that the compiler knows how to treat this. There are also
comparison operators that will allow you to look at a few different pieces of
code and then determine if they are similar or not and how the computer
should react based on that information.
Many times these operators are going to show up in a lot of different parts of
your code, and you may not even realize that you are using them. There are
assignment operators, Boolean value operators, and even various arithmetic
operators. All of these can be useful for adding in a little more strength to
your code.
While there are many different parts that need to come with writing your own
codes in Python, you will quickly be able to expand on this and see some
great results. The code is meant to be simple, but you must make sure that
you are able to keep everything in line and use the right parts of the code, to
make sure that the compiler will understand all the commands that you give
to it.
Working with Variables in this Language
The next thing that we need to look at is the importance of the variable. These
variables are important parts of Python that you need to learn because they
will be there to store a part of the code onto the computer so that the compiler
has a chance to find them later on. If the variables aren’t listed the right way,
the compiler can run into trouble finding the right parts, and you can end up
with a mess in your code.
The first thing that we need to focus on here is how to give a value to our
variable. To ensure that the variables are going to work in the proper manner
with the code, you need to assign some sort of value over to them. If you
don’t stop and work on this step, then you can do a variable, but it is just an
empty space stored in the memory of your computer. Assigning a value to the
variable is a much better option here.
If the variable does get some kind of value assigned to it, then the compiler
can go to that spot on the computer, pull it out, and knows how it is supposed
to react. When it comes to assigning a value to your variable, there are three
variables that you may want to work with. The variable type is going to
influence what kind of value you want to assign there. The different types of
variables that are available for you to pick from include:
Float: this would include numbers like 3.14 and so on.
String: this is going to be like a statement where you could write out
something like “Thank you for visiting my page!” or another similar
phrase.
Whole number: this would be any of the other numbers that you
would use that do not have a decimal point.
When you are working in Python, recognize that it isn’t necessary to list out
any kind of declaration to get that memory space reserved. This is something
that will automatically happen right after you assign the right value over to
your variable. If you want to double-check and test to see if this
automatically happens, all you need to do is use the equal sign. This assigns
the right value to the right variable, and is pretty easy to work with.
Now that we have some idea of what these variables are and why they are so
important to the code working, it is time to look at a few examples of this.
Some examples of how you can assign a value over to your variable, without
any problems at all, will include the following
x = 12 #this is an example of an integer assignment
pi = 3.14 #this is an example of a floating point assignment
customer name = John Doe #this is an example of a string assignment
Another thing that you can do here is to have two or more values that go to
the same variable. Just make sure that each part has an equal sign so they
know where they are associated. So writing out something like a = b = c = 1
would be just fine in your code because each of the variables would be equal
to one when you write out the code.
The Functions in Python
We also need to spend some time looking at the functions found in Python.
These functions are basically going to be some parts of the code that you are
able to reuse and can help to finish off the actions inside your code. They are
going to be effective when you want to write out the code, but you want to
make sure that you are not wasting space inside the code. Functions can be
really fun to use in Python, and can really benefit you as you work on
different codes.
When you are ready to start on a code, you must make sure that you take the
time to actually define your function. Only after the function has been
defined will you be able to get it to work with the compiler. You do get the
choice to call that function up with your prompt on Python, or you can
choose to call it up from another function.
Python as an Object-Oriented Language
The last thing that we need to take a look at is the idea of an object-oriented
language. These are pretty new inside coding languages, and it was
something that was developed as a way to make the languages easier. Older
languages are often missing out on this part, and this could result in codes
moving around, functions pulling out the right things, and just a mess. This is
often why many programmers decided not to learn the old languages at all;
they were worried that it would just take too long and be too difficult to get it
right.
These OOP languages are designed to make life easier for every programmer,
and they cut out the issues that even experienced programmers were
experiencing when they try to write out a new code. While there are many
older languages that aren’t really made to handle this, which can make things
difficult if you’re a coding novice, Python, and other OOP languages aim to
avoid this issue in the first place.
Why are the older programming languages so hard with this idea, and why do
they seem to cause a lot of issues for new programmers? This is often
because the older coding languages would rely on the procedural approach.
This could still get the coding job done for the programmer, but there were
flaws that came up that meant that only a few programmers who were really
dedicated could get the work done.
When you limit the number of people who are willing to put the work in to
learn and use a coding language, this really limits efficiency, creativity, and
more. But when you work with an OOP language like Python, one that has
gotten rid of a lot of these flaws, you introduce more people to coding, and
this opens up a whole new world of possibilities of what can be done with
that language.
Since the procedural approach was really hard and turned a lot of beginners,
and even more advanced coders away, the idea of OOP started to go through
development. Programmers of all kinds wanted to find a different way to
code some of the basics, as well as some things that are more difficult. This
not only made their job easier but ensured that beginners would come in as
well.
Chapter 20: Get to Know How to Program-A
Closer Look at the Tkinter Tutorial
The GUI gives very good feedback on elements of your code. You can
visually see the changes you affect your program and this will give you the
proper motivation to develop your coding skill more in this language.
Spotting mistakes in your code are also easy because the visual nature of your
program that provides enough information to know where to rectify.
Tkinter is simple and easy to understand, plus it’s already in the Python
library so you can immediately begin adding GUI elements to your
applications.
Advantages of Tkinter
Tkinter has been around for a very long time and therefore
more portable than any other GUI library.
Widget Description
Menu A list that appears when users click the menu button widget
Radiobutton Buttons that allow user to select a single option from several. They ca
deselected
Start off by making a simple window that contains very few lines of code.
Below is capture of the code.
Code Output:
Widgets
Label Widget
✓ Used to display text in a window
The main window was a rather simple code. Now you can add some text to
your window using the Label widget.
syntax
y = Label(master, options, …)
Code output:
We can go further and display more lines rather than just a single one like so
For instance:
The argument or option to pack() (Lines 8 & 9) method ‘left’ means that the
label will be pushed as far left as possible in the main window.
Frame Widget
✓ A container to hold other widgets. Used to organize widgets in a window
If you want to group a set of widgets together and move them around the
main window, separate from another set of widgets, you can contain each of
these sets in different frames.
syntax
Button Widget
syntax
Code Output:
The showinfo() (Line 7) method takes two arguments in this case: the title of
the window and the information to be displayed.
The Button Widget takes three arguments in this case: the first argument is
the parent window, then the text to be displayed on the button and lastly the
command to execute or function to call once the button is clicked.
tkinter.messagebox.showinfo(title, message)
Quit Button
We can add a button to quit our application by using the root widget’s
function/command destroy() (Line 11) as our callback function.
Entry Widget
✓ The entry widget appears as a rectangular area where users can input a
single line of text into the GUI.
This widget can be used to obtain a personal username for instance or obtain
a value like kilograms to be converted to pounds. To confirm entry, a button
is clicked which gets the value that has been input and is stored in a variable
to be processed before displaying of results. The entry’s get() method (Line
7) is used here to do just that.
syntax
syntax
y = Radiobutton(master, option, …)
Options – They are used to further enhance the widget by adding details.
Radio buttons are used along with classes provided in tkinter like IntVar
and StringVar. Each button carries a value that when selected, stores its value
in the object (IntVar or StringVar). For the StringVar, the value will be a
string. In the illustration below, the “Accept” button will display a message
box showing the selection made while picking a musical instrument.
Code Output:
So Line 21 creates an object of StringVar called radioButtonVar. Line 23
then calls the object’s set method to store a default value i.e. “Piano”.
Lines 27, 28, and 29 create the Radio button widgets. The argument
variable = radioButtonVar (in line 27) associates the Radio button with
the radioButtonVar object. The argument value = ”Piano” (in line 27)
assigns the string “Piano” to this Radio button. So, every time you select
the Radio button, the string “Piano” is stored in the radioButtonVar
object. The same goes for all the radio buttons.
Check buttons also can be selected or deselected but they do not work like
radio buttons where selections are mutually exclusive. They allow
multiple selections in a given list of options.
syntax
y = Checkbutton(master, option, …)
Master – This represents the parent window
Options – They are used to further enhance the widget by adding details.
We used the StringVar object in radio buttons. Let us use the IntVar object
rather, on the check buttons. Unlike radio buttons, however, each check
button is associated with a different IntVar object. When a check button is
selected, the value of the object holds the value 1 while when deselected
holds the value of 0.
Below is an illustration.
Code Output:
Canvas Widget
For the purpose of drawing, the canvas widget has methods with the word
Create for example, create_line(), create_oval(),create_rectangle() etc.
Source Code:
So as you can see, the number of arguments the method create_rectangle()
has in the code are five (Line 7). The first two arguments (10,50) describe the
starting coordinates in the x-y plane from where the rectangle will be plotted.
Then the next two (150,100) describe the length and the width of the
rectangle. Finally, the last argument is to fill the shape with color; in this case
“purple.”
Notice the origin point (0,0) is the top left of the window.
Source Code:
For the last one, you can also make ovals with the same procedure.
Source Code:
The first arguments to the method create_oval() (Line 7), represent the left
top (x0, y0) coordinate of the rectangle from which the oval was derived and
the last two represent the bottom right (x1,y1) coordinates.
Scale Widget
✓ A scale widget provides a graphical slider for the user to select a specific
value
syntax
y = Scale(master, option, …)
Master – This represents the parent window
Options – They are used to further enhance the widget by adding details.
Sliders are extremely useful when a finite number of inputs is allowed.
Turning up a volume knob for example has a fixed number of values to
choose from. A simple slider is shown below.
Source Code:
Other than Tkinter, there are several other graphical user interface that you
can use on your PC. We will go through the list of these GUIs and compare
them to Tkinter. As a beginner who wants to make your way into the
programming world, you should know other GUIs that are easy to use. It is
important to stay informed. Here is a list of other GUI frameworks that can
work on either your Windows, Mac, or another operating system.
1. PySide. For one, Pyside is free. How does it work? Pyside has a lot of
widgets which makes it possible to create a graphic user interface. It is
similar to Java when it comes to the naming of classes, properties, and
functions. Every new word that makes up a name in this program is
capitalized, this is because it uses camel case.
This program is an open source. What does this mean? An open source is free
for anyone to use. The person who wants to use it can look at it and modify it
into what they want to work with. It is also a cross-platform tool kit. This
means that this program can run on various platforms without any
modifications been made to it. These are other graphical user interface that
you can find which operate with the Python program. The difference between
these programs and Tkinter is that, it is already installed, the other softwares
have to be installed. As you advance in your programming skills you should
know more. Make every effort to learn what is in other GUIs and know how
they differ, know how they will work on your interface and the difference
they will make. Why are GUIs important for beginners?
Through them you can be able to copy / cut and paste or drag and
drop you are able to exchange information from one software to
another.
Due to the fact that they use up a lot of memory and processing
power, it slows you down when you want to use a command-line
interface if you are an expert user.
Experienced users may find it irritating if the simple tasks they want
to carry out require a number of operations.
When you reach the stage where you want to try out other graphical
user interface on Python, you may be wondering what you should
look out for. Here are the characteristics of a good user interface.
The words used are easy to understand and they are relevant to the
user.
You have the read the book, now it is time to act. Put it into practice and
ready yourself in becoming a credible programmer. Start using Python to
develop software. Even though this book has been written for the reader who
is taking the first steps in learning, it doesn’t mean your thirst for knowledge
stops here. There is so much more to learn and a lot more to find out. Get out
there and ask questions, read tutorials. Let this eBook push you towards
knowing more. However, take it one step at a time; do not overwhelm
yourself with tasks.
Chapter 21: Python Statements and Syntax
In order to create a program, you must write your source code using a
programming language. How can you write one? Well, here are a few things
you need to know.
Statements
In the example, you instruct the program or computer to display the text
Hello World. A statement contains elements or internal components that you
need to place in order for the computer to perform an instruction. In the
example, you have used two elements. The first one is a keyword or
command, which is print. The second one is an argument or parameter, which
the keyword needs to receive in order for it to function.
Continuous spaces and tabs are generally ignored in Python. Even if you
leave a blank line in Python, Python's parser will just ignore it and skip to the
next line. You can try that in the interpreter.
Even if you try putting a lot of spaces between a keyword and its argument,
Python will not give you any error messages. For example: >>> print ("Hello
World")
Hello World
>>>
New Line
Explicit Joining
Implicit Joining
Aside from using a backslash in order to perform explicit joining, there are
some ways to join a statement with multiple ‘physical lines'. As of now, you
do not need to learn it, but here is an example: name_of_days = ['Monday',
'Tuesday',
'Saturday', 'Sunday']
Since the code is giving out a set of values and the line is not yet closed since
the programmer has not provided the closing square bracket (]), Python has
allowed to let the programmer use the next line and combine it to the
statement. Below is another example: >>> print ("Hello World",
>>>
Open Source – The author of Python has given the rights to third party users
to change and distribute the software for any purpose.
High-levelled – Really advanced programming language that has a multitude
of applications
White Spaced – Uses spaces and tabs to delaminate information (ie. divide
information into layers)
Python is great for programmers as the built-in data structures and easy
debugging feedback makes coding and programming a dream come true. The
debugging response occurs at source level and causes an "exception" or a
"stack trace" when an error is identified. This allows the programmer to
easily identify and correct the problem in the code.
Chapter 22: Python Loops
Input is one of the most useful operations you’ll find yourself using at first
when you program. But this is still only scratching the surface of what you’ll
be able to do as you learn more and more Python.
Another powerful tool for instance is to use loops. Loops essentially allow a
piece of code to keep running and repeating itself.
There are two different types of loops, which operate based on different
conditions. One of the most common examples of a loop for example is
the‘While’ loop. The clue as to how this loop works is very much in the
name. Basically, a while loop runs while something is true.
Note that if we hadn’t included the line Number = Number + 1 then the loop
would have run forever!
The other type of loop we can use is the‘For’ loop. For basically performs
some kind of counting job and finishes once that job is over. For example,
this: for Counting in range(100):
print(Counting)
Does the same thing that the previous loop did– counts to one hundred! But
we could also do something else interesting– for example we could do this:
for Counting in range(10, 100):
print(Counting)
And thereby count from 10 to 100!
What else can you do with loops? Well, one option is to‘break’ the loop. This
simply terminates the loop early and then continues with the rest of the
program. This can be used in the‘while’ and‘for’ loops and is something
we’ll come across later on…
Another one that will come in handy is‘continue’. This works similarly to
the‘break’ statement, except that it simply begins the loop again from the
start. And if you were‘For’ loop, then the condition that you were testing
would also be reset. Again, it will all make perfect sense soon…
If, Then Statements
At this point we’ve already gone over a lot of the most important components
of any programming language. Variable, loops and operations are all crucial
for any program and inputs also play an important role a lot of the time.
We’ve talked an awful lot of theory at this point so perhaps it’s time for us to
make our first game! It’s not going to be that much fun, seeing as you’ll
know the answer– but you can get your friends to play it to impress them
with your coding know-how (unfortunately, it’s still not all that fun even
then!).
The game is simply going to get the player to guess the number it is thinking
of and will then give clues to help them get there if they get it wrong.
CorrectNumber = 16
while True:
GuessedNumber = int(input("Guess the number I'm thinking of!")) if
GuessedNumber == CorrectNumber: print("Correct!") break
elif GuessedNumber < CorrectNumber: print("Too low!") continue
elif GuessedNumber > CorrectNumber: print("Too high!") continue
print("You WIN!!!")
Nesting Ifs and Loops
It’s also possible to‘nest’ your ifs and your loops in order to make even more
elaborate programs that test multiple different conditions.
We already did this once when we put the‘if’ inside the loop. However we
can also put ifs inside ifs inside ifs if we want!
Chapter 23: Thinking Like a Programmer Part One
Let’s take a breather and have a moment to discuss the power of conditional
statements (another term for‘if’ and‘then’) and how it affects programming in
Python– as well as programming in general.
Essentially, these kinds of statements are going to form the backbone of your
programming and will be what you use to inject logic into your programs.
We’ll learn a little about adding graphics and doing other fancy things later–
but ultimately the logic is what makes a program tick.
Pseudocode
Something else you need to learn about programming at this early stage, is
that probably 90% of it is done away from the computer. What do I mean by
that? Simply that you’ll work out how you’re going to apply your logic when
you’re washing up or when you’re driving. All you do when you’re sitting
down is to execute that idea by writing it down.
For this, you’ll find something called‘pseudocode’ comes in handy. What this
basically is is a kind of‘mental shorthand’ for your programming that allows
you to wrestle with ideas without needing to write actual code. It’s also
useful for communicating with other coders, for grasping concepts and for
explaining code to people who use other languages like Java.
Take a look at this code and hopefully you should have an idea of how it
works and how it would enable a character to walk and jump when on a flat
surface. I’ve used bits of formatting from Java, BASIC and Python and also
written some plain English in there– but it’s intuitive to understand even if
you have zero coding knowledge.
This is going to come in handy when you’re dreaming up your next big app
idea and it will also help us explain concepts further in this book!
I’m actually going to demonstrate this right now by teaching you a new
concept using pseudocode! That concept is‘and’ – another useful command
for writing conditional statements. AND basically tests two conditions and
only runs if both of them are true.
For instance:
Just to give you a little background too, it can be very interesting and useful
to get an understanding of what’s actually happening behind the scenes when
you create these kinds of conditional statements in your code.
Computers understand binary code as‘on’ and‘off’ where 0 means off and 1
means on (take a look at the power button on your device– it’s a zero with a
one through it!). Your code then is turning on and off switches in order to
redirect electricity and when you use conditional statements, this creates what
is known as a logic gate.
But from the battery to the bulb, we have two parallel wires and two‘routes’
that the electricity can take to light it. If we put a switch on both wires, then
the bulk will light up as long as one of those switches is in the‘ON’ position.
We now have our‘OR’ statement!
But what if we got rid of the second wire and instead put one switch after
another? Now the electricity has to travel through both in order to light our
bulb…
One wire with just one switch? Well, that’s just good old‘IF’.
Advanced Variables
This time we’re looking at variables again– but we’re going to see some of
the more complicated things we can do with them…
To start with, let’s take a look at how we can chop up our strings!
For instance: print(MyString[5]) will show the fifth letter of a string and
print(MyString[0:5]) will print the first letters from your string. Likewise,
you can say print(MyString[3:10]) and print characters three to number 10!
This is where using something like a for loop can be combined with other
tricks to do something interesting.
Modules, Graphics and More
So what does this have to do with extending your power? So far all it has
done is saved you a lot of typing…
Well, the beauty of modules with local variables is that you can use them
anywhere in your code and even grab them from one program and insert them
into another. These work in a modular fashion and that means you can be
much more efficient in the way you code– even lifting functions straight from
other pieces of code in order to make use of their algorithms and sequences!
And Python is designed to make this as easy as possible thanks to its use of
modules.
You see, when you create new files in Python, you’re really creating new
modules. These modules can then be treated as though they were functions
within your own code!
Let’s take a look at the‘game’ we made earlier that let our player calculate the
number being thought of. The problem with this game was that you couldn’t
play– because you already knew what the answer was from having made the
game!
And now you have your random number! Notice that this function is letting
us pass two different variables to it– there’s no limit to the amount of data
that can be passed and transformed using functions.
So let’s use this in our game! It’s easy: from random import randint
CorrectNumber = randint(0,10)
while True:
GuessedNumber = int(input("Guess the number I'm thinking of between
0-10!")) if GuessedNumber == CorrectNumber: print("Correct!") break
elif GuessedNumber < CorrectNumber: print("Too low!")
continue
elif GuessedNumber > CorrectNumber: print("Too high!") continue
print("You WIN!!!")
You can now play this game as much as you like. See if you can work out
what the fastest way to get to the answer is every time!
Installing New Modules
To find and install new modules for Python, you simply need to know what
you want to do and then find the modules that can help you accomplish that
task!
The good news is that installing modules is easy enough for the most part.
Normally they’re called‘packages’ and while they’ll be complicated to work
out in some cases, for the most part the creators have given them their own
installation files just like any other program for windows!
Earlier I discussed a little about the way a programmer thinks in logic and
how they will‘program’ even when they’re away from the computer!
This is why it’s perfectly acceptable to use open-source modules for your
code and in fact encouraged by the community. You can find tons of free
stuff on sites like GitHub and this way you can start coding like a pro in a
record amount of time. You’re not reinventing the wheel– rather you’re
letting a legion of talented programmers help you accomplish goals you never
could on your own!
So when you want to know how to do something that wasn’t covered in this
book, that’s what you do: you look for the command or module that can do it.
Only if it isn’t already there do you have to come up with the solution
yourself.
This is also just the best way to learn. No programmer remembers every
single line of code from every single language they know! Instead, they just
copy and paste and lift and share each time they need to do something.
Half of programming is just browsing Google and copying and pasting. The
rest is thinking about logical solutions to problems (the fun bit) and
occasionally searching for bugs and typos (the not-so-fun bit).
That way, you’ll learn what you need as you need it. Make this something
really simple to start with, but something that you also want to turn into a
reality and that will motivate you to keep going.
And the first time you successfully find yourself asking a question in a forum
and borrowing someone’s answers… well that’s when you know you’re a
real programmer!
There’s a huge amount more to learn but now you have the knowledge and
the tools to start learning it yourself. Have fun!
Setting Up PyCharm
Installation is super easy: just click on the .exe you’ve downloaded and then
set a folder to install the files to. With that done, it should execute on its own
and install everything for you.
Making a Basic Python Game: Hangman
What is the best way to learn a new subject? One theory that is very popular
among learning gurus is that the best approach is to look at something you’d
like to make and then make it.
This is much better than trying to learn without any structure because it gives
you a goal and something to work toward. Rather than learning code in a
random order and trying to remember everything in a very abstract sense,
creating something that is going to be actually useful or fun gives you a
context and informs which things you need to learn first.
For nowthough, let’s apply this principle with a very basic game of hangman.
As we try and introduce some basic features for our game, we’ll be going
through a lot of the things we’ve learned so far but putting them into practical
application. At the same time, we’ll find that we need more and more tools
and this will allow us to extend our toolset. So how is this going to work…
read on and find out!
Tidying Up With Modules and Loops
But in order for that to be of any use, we also want our guesses to impact on
our lives system, so that we can’t just keep guessing indefinitely until all of
the letters are gone! It would also be good to see some kind of feedback…
So to start with, let’s introduce our‘Lives’ variable and start removing points
each time that we have an attempt…
We can do this simply by using Lives = Lives– 1 each time the person
guesses.
Each time the player guesses one of the letters correctly, it will be added to
that reference word. Each time they fail to guess correctly, it will not be
added. We can then compare the two words in order to draw the new image
and fill in the blanks as they are guessed correctly…
So the following bit of code isn’t introducing anything new that you
shouldn’t already be familiar with. However, you might well find that it is
somewhat confusing at first– at this point we’re starting to introduce a whole
lot of different concepts into a single piece of code and each one will rely on
the others to work effectively…
So:
word = "moose"
print(word[2])
Returns‘o’.
If there’s a match, then the‘DrawSpaces’ module will draw the letter that we
correctly guessed. If there’s no match, then it will continue to show a blank
space!
One more thing: note that the‘\n’ indicates a new line and we can use this to
keep our game nice and tidy!
At the moment, our game only gives us one attempt. So it’s time we put that
module we created to good use by creating a loop that will let us keep trying
until we guess correctly or we are out of lives…
One obvious way would be to create another much larger string, which would
construct our letters in order. Or alternatively, we could try and make our
LetterGuess string organized in the correct order, which would require a fair
amount of effort.
This is where we need to engage in a little lateral thinking though and this is
a perfect example of the kind of fun thinking you can end up doing when
you’re a programmer!
How about you try and work it out for yourself a second and then read on
once you’ve come up with an idea…
See, the way that I would approach this, is to check the string we’re printing
for blank spaces (the underscore character). These are eradicated each time
we get a correct answer, so if we have filled out every letter correctly, there
will be no more blank spaces left!
Winner = 0
if Winner == 1:
print("\n You Win!")
else:
print("\n You Lose!")
Notice we have one more bit of code here:‘if not in’. This is literally the
opposite of the‘if in’ line that we saw earlier. Once again, it reads just like
English and is entirely intuitive for us to know what it means. That’s just one
more reason that people love Python!
Some Lessons to Take Away
You can try entering this in yourself, or you can just copy and paste this code
for now. Either way, you’ll then be able to try tweaking things yourself or
changing things to see how it affects the way the game performs.
This is also generally an example of good coding practice. We’ve done a lot
with very few lines of code, which is partly thanks to the beauty of Python
and partly thanks to the way that our code has been arranged. If you collapse
the‘DrawSpaces’ module and the loops, you’ll be left with something really
rather compact and elegant: from random import randint
Winner = 0
if Winner == 1:
print("\n You Win!")
else:
print("\n You Lose!") That is the beauty of Python!
The other reason that this game can be considered a good example of correct
coding practice, is that the way it has been written means that we can now
very easily and quickly grow our game by adding new words to the list. Had
you created this game and released it on the Android app store, you would
now be able to very easily apply updates by replacing the words or adding
entirely new ones.
Adding More Features and Functions
Were we to stop there, we would already have a fairly decent little game to
play and we would have learned a few useful lessons.
But it’s by pushing onward and honing and refining our game that we’ll be
able to learn even more advanced skills!
The first thing we need to do, is to prevent our user from entering
too many characters at once. That’s easy enough to do using code
that we’ve used a few times at this point: while Lives > 0:
print(DrawSpaces(Word, ReferenceWord), "\n")
if "_" not in DrawSpaces(Word, ReferenceWord):
Winner = 1
break
print("Lives: ", Lives, "\n", "\n")
LetterGuess = input("Guess a letter: ")
if len(LetterGuess) > 1:
print("Enter one character at a time! \n")
else:
Lives = Lives - 1
if LetterGuess in Word:
print("Got one!")
ReferenceWord = ReferenceWord + LetterGuess
else:
print("Nope!")
Likewise, we could also prevent our player from guessing the same
letter more than once: while Lives > 0:
print(DrawSpaces(Word, ReferenceWord), "\n")
if "_" not in DrawSpaces(Word, ReferenceWord):
Winner = 1
break
print("Lives: ", Lives, "\n", "\n")
LetterGuess = input("Guess a letter: ")
if len(LetterGuess) > 1:
print("Enter one character at a time! \n")
elif LetterGuess in ReferenceWord:
print("Already guessed! \n")
else:
Lives = Lives - 1
if LetterGuess in Word:
print("Got one!")
ReferenceWord = ReferenceWord + LetterGuess
else:
print("Nope!")
And we are reusing a previously visited line of code again here too, this
time‘Elif’ – which if you recall essentially means‘Else, If’.
Another safety precaution to make our game a little more fun, would be if we
were to
Adding Additional Modules
But right now our game only runs inside the shell and this doesn’t look very
professional. It also means that you couldn’t easily share it with friends or
sell it.
And it can be a little fiddly. Fortunately, I’m here to guide you through it!
Installing Additional Modules
Specifically, you need to find the closest version of PyGame for your version
of Python. So as I am running Python 3.6, the closest version is PyGamefor
Python 3.2. I also need to ensure that I download the x32 or x64 bit version,
depending on which Python installation and which PC I’m running.
Once you have the download file (.msi), you can click on it and it will install
automatically. However, you need to choose the location where Python is
installed on your machine. Choose the base folder and it will install the files
in the right places.
If all goes to plan, then restart PyCharm. Now type: import pygame
pygame.init
Problem is, there might still be. And that’s where things get really fiddly and
unfortunately you start to see one of the big drawbacks of Python. Yes, we
have raved about Python a lot in this book and there’s lots to love. This is a
programming language that is at once beautiful, simple and a fantastic
introduction to programming and to object oriented programming in
particular. It’s also incredibly versatile and can be made to create a wide
range of different tools.
BUT it is also a bit fragmented. Python is split down the middle right now
with some people still using Python 2.7 and many more still using Python
3.4. Many have ignored the latest version (3.6), or chosen to stick with
Python 2.7 owing to not all modules yet supporting 3.4.
That is to say, that if you have built a program that entirely relies on a module
that only supports 2.7, then you wouldn’t want to make the switch to 3.6 even
though it has many superior qualities!
So what do we do?
There’s a good chance that your version of PyGamewon’t work with your
version of Python and the reason is that you are running PyGame3.2 for
Python 3.6. And if you look at PyGame.org, it hasn’t been updated since
2009.
This leaves you with two options. Option one is to uninstall Python (click on
the same installation. msifile that you clicked on to install it). Now you’re
going to download Python 2.7 in the 32bit version and then install
PyGamefor that iteration. You’ll then need to open up PyCharm and edit your
code to replace your lines of code that are for the Python 3 (e.g. Print(“”)
becomes Print“”). You’ll also need to update the path, so that PyCharmknows
where to find Python for interpreting your code. You’ll find this by heading
to‘File > Settings’ and then choosing Project: Hangman (or whatever you
called the file) and Project Interpreter. The line along the top on the right,
should be the path of your Python installation. Once you change this, you
should find that PyCharmworks like a… charm (sorry, I had to).
This all might seem a bit fiddly but it is a useful learning curve that will show
you a little more about the interaction between Python and PyCharm – and
how the different versions will affect your experience.
Download the most relevant file. Right now that file is‘pygame-1.9.3-cp36-
pc36m-win_amd64.whl. If you’re reading this some timein the future and
you’re running a different version of Python, then just look for the most
relevant and up-to-date file.
Now take that file and drop it in your Python root folder, in the sub-directory
called‘Scripts’. Hold shift and right click anywhere within that folder. This
will then allow you to open up a new command line in that directory. Do that
and then type: pip install pygame-1.9.3-cp36-pc36m-win_amd64.whl.
If all goes to plan, then it will install this latest version onto your drive in the
correct folder. Failing that, you might need to update your‘pip’, which is a
package manager of sorts for easy installation.
Again, this is a very messy process and might be a little off-putting but it’s
also good practice and these kinds of skills will help you out immensely
going forward.
Creating an Executable File
Wow, would you look at how far we’ve come! We’ve gone from having a
text program that runs only in a shell, to having a full-blown game that works
just like any other. It opens in a separate window, draws graphics to the
screen and is generally rather fully-functional!
But if you wanted to share or even sell a game like this, how could you?
Right now, someone would need to have Python installed on their computer
and then they would need to paste all the code into PyCharm…
To do this then, we need to turn our code into a single executable. The good
news is that there is a piece of software that will allow us to do this and that
can package everything from our graphical elements to our library
dependencies all into one file!
Better yet, you can install it very simply by typing pip install pyinstaller into
the command line! Do that and the entire thing will download and be ready to
go!
It doesn’t work with Python 3.6 at the time of writing. As of 22 days ago, the
creators said that they were working to provide support, so this is something
that we’ll see very soon.
But in the meantime, you’re going to have to roll back to at least Python 3.5
and you may wish to do this whole thing in Python 2.7 just to be on the safe
side…
Aaand of course you also need to install the relevant version of Pygame using
the MSI or using Pip. Pip is recommended because it will automatically
detect and uninstall the other versions you might have installed.
That said, it doesn’t hurt to first try and remove the existing installation of
PyGameyourself, which you can do by typing‘pip uninstall pygame’ from the
command line!
From here, you can now create an EXE of your game! To do that, all you
need to do is to enter into pip again and then use the line: pyinstaller.exe --
onefile --windowed
"C:\Users\rushd\PycharmProjects\Hangman\Hangman.py" – replacing the
file name and location with your own.
You might have difficulties if you are missing a working win32 file and there
are various other things that can go wrong here too. Unfortunately, you’ll just
have to chase these up and again, this is one of the things that is a little more
frustrating about using python. Like I said before, it’s a fantastic language but
not without its limitations and frustrations!
Games like Civilizationhave actually been built using this method though.
These provide executables that install all of the necessary modules and
libraries as well as the python framework onto a given user’s computer. That
way, said user is then able to launch the app like any other program without
needing any prior knowledge of what Python is. Civ5 and 6 are pretty
successful (you’ve probably heard of them, at least!) and so this just goes to
show us that Python can be used to have a real commercial hit. The sky really
is the limit!
More Ways to Distribute Your Apps
Another way you can go about distributing your creations– because of course
you are going to want to share them– is to simply release them as .py files.
As long as the user has Python installed, they can click on the .pyfile and it
will open a command line and the window to run the app. You can then
provide instructions and help on installing Python for those users who don’t
have it already.
If you want to make an .exe but eventually decide against using PyInstaller,
there are many others out there like CXFreeze and like Py2Exe. These all
work well depending on how your environment is set up. Unfortunately
though, they all do also contain a number of stumbling blocks along the way,
depending on the versions that you have installed etc.
For these reasons, many people choose to stick with Python 2.7 simply
because it has the most support. This will, for the most part, make your life
considerably easier and simplify the process of building and exporting games
and other apps. It’s really up to you though!
Chapter 25: Thinking Like a Programmer Part 3
It’s time for another of our‘thinking like a programmer’ interludes.
At this point, you now know how to make a game, you’ve built a little
animation and you’ve created a shopping list app. You’ve even seen how to
export these to executables that you can then distribute to other users!
But what if you wanted to make something more practical… like a note-
taking tool or a calculator that performs a specific job?
This is where you need to start getting a little more creative and combining
the things we’ve already done in unique ways. You can, for example,
combine several of these different things all into one program and that way
build yourself a kind of word processor or note taker. This could let you
select the file you want from a list and then edit it before saving the changes.
And this is one of the main uses for something like Python. It’s time to stop
thinking purely in terms of how you can make games in order to sell them
and make money, or how to be the next‘Microsoft’ with your own massive
hit software package. While it’s possible, these eventualities are also
relatively rare and unlikely!
So instead, think about how you can use Python to build apps and utilities for
your own benefit. This is what a lot of programmers use coding for– to help
themselves get their work done more quickly and to solve unique problems.
We’ve seen already that a coder will generally not write out a piece of code if
they can possibly avoid it. Instead, they’ll look for an existing module or
library that someone else has written and they’ll refer to that. This will save
them a lot of time and effort, rather than building things from scratch
and‘reinventing the wheel’.
This could be seen as‘laziness’ on the part of the programmer but rather it is
simply efficiency. Why struggle to work out a piece of code when there is a
huge, active community out there already helping you?
And that efficiency carries over to why many programmers start coding in the
first place…
And that is so that they never have to perform a boring, mindless task more
than once.
In other words: why input text into a spreadsheet hundreds and hundreds of
times over when you could write a simple Python script to do the same thing?
Why have a spreadsheet at all when you can create a program to handle all
that data more efficiently?
A smart coder might make an app to help them sort through their email
inbox, or they might create an app to help them organize the files more
intuitively on their computer.
Often this will involve using more modules or doing other things like that but
if it ends up saving you hours and hours in the long run… then isn’t it worth
it?
One high profile news story recently revolved around a man who decided to
use one of these services to outsource his entire job! He would receive work
from his superiors and then simply get the VAS to do it on his behalf.
Because the VAS company was only charging a dollar or less, he was able to
do this work, get paid the normal amount, and then make a big profit! This
then mean that he didn’t actually do anything all day, he sat at the computer
drinking coffee and playing games and got paid a decent salary.
Of course he was eventually caught and got into trouble but technically he
was doing nothing wrong! He was being paid to complete certain work and
that work was being completed… one way or another.
The point is that you can do this with a piece of software in pretty much any
area of your life and end up either earning more, or just saving yourself a ton
of time and being able to spend more of it doing things that you love.
One last final thing you might be interested in is building web-based apps.
This is another way to distribute and utilize all your hard work and it will also
give you some even more powerful applications, essentially allowing you to
build interactive web apps whether they be social sites or powerful utilities.
Web apps can be highly profitable as Mark Zuckerberg will attest and they
have countless uses.
Thankfully, the skills we’ve learned are relatively easy to take online and
we’ll look at just enough to get started here.
We’re then going to be able to build a‘web server’ app right on our own
computer, with no need to upload them. This is a good thing, seeing as you
may not already have a hosting account etc.
Chapter 26: Useful Tips from Python Experts
The following tips were provided by tech experts regarding the usage of the
Python programming language. These tips are intended for beginners.
Dynamic Input
When using programming languages that involve statically typed values like
C++ and Java, you need to define every function argument as well as the data
type for your function return values.
Python, however, is a language that uses dynamic inputs. Here, you will
never need to define the data info of anything. Python will automatically take
note of the data types that you enter, depending on the values that you will
use.
Interconnecting Strings
If you want to combine or link several strings, you can simply use the (+)
symbol. For example:
lightsaber
Finding names that are defined by modules
The “dir()” function can be utilized to know which names are defined by a
module. It produces a classified set of strings.
Accessing the documentation of a module
If you want to access the integrated documentation of a module, you can just
use ._doc_.
Using the Python Interpreter to run programs
The interactive interpreter used in this programming language lets you use all
the commands available in Python. You can just send the commands through
the command prompt and you will get results quickly.
You may want to break up your programs into multiple files to make them
more manageable as they increase in size.
Python lets you place several functions into a single file and convert them
into a module. You can incorporate this file into other applications and
scripts. They should have .py extensions.
Conclusion
Thank you for making it to the end of this book. The next step is to take the
new skills that you have learned and put them to use with what you already
know. You should find that using Python becomes easier because you already
know how the program works but with the new stuff that you learned, you are
going to be able to do more advanced moves with Python.
Once again, if you find that you are making mistakes, take the time to step
back and go back and look at the stuff that you might not have understood
when you went through it first. It is going to take time just like it did when
you were first starting out for you to get the hang of the new techniques that
you have learned.
You have already learned that programming is not going to come easy and it
is definitely not something that you are going to learn overnight. Even though
Python is simple enough to use, you are going to be learning a whole new
part of the program and it is going to get more complicated the more that you
learn. However, you are going to be doing some good for yourself because
you are going to be teaching yourself a valuable skill that can be used not
only in your personal life, but your professional life as well.
And with that, I must bid you farewell! We’ve learned a huge amount over
the course of this book, to the point that you’re now able to create entirely
functional standalone games with animations, graphics and the ability to read
from external files! Why not try building on the Hangman game and then try
and make some of your own projects, perhaps something that can help with
your daily workflow?
Thus we can say that Python is an extremely powerful language which can be
used for wide range of applications and that’s the reason why all big
companies are looking for data scientists or programmers who have learned
the art of Python.
We can conclude by saying that once you learn the basics of Python you will
be able to create almost anything you want.