0% found this document useful (0 votes)
452 views265 pages

PYTHON PROGRAMMING For Beginners The Easy and Complete Step-By-Step BooxRack

This chapter introduces Python as a high-level, interpreted programming language that is simple, powerful, and versatile. It is designed to be easy to learn and uses nearly regular English statements. Python is suitable for beginners and has a large community and many advantages for creating a variety of applications.

Uploaded by

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

PYTHON PROGRAMMING For Beginners The Easy and Complete Step-By-Step BooxRack

This chapter introduces Python as a high-level, interpreted programming language that is simple, powerful, and versatile. It is designed to be easy to learn and uses nearly regular English statements. Python is suitable for beginners and has a large community and many advantages for creating a variety of applications.

Uploaded by

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

Table of Contents

INTRODUCTION

CHAPTER 1: INTRODUCTION TO PYTHON


WHAT IS PYTHON
WHY YOU SHOULD LEARN PYTHON
Simple enough to read
Free
Fast
Works on a variety of platforms
A big library to work with
A large community
Libraries
Community

CHAPTER 2: A BRIEF HISTORY OF PROGRAMMING


CHAPTER 3: THE DIFFERENCE BETWEEN PYTHON 2 AND 3

CHAPTER 4: HOW TO INSTALL PYTHON. A STEP-BY-STEP GUIDE


UNDERSTANDING PYTHON VERSIONS
HOW IS PYTHON 3 BETTER THAN PYTHON 2?
SETTING UP PYTHON IN WINDOWS
Step 1: Download Installation Files
Step 2: Preparing Installation
Step 3: Completing Installation
Step 4: Verify Python Installation
INSTALLING PYTHON ON MAC
Step 1: Install Homebrew
Step 2: Install Xcode
Step 3: Install Python 3
INSTALLING PYTHON ON LINUX
Step 1: Check Python version and update package manager
Step 2: Installing Python 3 on Linux Mint and Ubuntu
Step 3: Installing Python 3 IDLE
SETTING UP ENVIRONMENT VARIABLES
SETTING UP PATH IN WINDOWS
SETTING PATH IN MAC AND LINUX
CHAPTER 5: GETTING STARTED WITH PYTHON
THE INSTALLATION PROCESS
RUNNING PYTHON PROGRAMS
USING IDLE
FEATURES OF IDLE
THE PYTHON SHELL

CHAPTER 6: HOW TO WRITE YOUR FIRST PYTHON PROGRAM


CHAPTER 7: PYTHON NUMBERS
OPERATORS USED FOR MATHEMATICAL EXPRESSIONS
OUTPUT FORMATION
COMPARISON OPERATORS

CHAPTER 8: PYTHON STRINGS


STRINGS
VALUES-HOW TO ACCESS THEM
UPDATING
ESCAPE CHARACTERS
SPECIAL OPERATORS
TRIPLE QUOTES
CHAPTER 9: PYTHON BASIC SYNTAX RULES, VARIABLES AND VALUES
INTRODUCING VARIABLES
INTEGERS, STRINGS AND FLOATS
NAMING CONVENTIONS AND COMMENTS
USING COMMENTS
HELLO WORLD PROGRAM

CHAPTER 10: FILE HANDING OPERATIONS


CHAPTER 11: PYTHON FUNCTIONS AND MODULES
MODULE
FROM…IMPORT
MODULE LOCATION
SCOPING AND NAMESPACES
DIR( ) FUNCTION
FUNCTIONS FOR GLOBALS ( ) AND LOCALS ( )
FUNCTION RELOAD ( )
PYTHON PACKAGES
FUNCTIONS
DEFINITION OF A FUNCTION
FUNCTION CALLING
VALUE VS PASS BY REFERENCE

CHAPTER 12: PYTHON DATES


CHAPTER 13: LISTS AND TUPLES IN PYTHON
LISTS
LIST UPDATING
DELETING ELEMENTS
TUPLES
ACCESSING VALUES
UPDATING
DELETING

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 16: PYTHON VARIABLES AND OPERATORS


OPERATORS, OPERANDS AND OPERATIONS
PERFORMING OPERATIONS ON VARIABLES
COMPARING VARIABLES

CHAPTER 17: CLASSES AND OBJECTS


HOW TO CREATE A NEW CLASS?
CLASS DEFINITION
Creating a class
Creating an inheriting class
SPECIAL ATTRIBUTES
HOW TO ACCESS MEMBERS OF A CLASS
CHAPTER 18: PYTHON DICTIONARIES
CREATING A DICTIONARY
ACCESSING ELEMENTS OF A DICTIONARY
DATA TYPE

CHAPTER 19: ORGANIZATION OF THE PYTHON CODE


PYTHON KEYWORDS
NAMING YOUR IDENTIFIERS
CONTROL FLOW WITH PYTHON
WORKING WITH STATEMENTS
WRITING COMMENTS IN YOUR CODE
EXPLORING VARIABLES
WORKING WITH OPERATORS
WORKING WITH VARIABLES IN THIS LANGUAGE
THE FUNCTIONS IN PYTHON
PYTHON AS AN OBJECT-ORIENTED LANGUAGE

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

CHAPTER 21: PYTHON STATEMENTS AND SYNTAX


STATEMENTS
SYNTAX
WHITE SPACE AND LINES
Explicit Joining
Implicit Joining
CHAPTER 22: PYTHON LOOPS
IF, THEN STATEMENTS
LET’S MAKE OUR FIRST GAME!
NESTING IFS AND LOOPS

CHAPTER 23: THINKING LIKE A PROGRAMMER PART ONE


A QUICK LESSON: LOGIC GATES
ADVANCED VARIABLES
MODULES, GRAPHICS AND MORE
INSTALLING NEW MODULES
CHAPTER 24: THINKING LIKE A PROGRAMMER PART 2
SETTING UP PYCHARM
MAKING A BASIC PYTHON GAME: HANGMAN
TIDYING UP WITH MODULES AND LOOPS
SOME LESSONS TO TAKE AWAY
ADDING MORE FEATURES AND FUNCTIONS
ADDING ADDITIONAL MODULES
INSTALLING ADDITIONAL MODULES
CREATING AN EXECUTABLE FILE
MORE WAYS TO DISTRIBUTE YOUR APPS

CHAPTER 25: THINKING LIKE A PROGRAMMER PART 3


BUILDING WEB APPS

CHAPTER 26: USEFUL TIPS FROM PYTHON EXPERTS


DYNAMIC INPUT
INTERCONNECTING STRINGS
FINDING NAMES THAT ARE DEFINED BY MODULES
ACCESSING THE DOCUMENTATION OF A MODULE
USING THE PYTHON INTERPRETER TO RUN PROGRAMS
WORKING WITH STATEMENTS USING PYTHON
EMPLOY MODULES TO MANAGE YOUR FILES

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.

Python is the chosen language of many different types of people – security


testers, data scientists, web app developers, etc. Most of the big applications
that you use on a regular basis today are written in Python, including
YouTube, the largest video-sharing app in the world.

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.

Python is an interpreted language, which means that it uses an interpreter to


convert codes and statements into machine-readable byte codes.

Learning a new programming language can be a great experience. You may


want to learn it so you can know more things about your computer and
understand how it works, how a website works, and perhaps you want to
learn so you can create your own applications and programs. But if you have
never worked with your computer in this way or with coding in the past, then
it is hard to figure out how to get started. With a little search, you will notice
that there are many coding languages available that you can work with
besides Python. From Java to C++ and so much more, it’s hard to determine
which coding language is the best for you.

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 object-oriented programming language which supports user-


defined classes, inheritance, and methods binding. In Python, everything can
be used as an object. Every object is first class.

Although its object-oriented feature is always emphasized, Python is actually


a multi-paradigm programming language which also supports structured,
aspect-oriented, and functional programming methods.

Python is an interpreted language. It has to convert programs into machine-


readable byte code before it can execute the codes. It is also a compiled
language because it has to implicitly perform compilation while loading the
modules or implementing standard processes.

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’s standard library which contains hundreds of useful modules is one


of the biggest reasons why it has remained popular across diverse types and
generations of users. These libraries or modules are easily accessible through
the import keyword and include various internet protocols, network
programming, mathematical functions, regular expression matching, random
module and functions, email handling, operating systems, GUI toolkit, and
XML processing.

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.

Python is a highly readable language that can be learned by anyone to make


powerful and useful programs within a short investment of time. It is a
beginner-friendly program that is highly recommended for those who are
learning to program for the first time.

To use Python, an open source language, you have to download its


installation files from the website of Python Software Foundation.

For windows users, you can use this link to find your preferred version:

https://www.python.org/downloads/

For Mac users, you may use this link:

https://www.python.org/downloads/mac-osx/

Python is a programming language that is both powerful and clear. It is


heavily object-oriented, similar to Java, Perl, Scheme, and Ruby.

These are some “language-specific” qualities of Python:

It produces cleaner handling of errors because it supports catching


and raising exceptions.

It has an automated memory management that lets you program


without having to allocate memory in your program codes manually.

It has highly advanced features like list processing and generators.


It has a wide range of fundamental data types such as strings
(Unicode and ASCII), dictionaries, lists, and numbers (complex,
long-integers, and floating points).

It allows you to classify your program code into packages and


modules.

Data types are dynamically and powerfully coded. If incompatible


data types are combined (e.g. trying to mix a number and a string),
exceptions will be raised, that’s why mistakes are discovered sooner.
Why You Should Learn Python

Python is a highly recommended first language for beginners. It is not just an


easy-to-learn language but a powerful language that has been used to build
desktop and web applications. Python has been widely used in the academic
circles for data analysis, scientific computing, and bioinformatics. It was used
to build Google, Pinterest, Dropbox, BitTorrent, Instagram, Civilization IV,
and other sites and platform.

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 programming is the use of the Python language to create computer


programs that are capable of performing a wide variety of tasks. Some
example applications include: basic computer housekeeping tasks, website
backend automation or CMS systems, systems integration, artificial
intelligence/machine learning and robotics/machine automation through
single board computer programming like the Raspberry Pi.

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.

Additionally, the interpreter is compiled for the operating system it is


installed on so Python programs can be fairly system independent. In other
words, code written on a Mac will in many cases run fine on a Windows
computer, or even a Raspberry Pi.

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.

Whether your task is to sort incoming emails on a server, or build a control


system for a revolutionary deep sea drone, Python provides an easy to learn
open source solution with unparalleled community support to get the job
done quickly and efficiently.
So, if there are a lot of choices out there why would you want to go with the
Python coding language in the first place? Many people, both experts, and
beginners all choose to go with Python because it is easy to learn, easy to
read, and it is capable of creating large, challenging codes that you might
want to write. There are a lot of different reasons that you would want to
work with this coding language, and these include:

Simple enough to read

Because Python is so close to the English language, it is easy to read. Add to


that the very strict rules of punctuation in Python and it’s even more readable
unlike some programming languages that are littered with curly braces
instead of punctuation. Python also runs by a set of rules that inform
developers exactly how their code is to be formatted. Called PEP 8, the rules
mean that a programmer always knows exactly where they need to put a new
line in and it also means that, when you read a script written by someone else,
you know that the same rules apply and you won’t have any trouble reading
and understanding it.

In fact, when it is compared to some of the other coding languages, it is one


of the most readable languages. Since this is an easy coding language to go
with, many beginners like that they can catch on so quickly and that they will
understand what they are doing in no time.

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.

Works on a variety of platforms

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.

A big library to work with

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.

In the beginning, assembly language was king. While it allowed highly


specific programming tailored and optimized for the low memory systems of
the day, it was very cryptic and difficult to learn, read or maintain.

As computers gained complexity in the 1950's, higher level languages like


Fortran, Cobol and Lisp were used to produce reams of instructional punch
cards which were physically read by computers to execute specific
instructions.

Programming with these tools was far easier than using assembly language,
allowing more complex programs to be written by a larger number of people.

As time progressed, improvements in technology brought better storage


methods for programs. Gone were the punch cards, replaced by magnetic tape
and eventually platter type disc drives. So too did the tools of creating
programs evolve and improve.

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.

These languages furthered the portability advances made by C and Pascal in


the 80's and added the ability to create objects and assign object specific
properties to them.

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.

Python is a computer users programming language. It provides actual users of


computers an easy to learn, easy to understand and powerful programming
tool for everything from automating system housekeeping tasks to developing
complex commercial applications.

Like all programming languages, Python has its set of rules and structures
that programs must follow.

This book is designed to cover the basics of those specifications.

In here you will be introduced to the basic requirements of language, from


obtaining and installing it to the variables, objects, functions, methods and
syntax used in creating a real program.

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.

There is a difference in speed when it comes to both Python 2 and 3. This is


because of both the xrange and the range () functions. People who have used
the two versions have reported that even though these two versions are
implemented in the same way, Python 2 is fast in speed as compared to
Python 3.

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.

It is important to know how python 2 and python 3 work. We are going to


generally look at how python works. We had previously mentioned that
python is an interpreted language. We are going to expound on that, and we
will see how an interpreter works. An interpreter is able to translate high-
level languages into low-level languages when the program is run. This was
previously mentioned: this is just a brief recap of what had been previously
discussed. Now, what happens in an interpreter is that you get to write your
program in the text editor or a similar program to this. After you do that, you
will proceed to instruct the interpreter to run the program.
Chapter 4: How to Install Python. A Step-by-Step
Guide
You need a working Python installation on your computer, as well as a text
editor and/or an IDE for Python programming. Certain computer operating
systems have Python setup already, in which case you may not need to
download, install, or configure anything.

If your computer is running a Linux, BSD, or Unix-based operating system,


an older version of Python may already be installed in your machine.
Understanding Python Versions

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?

Almost every incremental version of a software program comes with


improvements and Python 3 is no different. Compared to Python 2, the new
release features improve Unicode support, better integer division, improved
syntax structures, and added tools and features.

Python 2 will not be supported after 2020. Therefore, while it is good to


know how instrumental it has been in shaping the OOP language into what it
is today, it will soon be obsolete.

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.

Step 1: Download Installation Files

In your browser window, navigate to the download site


www.python.org/download . You should see this page:

Python Download Page


Click on the “Download Python 3.7.1” button. Note that the version number
of the download button may vary, but for this guide, we will use the current
version 3.7.1. The download manager should begin downloading a file named
“Python3.7.1.exe” on to your disk. Note that the file is roughly 30 MB.
Therefore, be patient if you are using a slow connection because it may take a
few minutes.

Step 2: Preparing Installation


Open your standard download location and open the Python3.7.1.exe file by
double-clicking it to run the installation wizard. An “Open File – Security
Warning” window should pop up.
Click Run. A setup Window with multiple
options will appear.

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.

Step 3: Completing Installation


During the process, the progress window will display the components being
installed.

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:

1. Open the installation directory


(C:\...\AppData\Local\Programs\Python\Python37-32). You should see the
program file python.exe.

2. Double-click python.exe. A command prompt interface window should


pop up with the file address of the python.exe file on the title bar. If you
encounter an error, there was a problem with your installation that you must
fix before you can use Python on your computer.

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.

Installing Python on Mac

Step 1: Install Homebrew


If you already have Homebrew installed, you can skip this step. If not, open
the terminal or terminal emulator you use and run this script:

usrbin/ruby -e "$(curl -fsSL


https://raw.githubusercontent.com/Homebrew/install/master/install
If you would rather not type this long command, go to Homebrew’s website
brew.sh and copy the code on their homepage then paste on your terminal.
Before the installation begins, this script will expound what changes will be
made on the computer. Wait for Homebrew to fully install.

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.

Step 3: Install Python 3


It is very easy to install the latest version of Python on your Mac with
Homebrew. Open the terminal or terminal emulator then run this command:

$ brew install python3


The installation process may take a couple of minutes. When completed, use
this command to verify the installed version:

$ 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.

Step 1: Check Python version and update package manager

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:

Step 2: Installing Python 3 on Linux Mint and Ubuntu


Distributions of Linux that use Ubuntu’s package distribution system version
17.10 and 18.04 and later have Python 3.6 by default. If this is already install,
use this command to invoke Python 3:

$ python3
Since Mint and Ubuntu use the same package management system, you can
install the latest version of Python using this command:

$ sudo apt-get update


$ sudo apt-get install python3
If your version of Ubuntu is 14.04 or 16.04, or earlier, use these commands to
update the package manager first:

$ sudo add-apt-repository ppa:deadsnakes/ppa


$ sudo apt-get update
Next, use this command to install the latest version of Python:

$ sudo apt-get install python3

Step 3: Installing Python 3 IDLE


IDLE is Python GUI programming tool. If you wish to install this tool on
your Linux computer, you will have to download and install the package
using this command:

$ apt-get install idle


To start Python IDLE from the terminal, use this command:

$ idle
Setting Up Environment Variables

When you type “python” or “python3” on your computer terminal, variables


will point the Python interpreter towards where the module files are stored to
be imported into the program. In UNIX-based operating system, PATH is
case sensitive while in Windows it may referred to as path, Path or PATH. If
when you enter “python” in Windows or “python3” in Mac and Linux you
encounter an error, this may mean there is a problem with the installation’s
environment variables. The important points to note about environment
variables are:

An operating system stores PATH in a named string. This string


contains information that the command shell and other programs can
use to access the right files.

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:

setenv PATH "$PATH:usrlocal/bin/python3"


On Linux, open the bash shell and type this:

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…

IDE basically stands for ‘Integrated Development Environment’. This is a


piece of software that contains all the components you need in order to start
making and testing your programs. This includes an interpreter, which
basically interprets the code you’re inputting so that it can be made into
useful software. You’ll also get a compiler that can turn your program into an
executable, meaning it can run on its own ready for distribution.

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.

You can get PyCharm here: https://www.jetbrains.com/pycharm/.


Whichever you choose, you’ll now be able to
launch the software and have somewhere to
enter the code. And when you run the program,
the interpreter will kick in and you’ll be able to
see it working!

But for now we’re not going to be using an IDE


at all. Rather, we’ll be looking at how you can
create apps using the Python GUI, which is also called IDLE.

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.

The output in the shell should look something like this:

RESTART: fullfilepathcylinder.py
785.3981633974483
Alternatively, the script can be executed by sending it to the interpreter with a
terminal shell.

On OS X or Linux, open a terminal window (in Windows use command.exe


or Windows PowerShell) and change the present working directory to the one
containing your file cylinder.py.

Then enter the following command

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

IDLE stands for Integrated Development Learning Environment. It is an


integrated development environment (IDE) which was created for use with
Python. IDLE is installed alongside the Python interpreter and document
files. It uses a simple graphical user interface with several built-in features to
make Python programming more efficient and intuitive.

IDLE provides an efficient platform for exploring, reviewing, and writing


Python programs. It supports Python’s interactive mood and script mode.

When using IDLE in interactive mode, Python displays feedback after


reading and interpreting the statement entered and analyzing this in relation
to previously entered statements saved in active memory. If you simply want
to explore Python commands or test bits and pieces of your code, the
interactive mode is what you would normally use.

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

multiple-window text editor

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.

The main options in Python


Shell’s menu are File, Edit,
Shell, Debug, Options,
Windows, and Help.
Chapter 6: How to write your first Python Program
To do anything with the beautifully clear Python programming language, you
first have to establish an environment in which you can do things. I’d say that
goes without saying, though.

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.

Within ch1.py, type the following:

print “hello world.”

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

Your output should look something along the lines of this:


user@userpc:~/Python$ 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.

It is tradition in the world of programming to start every new programming


language the same way– by writing a program to say‘Hello World’. This is
the most simpleand straight forward program you can make and it teaches
you the very basics– like how to actually get some code to run.

So how do we get‘Hello World’ to run in IDLE?

Simple: we type:

print(“Hello World”)

And then hit enter!

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!

On doing this, IDLE will seem to‘respond’ by saying‘Hello World’. Simple!

But of course a program needs to be more than one line long… so how can
we do that?

Well, at the moment IDLE is in‘interactive’ mode. We want to change that


and put it in‘script’ mode so that we can write a program. To do that, we need
to create something called a module.

Just like a‘.txt’ file is a text document and‘.mp3’ is a music file,‘.py’ is a


Python file. And when you open one of these in IDLE, it knows to be
in‘script’ mode.

To create a module/.py file, simply go to the‘File’ option in IDLE’s menu


and then select‘New’. This will automatically open a new window where you
can type in script mode. You can then click‘save’ to save the file, and call it
whatever you want leaving the extension as .py.

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.

Our formula is going to look a little something like this:

Mbrick = mkg x 4.5 / 10

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

Mass_kg = int(input( “My weight in kilograms” ))

Mass_brick = mass_kg * 4.5 / 10

Print ( “I weigh”, mass_brick, “brick.” )

Thanks to the programming that is written into Python, it is now going to do


the calculations for us so that we do not have to worry about messing the
calculations up.
Operators used for Mathematical Expressions

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.

Exponent – zb – Python: z**b Square root - √z – Python: math.sqrt(z) (With


the square root function, you will have to import the math module at the
beginning of your code so that Python knows you are wanting to do a square
root expression) A floating point arithmetic is going to result in rounding
errors and therefore will bring about results that you are not going to be
expecting.

Example

>>> print (0.8/0.4)

4.0

>>> print (0.8//0.4)

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 Python 3.x a single forward slash is going to be the mathematical operator


that is used for all number types when you are doing true division.

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

What is the mass of a cow in kilograms? 907

The cow is going to weigh 142.828051 in stones.

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

Print (round( 142.828051, 2))

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

Print (“ The cow weighs” , round( mass_stone , 3), “stone.”)

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

twoSigFigs = round (mass_brick, )

nmToString = str( twoSigFigs)

print ( “The cow’s weight” + numToString + “brick” )


Comparison Operators

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;

Print ( “Line 3 – result of res : “ , res)

Res = 50 != 15 ;

Print ( “Line 2 – result of res : “ , res)

Res = 50 > 15;

Print ( “Line 1 – result of res : “ , res)

Res = 50 < 15;

Print ( “line 4 – result of res : “ , res)

Res 50 >= 15;

Print ( “line 6 – result of res : “ , res)

Res = 50 <= 15;

Print ( “line 5 – result of res : “ , res)


Chapter 8: Python Strings

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.

Str.join ( ) can be used when you are using string concentration.

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!

Print “ “ join([ “peanut butter” , “jelly” , “and” , “peanut butter”]) #while it


does not seem like it, this is going to be more efficient for your code in
Python. You may also notice that this is a Python idiom that is used often.

Print “%s %s %s %s %s ( “peanut butter,” “jelly,” “and,” “peanut butter”)


#this is also a method that is pythonic as well as an example for string
concentration.
Values-How to Access Them

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

Variable 1 = ‘This is a string I created’

Variable 2 = “I can type anything I want”

Print “Variable 1 [1]: “ , variable 1 [1]

Print “Variable 2 [3:6]: “ , variable 2 [3:6]

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

Variable 1 = ‘This is what the world works.’

Print “update string : - “ , variable 1 [: 3] + ‘how’

Output

Update string : - ‘This is how the world works.’


Escape Characters

When you use an escape character, it is going to be interpreted by Python

Escaped characters are going to use single or double quotes.


Special Operators

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.

Concatenation – the value is going to be added despite where it falls on the


operator (+)

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 ( [ : ] )

Membership – the condition is going to be returned as true but only if the


character is found inside of the selected string ( in ) Membership – this is the
same thing as the previous one, except the character is not going to be found
inside of the string that you have selected ( not in ) Raw string – the escaped
characters are going to be suppressed. You are going to write it just like you
would if you were creating a now string, except you are going to use the
letter r with a set of quotation marks. ( r / R ) Format – the string is going to
be formatted ( % )
Triple Quotes

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.

A backslash in a raw string is not going to be treated like it is a special


character. Instead, whenever you put a character, into a raw string, it is going
to be produced like it appears.

Example

#! usr bin/ python

Print ‘D:\\ anywhere’

Output

D: \ anywhere

But, when you put in an expression such as an r expression it is going to


change the output.

Example

#!/usr/bin/python

Print ‘D:\\ anywhere’

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.

Essentially, a variable is a container or a representative. This is a word or a


letter that represents a number. That number can change but you can write the
letter or word at any point in your math to represent it. You can think of it
almost like a box and every time you tell the code to look inside the box, it
will find the information you put in there. That means you can change the
information regularly (by changing the value of the variable) but Python will
still always know where to look!

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.

In this case,‘x’ is actually‘3’.

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

We could also say:

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

Strings Lists Tuples Dictionaries For nowyou don’t need to learn


about lists, tuples and dictionaries but if you just can’t wait then skip
ahead to the called‘Advanced Variables’.
Naming Conventions and Comments

Variables are one of the most common elements in programming because


they allow things to change in a controlled manner– thus allowing for
dynamic programs that change over time or in response to input.

One way in which variables are different in other programming languages


though, is that they must first be defined. In Python, we can simply say: x = 3

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

In keeping with the age-old tradition of introducing newbies to the world of


programming with a simple Hello World, your first program will be a simple
program that displays the "Hello World".

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.

Enter the following text and press enter (return):

>>> print ("Hello World!")

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.

Exercise1: Hello World!

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!')

print ("My name is (enter your name here)")


Chapter 10: File Handing Operations

When creating programs, it is sometime useful to be able to store and retrieve


data from an external file. If you don’t export data to an external file, the data
is only available whilst the program is running. Unless you say otherwise, the
file is always saved to the same folder as the Python program you have
produced.

How do I write information to a file?

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.

Write to an external file


Write this program using the editing window.

This program will output the sentence to the external file.

Write to an external file and automatically close the file

Sometimes you want to write a program that automatically closes the file.
Write this program using the editing window.

This program will output the sentence to the external file.

How do I write a list to an external file?

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.

How do I read information from a file back into my program?

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.

Here is the output produced.


How do I read a list from a file back into my program?

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.

Write this program using the editing window.

Here is the output produced.

1. Here are the instructions for a game.

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

Import module1 [, module 2 [, … moduleA]

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

#import help for module


Import help
#At this point the function can be defined

Help.print_func (“Tim”)

Output

Good bye: Tim

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

From modname import name1 [, name 2[, … nameB]]

Example

From dig import dignity

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.

From modname import *

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.

Next it is going to go through all the directories that are inside of


PYTHONPATH

Lastly, it is going to check the UNIX directory which is going to be the


default path.

The search path is going to be inside of the module under the variable of
sys.path.

This variable is going to be in one of the three directories mentioned above.


Scoping and Namespaces

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 ( )

Any imported module is going to be carried out once.

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.

This package will have sub-subpackages, subpackages, and modules.

Example

#! usr bin / python

Def Butter():

Print “I am the phone number for the Butter family.”

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

When a function is defined in Python, it is going to increase the functionality


of the 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

#! usr bin/ python

#the definition for my function is going to entered in here

Def printme ( str ) :

“This will be where the string is printed”

Print str

Return;

# at this point I am going to be able to call upon the printme function

Printme ( “This will be where the first definition is going to go”)

Printme (“This is the second definition”)

Output
This will be where the first definition is going to go.

This is the second definition.


Value vs Pass by reference

When a parameter is set in Python, it has to be passed by a reference.

Example

#! usr bin/ python

#define your function in this space

Def nameme ( asection ) :

“This is going to be before you change anything”

Asection. Append ( [ 5, 10, 15, 20 ] );

Print “the numbers in the function I created: “ , asection

Return

#here is where you are going to change your function

Asection = [ 2, 4, 6 ];

Nameme( asection ) ;

Print “Any number that is not in the function “ , asection

Output

Numbers in the function [ 2, 4, 6, [ 5, 10, 15, 20 ] ]


Numbers not in the function [ 2, 4, 6, [ 5, 10, 15, 20 ] ]
Chapter 12: Python Dates

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.

A list of the acronyms used in the following examples:

YYYY – Year (eg. 2017)

MM – Month in a date (eg. 02 for February)

MM – Minutes in a time (eg. 22 for twenty-two minutes)

DD – Day (05 for the 5th of a month)

HH – Hours (eg. 23 for 11 o'clock PM)

MS – Milliseconds (these are usually printed to 6 decimal places)

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:

In Year-Month-Date format (YYYY-MM-DD)

Components of Day, Month, Year (DD MM YYYY)

Date and Time (YYYY-MM-DD and HH:MM:SS.MS)

Time only (HH:MM:SS.MS)

Worked Example:

Notice the functions imported from the datetime module

Observe the process used to invoke the desired output

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:

Programming the time output format

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:

%y or %Y – abbreviated year (17) or full year (2017)

%a or %A – for the weekday

%b or %B – for the month

%d – for the day of the month

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

The control codes used to format days & times are:

%c – locale's date & time (will change depending on locale in the world)

%x – locale's date only (will change depending on locale in the world)

%X – locale's time only (will change depending on locale in the world)

%I – Hour in 24-hour format

%H – Hour in 12-hour format

%M - Minutes

%s – Seconds

%p – locale's morning, AM, or afternoon, PM (will change depending on


locale in the world)
In the below example, a user will discover that it is possible to format the
output to return:

The current year

The day of the week and the current date

The day of the week and the current date and the time

The Numerical presentation of the date

Time with seconds included

Time without seconds

12-hour time stating morning (AM) or afternoon (PM)

Worked Example:

Input Code:

Output returned:

Programming a lapse in time

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)

Admittedly, it is not as straightforward as an arithmetic equation but after


these coming examples it will be easy for you!
Before we get to that, allow me to show you something pretty cool…

Here is a quick program to creating a calendar month:

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.

A programmer can use timedeltas to either go forward or backward in time to


determine the desired date and/or time. This concept is concisely presented in
the following worked example.

Worked Example:

Follow the logic of the following statements

Notice how the programmed code returns specific results

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:

Follow the logic of the following statements

Notice how the programmed code returns specific results

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.

The changed input is here:

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

Do the above code using your birthday

Change the above code to find New Year's Day

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

First list = [ ‘ science’, ‘history,’ , 2002, 2030 ] ;

Second list = [ 2, 4, 6 ,8 ,10 ];

Third list = [“ b”, “d”, “e”, “g” ]

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

#! usr bin/ python

First list = [ ‘ science’, ‘history,’ , 2002, 2030 ] ;

Second list = [ 2, 4, 6 ,8 ,10 ];

Print “first list [ 2 ] : “ , fist list [ 2 ]

Print “second list [ 2:4 ] : “ , second list [ 2 : 4 ]

Output

First list [ 2 ]: history

Second list [ 2:4 ] : [ 4, 6, ]


List updating

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

Section = [ ‘science’, ‘history’, 2002, 2030 ];

Print “numbers at the third index”

Print section [ 3 ]

Section [ 3 ] = 2060;

Print “the new value at the appointed index : “

Print section [ 3 ]

Output

Number found at the third index :

2002

New number found at the third index :


2060
Deleting elements

Sometimes elements have to be deleted from the list that you have created.

Example

#!/usr/bin/python

Secion1 = [ ‘science’ , ‘history’, 2002, 2030 ] ;

Print secion1

Del section1 [ 3 ] ;

Print “the new list after the third index has been deleted : “

Print section1

Output

[ ‘science’ , ‘history’, 2002, 2030 ]

After using the del function for index 3 :

[ ‘science’ , ‘history’, 2030 ]


Tuples

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

Tup1 = ( ‘science’ , ‘history’, 2002, 2030 )

Tup2 = ( 5, 9, 7, 4, 2 )

Tup3 = “f”, “b”, “e”, “t”

To write a tuple that is going to be returned as empty it is going to use the


tuple function and a set of empty parentheses.

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

Tup1 = ( ‘science’, ‘history’, 2002, 2030 ) ;

Tup2 = ( 5, 6, 8, 4, 3 , 1, 0) ;

Print “tup1 [ 2 ] : “ , tup1 [ 2 ]

Print “tup2 [ 2: 6 ] : “ , tup2 [ 2: 6 ]

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) ;

Tup2 = ( ‘lmn’ , ‘nop’ ) ;

#the action is not going to be able to be used for the tuples

#therefore, we are going to make a new tuple

Tup3 = tup2 + tup1

Print tup3

Output

( 5, 9, 25, ‘lmn’, ‘nop’)


Deleting

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

Tup = ( ‘science’, ‘history’, 2002, 2030) ;

Print tup

Del tup;

Print “the tup after it has been deleted

Print tup

Output

( ‘science’, ‘history’, 2002, 2030)

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

Python code and interactive prompt


When using the interactive prompt, you are going to have the ability to type
in code for Python without having to enter in system commands.

Codes like edit are not actual Python code.

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.

Launching files in Python are going to use an import function, but it is


different from the system command that will bring the file into the prompt.

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.

Automatic extensions with Windows

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.

Be sure to use programs that are going to be Python text friendly.

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.

File icon on Windows

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 are typically going to go at the end of a statement that is


considered to be compound.

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.

Forgetting a colon is going to result in an error message from the program.

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.

Python is going to automatically indent the code as it needs to be. White


space is going to be placed before your code so that it is indicated as a block
of code that has been nested.

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.

Parentheses and function calls


Parentheses have to be used when a function is being called despite the fact if
it has an argument or not.

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.

Your parentheses can be assigned to a specific value as well.

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.

C language with Python

Parentheses do not need to be used with if and while statements.

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 search paths


The module search is not going to be used so that is not going to be how the
file is located, instead an absolute path is going to be used, but it has to be
provided by you.

This is to assume that the file name is going to be working properly.

Module searches are only going to be used when you are importing a module.

Specific types

List types cannot be used on strings.

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.

While and range in loops


For loops are going to help you to skip over objects that are in your sequence
that you have created.

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.

Results from functions


The methods that are going to append or sort your list are not going to return
you object, it is simply going to modify them.

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.

Numbers can also be converted into to strings and vice versa.

Cyclic data structures


Many objects have a reference to itself and this is known as a cyclic object.
Python is going to display a set of square brackets and three dots.

The program is going to detect the cycle so that it does not have to go around
forever.
Chapter 16: Python Variables and Operators

As with any programming language, in Python it is critical to understand


variables and the operators used to manipulate them.

Variable usage in Python is much easier than in more structured languages


such as C/C++. Even so, variables and their operators still function on a basic
set of rules which cannot be ignored. If you attempt to do something outside
the rules, an exception will be thrown.

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?

In fact, one would think that an immutable object is simply a constant.

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.

So, how is that immutable?

It is all in the magic behind the scenes!

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!

So what’s next? Well, we start making more useful programs of course!

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!

Likewise, you can also use subtraction like so:

10 – 2

Things do get a little different though if we start using multiplication and


division. That’s because you represent a multiplication with a * rather than X
and you use / to perform division. Other than the syntax though, this is
basically the exact same process.

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

Something else that you’ll find useful to understand is what is known


as‘operator precedence’. What is this referring to? Basically, it means the
order that the operations are going to get carried out.

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.

For example, if we write:

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.

To do this, we have a few symbols and conventions. To ask if


something‘equals’ something else, we will use the symbol‘==’ (using‘==’
compares two variables, whereas one‘=’ forces them to be the same). This is
what will allow us to test certain conditions for our IF, THEN statements.
This way we can say‘IF’ password is correct,‘THEN’ proceed.

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…

(That’s right– programming languages can be attractive! In fact, there is even


such thing as‘code poems’!) We can also use an input to make this a bit more
interactive!
Chapter 17: Classes and Objects
It adds in a little more order to the whole thing. Think about this process as
you organizing the closet. You have to make sure that your closet is
organized by placing the shoes in one area, hanging up the clothes in another,
adding the purses together, and then having a place for all those extra things
lying around. You do this process task it ensures that everything looks nice
and is easier to find later on.

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.

To make things easier to understand, you should see objects as different


aspects and parts of the code that you are writing and then the classes will be
like the containers which you will use to store away these objects. You can
easily create a class out of anything that you want and then add in similar
objects that match up together into that class. You can pick out whatever
label that you want to go with the class, just be certain that it actually makes
sense for the type of object that you want to place inside the class. When
someone looks at the class, they should have a good idea of what you placed
inside of it and the objects should all match that label as well.

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

Classes are instantiated (creating a particular instance or realisation) by


declaring a variable with the term "c = " .

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.

Creating an inheriting 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__

This is considered a tuple that contains any of the superclasses

__module__

This is where you are going to find the name of the module, and it will also
hold your classes.

__name__

This will hold on to the class 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.

class Cat(object) itsAge = None

itsWeight = None itsName = None

#set accessor function use to assign values to the fields or member vars def
setItsAge(self, itsAge): self.itsAge = itsAge

def setItsWeight(self, itsWeight): self.itsWeight = itsWeight

def setItsName(self, itsName): self.itsName =itsName

def getItsName(self): return self.itsName

objFrisky = Cat() objFrisky.setItsAge(5) objFrisky.setItsWeight(10)


objFrisky.setItsName(“Frisky”) print(“Cats Name is:”,
objFrisky.getItsname()) print(“Its age is:”, objFrisky.getItsAge())
print(“Its weight is:”, objFrisky.getItsName()) Make sure to open up and
place this in your compiler before we move on. If you ask the compiler to run
this, you should get some results that show up right away. The results that
you get will include that the name of the cat is Frisky (or whatever name you
would like to add in there) and that the age is five while the weight is 10.
This is the information that we placed into the code, but you can add different
names and different numbers in there if that works out better for you. Try out
a few different options to see what will work and learn how you are able to
make it work for you.

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

To create a dictionary, simply place item pairs separated by commas inside


curly braces {}. Each item must have a key and a corresponding value in the
format key: value.

Exercise31: Creating dictionaries

empty_dict = {}

integerkey_dict = {1: "Mango", 2: "Apple", 3: "Orange"}

mixedkey_dict = {"name": "John", 0: [2, 4, 3]}

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.

Exercise32: Accessing dictionary elements

my_dict = {"name":"John", "age": 21, "occupation":"Programmer"}

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.

Adding, deleting, and modifying elements in a dictionary

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 = {"name": "John Doe", "age": 25, "grade": "B+"}

print ("Before update:", student)

print ("\nChange age to 30:\nAdd Sex key:value pair")

student["age"] = 30

student["sex"] = "Male"

print ("\nAfter update:", student)

print ("Delete grade entry:")

del student["grade"]

print ("After deleting grade:", student)

When you run Exercise33.py, you will learn that:

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

cmp(dict1, dict2) Compares the elements of dict1 to those of dict2.

len(dict) Returns the total length of the dictionary (the number of item
dictionary)

str(dict) Returns a printable string representation of the dictionary

type(variable) Returns the type of the passed variable.

The next table is a presentation of the methods that you can use to manipulate
the elements of a dictionary:

Methods Description

dict.clear() Removes all the elements of the dictionary dict


dict.copy() Returns a shallow copy of the dictionary dict

dict.fromkeys(

) Returns the value of key x in the dict dictionary or def


not exist.

dict.has_key(x) Returns True if key x is in dictionary dict, otherwise F

dict.items() Returns a list of dict's (key, value) pairs in tuple forma

dict.keys() Returns list of keys of the dict dictionary.

dict.setdefault(x, Returns the value of key x in the dict dictionary or set


default=None) dict[key]=default if key does not exist.

dict.update(dict2) Adds dictionary key:value pairs from dict to dict

dict.values() Returns a list of values from the dict dictionary.

Properties of dictionary keys

While the values of a dictionary in Python have no restriction – they can be


made up of any arbitrary objects or data types, which include standard or
user-defined objects – keys are different. There are two vital points you must
know about dictionary keys in Python:

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.

Object-oriented languages, or OOP languages, made it their goal to change


all of this. It has been designed to make some changes in the language and to
ensure that the programmer - even the new ones - would be able to organize
their code, without having things moving around on them and causing a
mess. And Python is one of these OOP languages.

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

Tkinter (short for Tk interface) is a GUI library made for Python.


Benefits of Tkinter in Studying Python Language

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.

Tkinter is free and comes with Python meaning machines with


python installed will accept the GUI.

Its simplicity enables you to have a good grasp on GUI


concepts and builds a foundation over which more complicated
elements from other libraries can be easier to understand.
Disadvantages of Tkinter

Tkinter provides very widgets giving it a very old look as


compared to other GUI libraries like .NET which has more
modern widgets giving it a very modern look
This GUI library is hard to debug because its core code is not
in Python language.

Fig. 8.1: A simple GUI application made from Tkinter


A GUI program offers a window with a variety of widgets for you to view
and interact with. There are 15 widgets that are provided in Tkinter module.

Widget Description

Button When clicked an action occurs.

Canvas An area for graphics display

Checkbutton A button that takes the state ‘On’ or ‘Off’

Entry A space to type a single line of input using your keyboard


Frame This container holds the other widgets

Label Displays an image or one line of text

Listbox Shows a list where users can select an item

Menu A list that appears when users click the menu button widget

Menubutton Click this button to display the menu

Message An area displaying multiple lines of text

Radiobutton Buttons that allow user to select a single option from several. They ca
deselected

Scale A slider where users select a value

Scrollbar Adds scrolling ability to a number of widgets e.g. listbox widget

Text Makes it possible or users to input several lines of text

Toplevel A separate window container


Creating an Empty Window

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, …)

Master – This represents the parent window


Options – They are used to further enhance the widget by adding details
like text, width, height etc.
Within the brackets represents the attributes to the given widget. Below is the
code for displaying “Hello World”. Write it down and try it on your
computer.

Code output:
We can go further and display more lines rather than just a single one like so

The pack() (Lines 8 & 9) method is one of the geometry management


methods widgets that have access to and can be used to place the text in
different parts of the main frame. This is achieved by providing appropriate
options to this method. Options include: top(default), bottom, right, left.

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

y = Frame (master, options, …)

Master – This represents the parent window


Options – They are used to further enhance the widget by adding details
like highlightcolor, highlightbackgroundetc.
Code Output:

Button Widget

✓ These widgets are used to create buttons in our applications.


They are labelled with a text or image to display their function to the user.
When clicked, a callback function executes. In this demonstration, a window
will display some information after the button is clicked.

syntax

y = Button (master, option = value, …)

Master – This represents the parent window


Options – They are used to further enhance the widget by adding details
like image, height, font etc.
To add a button to our GUI follow the code below.

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

y = Entry (master, option, …)

Master – This represents the parent window


Options – They are used to further enhance the widget by adding details.
The following is a simple program to convert kilograms to pounds (Line 8).
Code Output:
We can also display the results on a Label widget instead of the message box.

Radio Button Widget

✓ Allows users to pick from a selection of options


When a radio button is selected, a dark circle appears inside the clear one and
indicates a user has taken an option. On the other hand, when deselected, the
dark circle disappears. These buttons are mutually exclusive, in that, when a
button is selected, the previously selected one is deselected. This occurs only
for radio buttons in the same container.

syntax

y = Radiobutton(master, option, …)

Master – This represents the parent window

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.

Callback functions can also be added to the arguments of our Radiobutton().


That means, once the button is selected, a specific action happens.

Check Button Widget

✓ The check button widget allows for multiple selections in a number of


choices or in a list

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

✓ A rectangular area meant to display graphics


syntax

y = Canvas(master, option = value, …)


Master – This represents the parent window
Options – They are used to further enhance the widget by adding details.
This widget enables drawing of lines, circles, images, and also plots. Below
is a demonstration of filling the window with color.
Source Code:

In Line 5, a canvas widget is created that has several arguments. bg defines


the background color of the canvas. The height and width define the
dimensions of the window.

Now let’s add something more to your empty canvas.


Source Code:

The first two arguments of creat_line() method in line 7 represent the


coordinates of furthest point to the left and the next two the point at the
furthest right. The last argument is to add a color to the line.

For the purpose of drawing, the canvas widget has methods with the word
Create for example, create_line(), create_oval(),create_rectangle() etc.

In the following example we will use create_rectangle().

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.

If you are to understand the online documentation, you will need to


understand the naming convention-this could prove to be helpful for you.
There are various online tutorials for this GUI. The old tutorials tend to be
short and easy to understand. Unlike Tkinter, you will have to download and
install PySide. Follow the installation instructions based on the operating
system that you are using.
2. WxPython. This is another graphical user interface that is used in
programming the Python language. Through this toolkit, the user is able to
create programs in a simple and easy way. They are able to use a graphical
user interface that is highly functional.

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?

For a beginner who is new to programming they are easy to use.

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.

What are their disadvantages?

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.

It is attractive to look at. Something pleasing to the eye will always


attract a lot of attention.

The user is able to experiment with the different available options.

It should be easy to use.

The words used are easy to understand and they are relevant to the
user.

The key areas have relevant colors.

The Tkinter graphical interface is readily available since it is already pre-


installed in your Python program. It is the best if you are starting off to use
what is available and then progress to other GUIs later on.

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 programming, statements are more like commands or instructions. Every


statement makes the computer do something for you.

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.

In order for a statement to function well or to work, it must follow the


programming language's syntax. In the previous chapter, it was emphasized
that if you exchange the position of the argument and the keyword in the
statement, Python will return an error.
Syntax

In programming language, you need to follow syntax. Syntax is the collection


of rules you need to follow in order to create a correct statement in
programming languages. Just like in English grammar, one small mistake in
writing your sentence may change the context of what you are trying to say.
Unfortunately, the rules in computer programming are much stricter.
Nevertheless, it is much simpler and easier to remember.
White Space and Lines

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

New lines do not terminate a statement. For example, by doing an explicit or


implicit joining (or extending a statement over the new line), the new line
will not terminate the statement.

Explicit Joining

As mentioned before, every line of code in Python is a statement. However, it


does not mean that you have to stick with ‘literally' putting a huge statement
in one line. It can be daunting and it can be an eyesore to do. In order to work
around that, you will need to cut the statement into multiple lines and join
them together. It is important to be somewhat organized when
programming") That is one line. And if you are coding in a source code
editor, it will exceed the width of the viewport, and you will need to scroll
right to view the rest of that long statement.

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',

'Wednesday', 'Thursday', 'Friday',

'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",

... "And Welcome!")

Hello World And Welcome!

>>>

Let us explore the adjectives used to describe python in the easiest to


understand manner:

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

Uncompiled – Implementations are interpreters which are step-by-step


executions of source code

Interpreted – Instructions are directly executed without having to be in "weird


computer language "

Dynamically typed – variables are typed straightforwardly with no difficult


rules needed

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!

This is another example of something that might seem rather pointless


currently. Why would you want to count to 100 this way when you have
other methods? Well, one example might be to look through a list of items–
and we’ll discuss that in the on‘Advanced Variables’.

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…

One way that it might be useful as an example though, is if we use while


True. This statement (notice the capital‘True’) simply runs our loop until we
say otherwise with break. We’ll use this in the very next chapter…

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.

But there is perhaps nothing that characterizes programming as a whole quite


as well as the‘IF, THEN’ statement. This is a little sequence of code that
basically tests a condition and produces output based on that. The result is an
instruction that reads‘if this, do that’.

For instancethen, we can allow a user only to progress when they’ve


answered a question correctly, or when they have entered the correct
password.
Let’s Make Our First Game!

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.

For instance, if we were making a platform game then it would be an‘if’


statement that would make the character fall if the ground wasn’t underneath
them (it could also be done with a while statement but that’s not really the
point!).

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.

To write in pseudocode, simply name variables in a descriptive manner (with


no need to explain how you got them) and forget all about formatting
conventions.

To demonstrate, this is how the‘physics’ of our aforementioned 2D


platformer would work in pseudocode: While Y-coordinate-underneath-
character is EMPTY: Y coordinate = Y coordinate + fallspeed Else:

If player-presses “right” then: X coordinate = X coordinate + walkspeed Else IF player-


presses “left” then: #Go the other way
Else if player-presses “jump” then: #jump sequence
Y-coordinate = EMPTY;
End if

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:

If FirstName = Bill AND LastName = Gates Then print “You created


Windows!”
Get it?
A Quick Lesson: Logic Gates

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.

Essentially, IF, THEN statements are actually representative of the


underlying physical components of your device. Specifically, your
computer/phone’s CPU uses a complex network of switches in order to allow
the creation and destruction of circuits. When you code, it gets translated by
the interpreter into binary– which means 1s and 0s.

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.

What is a logic gate? The easiest way to visualize it is by imagining two


straight wires both connected at either end to the same bulb and the same
battery. The bulb is also connected back to the battery from the other side,
completing the circuit.

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…

Which is the AND statement that we only just learned!

One wire with just one switch? Well, that’s just good old‘IF’.
Advanced Variables

Alright, that’s enough messing around! Back to the hard stuff…

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!

Well, how about we add a random number?

There’s just a small problem though… Python doesn’t include a random


number generator as one of the commands! Or at least not as one of the built-
in commands! Thankfully though, there are modules out there that you can
use to access this ability.

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!

Note that modules can sometimes be referred to as‘libraries’ as well.


Chapter 24: Thinking Like a Programmer Part 2

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

We mentioned PyCharmearlier in this book as a passing interest but now it’s


time to actually give it a go. Writing scripts in the text editor is only going to
allow you to do so much and eventually, you’ll find yourself needing
something a little more powerful in order to edit your work and try it on the
fly. This will also allow you to view your game assets and all the files in your
project and much more.

To get started, head over to the JetBrains website

www.jetbrains.com) and then download PyCharm using


(
the link on the main page. This will then download automatically. Choose the
Community version in order to get the free and basic version that will take up
the least space on your computer.

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.

My advice to you as a beginner is to decide on something you’d really like to


make, whether that’s a basic game or a useful tool. Either way, you can then
do the research as required to make it and by the end, you should have much
more confidence ready for tackling future projects.

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…

This is the code so far:

from random import randint

Listy = ["calculator", "music", "optimal", "diagonal", "hexagonal",


"muscle", "irate", "python", "libraries"]

Word = Listy[randint(0,len(Listy) -1)]


ReferenceWord = ""
Lives = 13

def DrawSpaces(HiddenWord, Attempts):


Rounds = 0
Spaces = ""
while Rounds < len(HiddenWord):
if HiddenWord[Rounds] in Attempts:
Spaces = Spaces + HiddenWord[Rounds]
else:
Spaces = Spaces + "_ "
Rounds = Rounds + 1
return Spaces;

print(DrawSpaces(Word, ReferenceWord), "\n")

LetterGuess = input("Guess a letter: ")


Lives = Lives - 1
if LetterGuess in Word:
print("Got one!")
ReferenceWord = ReferenceWord + LetterGuess
else:
print("Nope!")
print(DrawSpaces(Word, ReferenceWord), "\n") So what does all this do?
Well, first, we have made our little bit of code that draws the spaces into a
separate module. This allows us to run it multiple times but it also means that
we need to pass the variables to and from it. We can’t access the same global
variables so instead we need to‘pass’ the hidden word (the word we grabbed
from our list at the start) and we need to pass the attempts we’ve built up.
When we guess correctly, the letter we guessed will be added to
our‘Attempts’. This will then allow us to check each letter in our hidden
word against our attempts. To do this, we can get the character from any
string simply by using String[index]. This works just the same as it does for
lists!

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!

Remember, using‘Return’ in object oriented programming allows us to


essentially‘code’ a variable. By returning the value of‘Spaces’, we can treat
this just like a regular string and that means we can include it in print
statements, check its length, look into its index etc. Each time we reference it
though, we need to pass it the strings that it is using in its algorithms to
calculate.

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…

Doing this is pretty simple:

from random import randint

Listy = ["calculator", "music", "optimal", "diagonal", "hexagonal",


"muscle", "irate", "python", "libraries"]

Word = Listy[randint(0,len(Listy) -1)]


ReferenceWord = ""
Lives = 13

def DrawSpaces(HiddenWord, Attempts):


Rounds = 0
Spaces = ""
while Rounds < len(HiddenWord):
if HiddenWord[Rounds] in Attempts:
Spaces = Spaces + HiddenWord[Rounds]
else:
Spaces = Spaces + "_ "
Rounds = Rounds + 1
return Spaces;

while Lives > 0:


print(DrawSpaces(Word, ReferenceWord), "\n")
print("Lives: ", Lives, "\n", "\n")
LetterGuess = input("Guess a letter: ")
Lives = Lives - 1
if LetterGuess in Word:
print("Got one!")
ReferenceWord = ReferenceWord + LetterGuess
else:
print("Nope!")
So now we have a game that will let us guess as many times as we like! Each
time the loop goes round (which continues until lives = 0), it will draw the
spaces and letters and give us a chance to input one more option. We lose a
life each time we guess and once we’ve lost all our lives, the loop stops. It
would be very easy at this point to say‘Game Over!’.

But how can we reward our player for winning?

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!

Remember, to bust out of a loop, we use the command‘break’. This means


that we can deploy this early if we notice that the new DrawSpacesreference
doesn’t return any blanks!

Listy = ["calculator", "music", "optimal", "diagonal", "hexagonal",


"muscle", "irate", "python", "libraries"]

Word = Listy[randint(0,len(Listy) -1)]


ReferenceWord = ""
Lives = 13

def DrawSpaces(HiddenWord, Attempts):


Rounds = 0
Spaces = ""
while Rounds < len(HiddenWord):
if HiddenWord[Rounds] in Attempts:
Spaces = Spaces + HiddenWord[Rounds]
else:
Spaces = Spaces + "_ "
Rounds = Rounds + 1
return Spaces;

Winner = 0

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: ")
Lives = Lives - 1
if LetterGuess in Word:
print("Got one!")
ReferenceWord = ReferenceWord + LetterGuess
else:
print("Nope!")

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

Listy = ["calculator", "music", "optimal", "diagonal", "hexagonal",


"muscle", "irate", "python", "libraries"]

Word = Listy[randint(0,len(Listy) -1)]


ReferenceWord = ""
Lives = 13

def DrawSpaces(HiddenWord, Attempts):...

Winner = 0

while Lives > 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!

To start with, there’s still a little bit of basic tidying up to do.

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.

The first thing we need to do to make this a lot more professional-looking


then, is to add some graphics. We’ve seen how to make graphics with Turtle,
but those graphics were pretty much just vectors created very slowly… not
really suitable for a game that you want to become a best-seller!

And it can be a little fiddly. Fortunately, I’m here to guide you through it!
Installing Additional Modules

First, head on over to PyGame.org/downloads.shtml, where you’ll be able to


find the download files. This is where things get a little complicated, because
you need to ensure that the version you download is the right one for your
particular set-up.

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

And you should find that there are no red underlines.

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.

Option two, is to use a less user-friendly method of installing modules. The


good news is that this will allow you to use a version of PyGamethat is
intended for the latest version of Python and which is available in 64bit. The
problem is that it is‘pre-release’, which means that it doesn’t come with
the‘easy installer’ (MSI file).

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.

Type‘python–m ensurepip –upgrade’ and‘pip install wheel’.

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!

So well done you.

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!

It’s called PyInstaller and it can be found at Pyinstaller.org.

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!

There’s just one unfortunate downside…

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 website I highly recommend is called


automatetheboringstuff.com/chapter13/. This is a page that will provide you
with a bit of detail on two very powerful modules that will let you work with
PDF files and DocXfiles. Using both, you can then edit word documents and
PDF files and if you are someone who writes for a living in any capacity…
well then imagine the amount of time you might potentially be able to save
yourself!

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.

That is the mindset of a programmer!


Building Web Apps

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:

>> print “light” + “saber”

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.

The = and == operators – when it comes to assignments, the symbol “=” is


used by Python, while the symbol “==” is employed to compare values.
Currently, the Python language does not accept linear assignment, which
means the programmer will not accidentally assign values when he is trying
to perform a comparison.
Working with Statements using Python

When separating blocks of code, Python uses an indentation and a colon,


while for separating assignments, a carriage return is used. C++, C, and other
compiled languages utilize semicolons to divide statements and brackets (the
curly ones) to divide blocks of codes.
Employ modules to manage your files

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?

You’ve learned what it means to think like a programmer more importantly


and how to go about expanding your knowledge from these foundations.

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.

You might also like