Python Programming

For Beginners

Learn The

Basics Of Python Programming

By

James Tudor

www.MillenniumPublishingLimited.com

Copyright ©2021

All rights reserved. Except as permitted under the U.S. Copyright Act of 1976, the scanning, uploading and distribution of this book via the Internet or via any other means without the express permission of the author is illegal and punishable by law. Please purchase only authorized electronic editions, and do not participate in or encourage electronic piracy of copyrighted material.

Table of Contents

Who Is This Book For?

What Is Python?

Interpreted Not Compiled

Advantages of Python as an Interpreted Language

Scripts

Python as a General Purpose Programming Language

Community Frameworks, Toolkits, Libraries, and Modules

Programming Paradigms and Object Oriented Programming

History, Background, and Evolution

Core Philosophy and Uniqueness

Summary

Chapter 1

Getting Started With Python

Python 2.x vs. Python 3.x

Installing the Interpreter

Using Python Shell and IDLE

Writing Your First Program

Shell, IDLE, and Scripts Syntax

Prompt

Indentation

Indentation Prompt

Python Shell Navigation

IDLE Navigation

Troubleshooting Installation Issues

Practice Exercise

Chapter Summary

Chapter 2

Variables and Operators

Computer Basics

Computer Program

What Are Variables?

Naming Variables

Using Variables

Naming Conventions

Naming by Description

Introduction to Expressions and Python Operators

Expressions

Operators

Arithmetic Operators

Relational Operators

Assignment Operator

Logical Operators

Truth Table

Membership Operators

Identity Operators

Bitwise Operators

Truth Table

Practice Exercise

Chapter Summary

Chapter 3

Simple Data Types

Numbers

String

Combining/Concatenating strings

Avoiding Type Errors with Conversion Functions

Avoiding, Replacing, and Stripping Whitespace

Avoiding syntax errors with strings

Collections/Sequences

Tuple

Dictionary

Styling your code

General Style Guide

Indentation

Line length

Blank lines

Practice Exercise

Chapter Summary

Chapter 4

Conditions and Loops

“if” statements

Else Statements

Code Blocks

Loops

While

For Loop

Break

Continue

Error Handling

Try and Except

Variable Styling

Practice Exercise

Chapter Summary

What Comes after This?

The End

Who Is This Book For?

This book is primarily for people who are relatively new to programming and, more specifically, those who want to discover the world of Python. This book will take you through the fundamentals of programming and Python.

You’ll discover the basics of programming and common computer data processing. The lessons will familiarize you with how programs work and their primary components.

What Is Python?

Put simply, Python is an interpreted, high level programming language for general-purpose programming. Created by Guido van Rossum, Python has a design philosophy that emphasizes code readability, which reduces the cost of program maintenance. It does not require compilation and, much like Java, it is object oriented.

Python’s high-level built in data structures, combined with dynamic typing and binding, make it very attractive for Rapid Application Development. It supports multiple programming paradigms, including object oriented, imperative, functional and procedural, and has a large comprehensive library.

The book will explain more about these characteristics later.

Interpreted Not Compiled

A program is a set of instructions that direct a computer’s hardware to perform certain tasks. The computer load the instructions in its memory, read the instructions, and execute them one by one.

Creating a program requires a developer to write code using a programming language. Written code alone is not enough to make a program operational since the computer does not understand code written using a programming language.

There are two common ways to make written code an operational program. The first method is compiling and the second method is interpreting.

Usually, a developer compiles his written code using a compiler. The compiler check the validity of the code and then it translates it to native code or instructions computers can understand. Programming codes of some programming languages like C and C++ require compiling.

However, programs written using Python does not require compiling – instead, they are interpreted. A separate program, called the interpreter, runs when a user executes Python code. The interpreter interprets or translates Python code to byte code once a user executes it, which then allows the computer to understand the instructions in the code.

Advantages of Python as an Interpreted Language

The problem with compiled programs in native code is that it only works on the target platform. For example, a program compiled for Windows operating systems will not work in MacOS or UNIX based program. Of course, the user can use a third party program like virtual machines to run the compiled application.

With Python as an interpreted language, a Python developer does not need to worry about that. Since the Python interpreter is basically a virtual machine of sorts, you can run Python code in almost every platform and device available (a very powerful benefit).

Another problem with compiled language is the compilation process itself. Compilation takes time. A small program with a thousand lines of code can take a minute or two to compile.

That seems a small issue at first. However, if you need to debug (i.e. troubleshoot) or perform a test run of your program, you will always need to compile it. And those one to two minutes compile time can easily add up.

Another issue is that you cannot edit the program easily. You always have to edit the source code, recompile, and debug.

An interpreted language like Python does not have those issues. Once you are done with the code, you can just run it. If you are not satisfied, you can just go back on editing your code and run it again. This is why developers like to rely on Python for rapid application development or RAD.

Scripts

Programs written in Python are often referred to as scripts, especially if they are small in size. Scripts are small programs that are executed within a runtime environment. In Python’s case, the runtime environment is the Python interpreter.

Most scripts usually deal with text processing. In web development, Python is used as a server-side scripting language. Server-side scripting is basically a technique used in web development which involves employing scripts on a web server which produce a response customized for each user’s request to the website. The alternative is for the web server itself to deliver a static web page.

Web developers often use Python as a replacement for other popular server side scripting languages like PHP and ASP.

Python as a General Purpose Programming Language

Python is versatile as mentioned before. People in different industries and field of studies use it. You can use it to create programs with a graphical user interface (GUI). Furthermore, you can develop web servers or cloud applications using Python. Last, but definitely not the least, you can use it to process big data.

Community Frameworks, Toolkits, Libraries, and Modules

Python by itself is a small tool that you can use to develop simple programs and scripts. Because of that, you need to write a lot of code to develop large and complex programs.

However, writing every line of code is tedious and unnecessary for you to achieve or create complex programs. You can always opt for a far easier and practical route: using frameworks and importing libraries and modules.

Frameworks, toolkits, libraries, and modules are files containing written code that you can use to add more functionality to Python and your programs.

For example, creating a simple graphical user interface window in Python is not possible if you do not use frameworks, libraries, modules, or toolkits. Using a toolkit like TkInter will allow you to easily create a GUI.

Thankfully, Python is backed by its huge community. Its community has lots of frameworks, toolkits, libraries, and modules to offer. Most of them are free for you to use. And they can help you immensely in creating robust and complex programs you have in mind.

Programming Paradigms and Object Oriented Programming

Python is an object oriented programming language. Object-oriented programming (OOP) refers to a type of computer programming in which programmers define not only the data type of a data structure, but also the types of operations (functions) that can be applied to the data structure.

In this way, the data structure becomes an object that includes both data and functions. In addition, programmers can create relationships between one object and another e.g. objects can inherit characteristics from other objects.

Furthermore, OOP is a programming paradigm and multiple paradigms have been developed over the years.

A programming paradigm is essentially a methodology on how to write programs. You should bare in mind that writing a program is a constant process of solving problems. With each line of code, you solve a problem that often presents itself as, “How can I write this program to make sure that it will work as I intended to?”

As with any problem, especially those that are mathematical in nature, there are multiple ways to write and solve them. For example, you can write and solve the problem 1 + 1 + 1 as 1 + (1 + 1) or 1 * 3. Despite obvious differences in the way the problem is presented, you still arrive at the same solution, which is 3.

Programming paradigms are like that. They are like disciplines, if you will. Each paradigm has its own advantages and disadvantages. Nonetheless, all of them will allow you to still create a program that will work as you intended.

Python is well suited to object oriented programming. It does not mean that you cannot use other programming paradigms with it. It just means that it is easier to write object oriented programs with it.

We will discuss more about programing paradigms and object oriented programming in later parts of this book.

History, Background, and Evolution

The development of Python started in the 1980s. Guido van Rossum started its implementation in 1989. Rossum decided to name the programming language after Monty Python, a UK based comedy group.

Rossum released Python 2.0 in the year 2000. At the same time, he made the development process transparent and allowed community involvement. He then released Python 3.0 in 2008. This version of Python had major changes, which did not have backwards compatibility (i.e. did not work well) with programs written in previous Python releases.

Due to the limitation of Python 3.0 in terms of compatibility with old source codes, most businesses and developers stuck with Python 2.x. Be that as it may, Python 3.x is equipped with a Python 2.x code conversion tool that makes transition to the latest releases possible. However, some deemed it easier to keep and maintained their old code.

Core Philosophy and Uniqueness

The core philosophies of Python can be summed up to simplicity, transparency, and readability. Rossum and the community behind Python made sure that all programs written in Python can be understood by everyone after reading the code once.

Below are some of the ways Python programming differs from some of the most common programming language conventions:

- You can create code blocks through indentation alone instead of enclosing with brackets to create blocks of code.

- You can end a statement without placing a semicolon (;) or any symbol.

- You can splice in other programs with Python seamlessly and you can use it for different purposes.

- You can create programs with shorter code.

- You do not need to declare variables and define their types.

Summary

Veteran programmers and developers see Python as a versatile and handy tool. They can use it anywhere and anytime they want. It is compatible with multiple platforms.

Inexperienced programmers and total beginners should know that Python is an excellent language to learn. It is a practical choice.

As of now, Python is one of the top 10 most used and popular programming languages in the world. Its usefulness is vast and it continues to grow in popularity. With all of the characteristics it has, it has clear advantages over other programming languages.

Did you know?

There is a poem written by Tim Peters named as The Zen Of Python which can be read by just writing import this in the interpreter!

Chapter 1

Getting Started With Python

You can run and code Python on Windows, Mac, and Linux. To get started, head over to the official website: www.python.org and download the Python installer. This book will use Windows as the primary environment for the examples and lessons.

Python 2.x vs. Python 3.x

There are two popular and official versions of Python: Python 3.x and 2.x. As of this writing, you can download Python 3.7.0 if you want the 3.x version. You can also download Python 2.7.15 if you want the 2.x version.

However, to prevent any conflicts and misunderstandings, please download and use Python 3.x. All the examples and lessons in this book are written with Python 3.x in mind.

The 2.x version is an older version of Python. Ever since the Python developers proceeded in developing Python 3.x, they have made a lot of changes to the behavior and even the syntax of the Python programming languages.

For example, if you divide 3 and 2 using the ‘/’ operator in Python 2.x, you will receive an output of 1. If you divide the same numbers with the same operator in Python 3.x, you will receive an output of 1.5.

You may ask: If Python 3.x is new and improved, why are the developers keeping the old versions and why is Python 2.x being used?

The quick answer to that is code migration. Because there are many differences between version 2.x and version 3.x, programs and scripts created using version 2.x need to be recoded to become compatible with version 3.x Python.

If you are dealing with a small program using version 2.x, then the code migration will be a trivial problem at best. However, if you have programs with thousands of lines, then migration can become a huge problem. Other issues with migrating to Python 3.x are code maintenance and retraining programmers to adapt with the changes.

Because of the aforementioned reasons, developers with huge programs written and ran using the version 2.x runtime environment did not bother making the transition to version 3.x.

Installing the Interpreter

Python comes with two important ‘programs’:

- Python’s runtime environment and

- Command line interpreter.

The Python installer you download from its website contains both. Installing them is easy, particularly in Windows.

All you need to do is download the file and click open to let it run the setup. You will need to follow a few simple step-by-step instructions, click a few buttons here and there and Python will be available on your computer.

Note that there will be a point during the installation that you will need to select the packages and features that you want to be installed in your system. Make sure that you check all of them.

Note that tcl/tk installs TkInter, which is a Graphic User Interface (GUI) toolkit you need if you plan to create windows for your programs. The Integrated Development and Learning Environment (IDLE) require and depend on TkInter since it is a Python program with a GUI.

Also, for now, check the Python test suite feature. You will need it later. Finally, PIP is an optional feature that allows you to download Python packages later.

If you believe you do not need some of them, just make sure that the checkbox for IDLE and Python Test Suite are selected.

Using Python Shell and IDLE

There are two ways to run a Python program. And that is using its runtime environment or using the command line interpreter. The command line interpreter has two forms. The first one is the regular Python shell. The second one is IDLE or Integrated Development and Learning Environment.

The regular Python shell uses the familiar command line interface (CLI) or terminal look while IDLE is a Python program encased in a regular graphical user interface (GUI) window. IDLE is full of easy to access menu, customization options, and GUI functions while the Python shell is devoid of those and only offer a command prompt (i.e. the input field in a text-based user interface screen).

One of the beneficial functions of IDLE is its syntax highlighting. The syntax highlighting function makes it easier for programmers or scripters to identify between keywords, operators, variables, and numeric literals.

Also, you can customize the highlight color and the font properties displayed on IDLE. With the shell, you only get a monospaced font, white font color, and black background.

All of the examples in this book are written in the Python shell. However, it is okay for you to write using IDLE. It is suited for beginners since they do not need to worry about indentation and code management. Not to mention that the syntax highlighting is truly beneficial.

Writing Your First Program

To get you started, code the below Hello World program. It has been a tradition for new programmers to start their learning with this simple program. Just write this line in the shell or IDLE and press Enter.

>>> print("Hello World!")

Hello World!

>>> _

Shell, IDLE, and Scripts Syntax

Programming languages, just like a regular human language like English, have grammar/writing rules or syntax. Syntax rules in programming languages are simple but strict.

Unlike humans, the computer and computer programs like compilers and interpreters cannot understand context. They require precise and proper statements to know what you want. A simple syntax error can stop your program from functioning or make the computer terminate your program.

This book will not discuss every syntax rules in this section. It will, instead, teach you one on a need-to-know basis. Syntax rules, after all, are dependent on the things you are writing. And since you do not actually have anything to write yet, this section will introduce you to the basic ones first.

Prompt

The Python Shell and IDLE has a prompt, which looks like this: >>>. You generally start writing your code after the prompt in the Python Shell and IDLE. However, remember that when you write code in a file, py script, or module, you do not need to write the prompt.

For example:

class thisClass():

def function1():

x = 1

print(x)

def function2():

pass

That is valid code.

Indentation

When programming, you will encounter or create code blocks. A code block is a piece of Python program text (or statement) that can be executed as a unit, such as a module, a class definition or a function body. They often end with a colon (:).

Some code blocks (like modules) are normally executed only once, others (like function bodies) may be executed many times. Any statement that will be grouped inside the code block must be indented.

By default and by practice, indentation is done with four spaces. You can do away with any number of spaces as long as the code block has a uniform number of spaces before each statement. For example:

def function1():

x = 1

print(x)

def function2():

y = "Sample Text"

print("Nothing to see here.")

That is perfectly valid code. You can also use tab, but it is not recommended since it can be confusing and you will get an error if you mix using tabs and spaces. Also, if you change the number of spaces for every line of code, you will get an error. Here is an example in the shell. Note the large space before print(x) on line 2.

>>> x = 1

>>>       print(x)

File "<stdin>", line 1

print(x)

^

IndentationError: unexpected indent

>>> _

By the way, a statement is a line of code or instruction.

Indentation Prompt

When using the Python Shell, it will tell you when to indent by using the prompt (...). For example:

>>> def function1():

x = 1

print(x)

>>> def function2():

y = "Sample Text"

print("Nothing to see here.")

>>> _

In IDLE, indentation will be automatic. And to escape an indentation or code block, you can just press Enter or go to the next line.

Python Shell Navigation

You cannot interact using a mouse with the Python Shell. Your mouse will be limited to the window’s context menu, window commands such as minimize, maximize, and close, and scrolling.

Also, you can perform marking (selecting), copying, and pasting, but you need to use the windows context menu for that using the mouse. You can also change the appearance of the window and shell by going through the properties menu.

Most of the navigation you can do in the shell is moving the navigation caret (the blinking white underscore). You can move it using the navigation keys (left and right arrow keys, PgUp, PgDn, Home, End, etcetera). The up and down arrow keys’ function is to browse through the previous lines you have written.

IDLE Navigation

The IDLE window is just like a regular GUI window. It contains a menu bar where you can access most of IDLE’s functionalities. Also, you can use the mouse directly on IDLE’s work area as if you are using a regular word processor.

You might need to take a quick look at the menu bar’s function for you to familiarize yourself with them. Unlike the Python shell, IDLE provides a lot more helpful features that can help you with programming.

Primarily, IDLE is the main tool you can use to develop Python programs. However, you are not limited to it. You can use other development environment or word processors to create your scripts.

Troubleshooting Installation Issues

First of all, make sure that you download the installation file from the website: https://www.python.org. Next, make sure that you chose the proper installation file for your operating system. There are dedicated installation files for Windows, MacOSX, and other UNIX based operating system.

If your computer is running on Windows XP, the latest release of Python will not work on it. You must install and use Python 3.4. Also, remember that there are two versions of each release: a 32-bit and a 64-bit version. If you are unsure if your computer is running on 32 or 64-bit, then just get the 32-bit version. Normally, the recommended installer that the site will provide contains both and will automatically detect which installer it will use.

Normally, you do not need to go to Python’s website to download the installation file if you are using a Linux distribution as an operating system. You can just use your system’s package manager.

Before installing Python, make sure that you have at least 100 MB free disk space. You can also edit the installation location of Python. However, take note of the location you specify if you wish to install Python in a different folder.

If the installer did not provide shortcuts for you, you can just create them. The Python shell is located in the root folder of your Python installation.

<Python installation folder>\python.exe

For example:

"C:\Python37\python.exe"

For IDLE, you can use its batch file located in

<Python installation folder>\Lib\idlelib\idle.bat

For example:

"C:\Python37\Lib\idlelib\idle.bat"

If you cannot find the idlelib folder inside the Python Lib folder, reinstall Python and make sure that IDLE is checked.

Practice Exercise

For now, familiarize yourself with the Python shell and IDLE. Try to discover the things you can do with them. Look at all the messages that it may send you as you enter information on it.

When it comes to IDLE, try to customize it (e.g. change the color theme from the default IDLE Classic to IDLE Dark). Explore all the other features and functions you can change. Have fun!

Chapter Summary

At this point, you are already a few steps away from writing code and creating programs. Remember that you need Python 3.x while learning the contents of this book. You also need to make sure that you have IDLE and the test suite.

With regards to the coding environment, you have two options: use the shell or IDLE. It is recommended that you use the latter. But if you want to do this intimately and be challenged a bit, you can choose the shell.

Did you know?

In 2009, Swedish programmer Markus “Notch” Persson released the first version of Minecraft, a building game he’d made. By 2014, Minecraft had around 100 million registered users and was sold to Microsoft for $2.5 billion.

Chapter 2

Variables and Operators

Before you learn about operators and variables, you need to have a brief understanding of how a computer functions and what a computer program is.

Computer Basics

A computer’s primary function is to compute, as its name suggests. It needs data to compute or process. The computer retrieves data from user input, programs, and other input sources like microphones, scanners, computer networks and even the Internet.

A computer has four important components:

- The central processing unit (CPU),

- Random-access memory (RAM),

- Motherboard (MB), and

- A power supply unit (PSU).

The RAM temporarily stores the data the CPU needs to process. The motherboard, which is basically a huge and complex circuit board, houses the CPU and RAM. The power supply, which also connects to the motherboard, supplies power to everything.

A computer can operate or boot (i.e. start up) with those four components alone. The absence of at least one of those components will render the computer unable to boot. Some older computers that do not have built-in graphics processors will require a graphics card to operate.

Other components like keyboards, hard disks, monitors, and graphics cards are additional peripherals you can install to extend the functionality of a computer.

The motherboard also houses the basic input output system (BIOS) chip, which stores a program that allows a computer to operate with only the most basic functionalities.

The BIOS allows the computer to accept basic input and provide basic output. Some basic input processes are accepting keyboard strokes and mouse clicks and movements. Some basic output processes are text and image monitor display and beep sounds.

Aside from handling input and output, the BIOS finds and initializes all hardware in the motherboard. It detects and initializes graphics/video cards, sound cards, ethernet adapters, keyboards, mice, mass storage medias (USB drives, hard disk drives (HDD), solid state drives (SSD), etc.), and other built-in functionalities of the mother board.

The BIOS allows the user to perform customization of the motherboard and basic hardware settings. It also allows the booting process of an operating system from a mass storage device or network.

Computer Program

A computer program is a set of data that contains instructions for the computer to follow. It tells a computer the computation it needs to work on. It retrieves the relevant data and then directs the computer with regards to which data to process. Furthermore, it tells the computer where to output the result of the computation(s).

The BIOS is a good example of a computer program. It is the very first thing that the computer runs when it boots. It gathers data from the hardware as input and typically displays them on the screen, in a readable format, as output.

It gives you time to provide an input from your keyboard. If it does not receive any input from you after a set period of time, it will proceed to find a suitable source of an operating system’s boot file. The BIOS program and its processes are almost unnoticeable, but it happens all the time when you open a computer.

Another good example of a computer program is the calculator program on your computer or smartphone. The program waits for your input. Your input or command can either be in the form of a number, operator, or a function. Inputting the number 1, the addition operator, the number 1 again, and the equals sign will make the program instruct the computer to add the two numbers and display the result on your screen.

Most computer programs behave this way. They require input to create an output. They need data to process. Some programs may not require input from the user, but they still process data and get them from other input sources such as your computer and the programs themselves.

What Are Variables?

The computer stores the data that your program uses or will use in its RAM. To do this, the computer first finds an empty space in the RAM and allocates that space for the data your program needs. All the computer needs to do when the program and computer needs the data is to find that space and retrieve it. The name given to the specific location (within the RAM) where the data is stored is the variable. In other words, a variable is a named location of data.

Do note that the RAM is like a hotel that only offers transient lodging. The main difference is that the RAM has thousands and millions of rooms /addresses depending on its size. The computer searches for a vacant room or address when it needs to store data. The computer finds a room, gives the room number to the program, and the program instructs the computer to store the data to that room number.

This process is a relatively easy task for the computer and your computer program. However, it can be problematic for you as the computer programmer. Why? Remember that the RAM is a huge hotel with thousands and millions of rooms, and data comes in and out of it every second your computer is on.

Say that you have a text data that contains the word “Pedro”. You want the program to store that information in the computer. The computer will then find space for it in the RAM.

The computer finds room 1,151,112 vacant and assigns/stores “Pedro” in it. When it is time for you to call or reference “Pedro”, you need to tell the computer that you want the program to retrieve “Pedro” from room 1,151,112. Seems easy, right? Bear in mind that in programming, memory addresses are often written using hexadecimal notation (i.e. a convenient way to express binary numbers in modern computers in which a byte is almost always defined as containing eight binary digits). The room number 1,151,112 is written as 0x119088 in hexadecimal notation. This simple resource will show you how to convert a decimal to hexadecimal.

The first problem is that the RAM is a transient hotel. The location of the data you will store will be definitely in a different room number if 1,151,112 happen to be occupied when you start the program again. Memorizing the room number or address is already a difficult thing.

You might think that a good solution is to instruct the computer to find the text “Pedro”, right? It seems reasonable, but what if your text data contains all the text in a Harry Potter book? You cannot type all of those in your computer program repeatedly just to find it in your computer’s RAM. Also, what if your data is an image? You cannot search an image by using text.

The second problem is data duplicates. What if other programs have a text data “Pedro” as well? Things can get messy quickly if you reference data from another program. What will happen to the other program who actually own that data if you process and change that data?

The solution to the aforementioned problems is to make use of variables. Variables have three basic components: data, identifier, and address. You already know what data is. The address, on the other hand, is its location or address in your computer’s RAM. The identifier is a letter, word, or combination of letters, numbers, and symbols, which you can use to name the address of your data.

For example, instead of memorizing the room number/address of your data, you can just tag it with a name. Say that the computer assigned the text data “Pedro” to room 1,234,456. Instead of referencing that room number to find “Pedro”, you can assign an identifier to it like textName (i.e. textName = Pedro)

The computer program creates a directory of sorts, which contains pointers to your data in the memory, to make it easier for it and you to find the data in RAM. Here is a sample variable directory for a simple calculator program that is going to perform an addition operation to the numbers 12 and 436:

Identifier

Data

Memory Address

firstNumber

12

0xff456e

secondNumber

436

0x5e4775

operation

“+”

0x6f1106

result

448

0x1ca607

In older programming languages, you needed to deal with memory addresses. In modern programming languages, the compiler will handle most memory related concerns like storing and garbage collection (i.e. freeing up space in the RAM by removing unused/redundant data).

Aside from identifier, data, and addresses variables also have other components such as data type and size. Strong typed programming languages like C and Java requires programmers to declare the variable and the type of data it will contain. Stronger and stricter programming languages like Pascal require declaration of the variable and its size and type.

Python is also a strong typed language, but it does not require programmers to declare variables and its type. For example, creating a variable in Python is as simple as assigning a value or data to an identifier.

>>> x = 1

>>> _

With that simple statement, the program will create the variable x and assign a value of 1 to it. If you type the variable’s identifiers in the command line, the interface will return its value.

>>> x

1

>>> _

Remember that if a variable does not exist in the program, Python or your program will return an error. For example:

>>> y

Traceback (most recent call last):

File “<stdin>”, line 1, in <module>

NameError: name ‘y’ is not defined

>>> _

The above error message might appear as gibberish for beginners. Fear not, later in this book, I will show you how to read and handle errors.

Naming Variables

You must remember the following rules when creating and using an identifier or name for your variable:

1. Your identifier must start with either an underscore or a letter.

2. Your identifier must never start with a number. The program will return an error if this occurs. Your program and Python will consider any number you type after a space as a number. You cannot use a number as an identifier. Your numbers cannot contain letters or symbols except when writing in a different numeric notation (e.g., hexadecimal 0x12E4).

3. Your identifier must only contain letters, numbers, and underscores.

4. Your identifier is case sensitive. This means that identifier X is different from identifier x.

5. Your identifier can be as short as 1 character (e.g., x, _, y, etc.).

6. Your identifier must not be the same as a keyword (these are reserved words e.g. return, True, False etc.) or a function.

Not following or adhering to these simple rules may lead to errors or unintended results in your program.

Using Variables

The primary function of variables is to store data. Storing data in a variable is as simple as using the assignment operator (=). Here is an example:

>>> x = 1

>>> _

In the example, the lines of codes created the variable x and assigned the number 1 to it. Assigning a variable is like Algebra. The assignment statement reads x is equal to 1. It can also be read as x has a value of 1 or 1 is assigned to x.

You can also assign the value of a variable to another variable. For example:

>>> a = 10

>>> b = a

>>> b

10

>>> _

There are other ways of assigning data to variables. One of them is assigning the result of an expression or operation to a variable, which will be discussed later.

Naming Conventions

You can easily get errors by being too careless with the identifiers you create. For one, you can receive an error by using variable THIS_IS_A_VARIABLE instead of this_is_a_variable. To prevent variable naming errors, you must follow or create your own naming convention. As a beginner, you should follow these tips first as your guide in creating identifiers.

Naming by Description

The best practice when it comes to naming variables is to name it using its description. Descriptions are memorable and descriptive words are easier to type than just typing random combination of letters or words. Also, other people who will look at your code can easily understand the context, purpose, and data type of your variables with description.

For example:

>>> christmas = "December 25"

>>> name = "John Doe"

>>> age = 25

>>> _

This kind of naming style is simple but can easily go out of hand quick. Remember that you can use one-word identifier or description when your program is still small. Bigger programs or projects can easily force you to create long identifiers and descriptions. Why? For one, this is to avoid different variables having the same identifier. Second, it makes variable management easier.

Here are some variable naming scenarios that you will encounter along the way.

Scenario 1:

>>> employeename1 = "Garett Jones"

>>> employeename1 = "John Doe"

>>> _

Scenario 2:

>>> firstname = "John"

>>> lastname = "Doe"

>>> _

In these scenarios where you are forced to use more than one word for descriptions, you need to establish how you arrange and present them. One of the most common naming conventions that programmers use in these kinds of scenarios is Camel Case typing.

For example:

>>> employeeName1 = "Garett Jones"

>>> employeeName2 = "John Doe"

>>> _

Scenario 2:

>>> firstName = "John"

>>> lastName = "Doe"

>>> _

Another convention is to use underscores.

>>> employee_name_1 = "Garett Jones"

>>> employee_name_2 = "John Doe"

>>> _

Scenario 2:

>>> first_name = "John"

>>> last_name = "Doe"

>>> _

You must enforce uniformity when working with multiple word identifiers or descriptions. You must create a naming structure to make the names more organized, memorable, and easier to type. A rule of thumb is to write the description in this format: noun/object + adjective/property + adverb.

For example:

>>> employee1_name_first = "John"

>>> employee2_name_last = "Doe"

>>> _

Of course, this is just a naming convention. It is not a rule, but it does help in organizing your variables. Also, most of the scenarios listed in this section can be solved by taking advantage of arrays, objects, and classes. Most of those will be discussed much later in this book.

Another scenario that you will encounter has to do with variables having the same description but different data types.

For example:

>>> employee_number = "emp-107012005"

>>> employee_number = 107012005

>>> _

What you can do is to add prefixes on your variables.

For example:

>>> str_employee_number = "emp-107012005"

>>> int_employee_number = 107012005

>>> _

Data types will be discussed later.

There are multiple naming conventions that you can use or apply in your programs. You can even create one of your own if you like. However, if you have other people working with you and your program, it is best that you set the naming convention standard for your project.

Introduction to Expressions and Python Operators

At this point, you already know how to store and access data in your program. The next part is processing them. Programming languages have operators. They can manipulate and process data. You code expressions when using operators.

Expressions

Expressions are lines of codes that perform operations using operators, which the program or computer evaluates to return a result. The term expression in programming is like Algebraic expressions wherein you have variables or data placed on the left and right side of an operator. For example, 1 + 2 is an expression.

Expressions have multiple components. They are constants, variables, data, operators, delimiters, parentheses, functions, and results or output. In the expression 1 + 2, 1 and 2 are data, + is the operator, and 3 is the output.

There are multiple types of expressions. Some of them are arithmetic, relational/comparison, Boolean/logical, string, bitwise, and mixed expressions. The type of expression you create depends on the operators you use and the data type of your expected result.

Your program is all about expressions. Expression mostly dictates the processing of data in your program. You can also use it in different scenarios. And one of the most common scenarios is to assign an output of an expression to a variable.

Example 1:

>>> x = 1 + 2

>>> x

3

>>> _

Example 2:

>>> operandFirst = 1

>>> operandSecond = 2

>>> output = operandFirst + operandSecond

>>> output

3

>>> _

Operators

Python, much like with many other programming languages, have numerous operators like arithmetic operators addition (+), subtraction (-), multiplication (*), and division (/). Some of those operators have similar functionalities in most programing languages.

Operators are divided according to their functionality and the data type of expression or output that they produce. Most operators use signs and symbols while some use keywords. Some operators that perform uncommon or advanced data processing use functions.

Note that not adding space between operands and operators will work. However, it is best that you avoid typing expressions like that to prevent any potential syntax errors.

Arithmetic Operators

Operation

Operator

Description

Example

Addition

+

Adds numbers

>>> 1 + 1

2

>>> _

Subtraction

-

Subtracts numbers

>>> 10 - 12

-2

>>> _

Multiplication

*

Multiplies numbers

>>> 42 * 35

1470

>>> _

Division

/

Divides the left-hand number by the right-hand number

>>> 132 / 11

12

>>> _

Floor Division

//

Divides the left-hand number by the right-hand number and returns only the whole number, effectively removing any decimal value, from the quotient

>>> 10 // 3

3

>>> _

Modulus

%

Performs a floor division on the left-hand number by the right-hand number and returns the remainder

>>> 133 / 11

1

>>> _

Exponent

**

Raises the left-hand number by the right-hand power

>>> 4 ** 2

16

>>> _

Relational Operators

Operation

Operator

Description

Example

Is Equal to

==

Returns true if left and right hand sides are equal

>>> 999 == 999

True

>>> _

Is Not Equal to

!=

Returns true if left and right hand sides are not equal

>>> 24 != 123

True

>>> _

Is Greater Than

>

Returns true if left-hand side’s value is greater than the right-hand’s side

>>> 554 > 64

True

>>> _

Is Less Than

<

Returns true if left-hand side’s value is lesser than the right-hand’s side

>>> 16 < 664

True

>>> _

Is Equal or Greater Than

>=

Returns true if left-hand side’s value is greater or equal than the right-hand’s side

>>> 554 >= 64

True

>>> 554 >= 554

True

>>> _

Is Equal or Less Than

<=

Returns true if left-hand side’s value is lesser or equal than the right-hand’s side

>>> 16 <= 664

True

>>> 16 <= 16

True

>>> _

Assignment Operator

Operation

Operator

Description

Example

Assign

=

Assigns the value of the right-hand operand to the variable on the left

>>> x = 1

>>> x

1

>>> _

Add and Assign

+=

Adds the value of the left variable and the value of the right-hand operand and assign the result to the left variable

>>> x = 14

>>> x

14

>>> x += 16

>>> x

30

>>> _

Subtract and Assign

-=

Subtracts the value of the left variable and the value of the right-hand operand and assign the result to the left variable

>>> x = 30

>>> x

30

>>> x -= 4

>>> x

26

>>> _

Multiply and Assign

*=

Multiplies the value of the left variable and the value of the right-hand operand and assign the result to the left variable

>>> x = 26

>>> x

26

>>> x *= 10

>>> x

260

>>> _

Divide and Assign

/=

Divides the value of the left variable by the value of the right-hand operand and assign the result to the left variable

>>> x = 260

>>> x

260

>>> x /= 13

>>> x

20

>>> _

Floor Divide and Assign

//=

Performs a floor division on the value of the left variable by the value of the right-hand operand and assign the quotient as a whole number to the left variable

>>> x = 20

>>> x

20

>>> x //= 3

>>> x

6

>>> _

Modulus and Assign

%=

Performs a floor division on the value of the left variable by the value of the right-hand operand and assign the remainder of the quotient to the left variable

>>> x = 6

>>> x

6

>>> x %= 4

>>> x

2

>>> _

Exponent/Raise and Assign

%=

Raises the value of the left variable by the power of the value of the right-hand operand and assign the result to the left variable

>>> x = 2

>>> x

2

>>> x **= 3

>>> x

8

>>> _

Logical Operators

Operation

Operator

Description

Example

Logical And

and

Returns true if both of the operands are true

>>> True and True

True

>>> _

Logical Or

or

Returns true if at least one of the operands is true

>>> True or False

True

>>> _

Logical Not

NOT

Returns the negated logical state of the operand

>>> not True

False

>>> _

Truth Table

The operator and will only return True if both of the operands are True. It will always return False otherwise. The operator or will only return False if both operands are False. Otherwise, it will always return True. The operator not will return False if the operand is True and will return True if the operand is False.

Below are truth tables for operator ‘and’ and ‘or’.

Left Operand

Logical Operator

Right Operand

Result

True

And

True

True

True

False

False

False

True

False

False

False

False

Left Operand

Logical Operator

Right Operand

Result

True

or

True

True

True

False

True

False

True

True

False

False

False

Membership Operators

Operation

Operator

Description

Example

In

In

Returns True if left operand’s value is present in the value of the right operand

>>> x = "cat and dog"

>>> a = "cat"

>>> b = "dog"

>>> c = "mouse"

>>> a in x

True

>>> b in x

True

>>> c in x

False

>>> _

Not In

not in

Returns true if left operand’s value is not present in the value of the right operand

>>> x = "cat and dog"

>>> a = "cat"

>>> b = "dog"

>>> c = "mouse"

>>> a not in x

False

>>> b not in x

False

>>> c not in x

True

>>> _

Identity Operators

Operation

Operator

Description

Example

Is

is

Returns True if left operand’s identity is the same with the identity of the right operand

Note: If may appear that it returns True if the values of the operands are equal, but Python evaluates the identity or ID and not the values.

Equal values of a single data or variable tend to receive similar IDs. Results of expressions may receive new IDs or overlap with existing IDs with similar values.

To check the ID of variables and data, you need to use the id() keyword/function.

If you want to compare if values of the operands are equal, use == operator instead.

>>> x = "a"

>>> id(x)

34232504

>>> id("a")

34232504

>>> x is "a"

True

>>> x * 2

'aa'

>>> x * 2 is "aa"

False

>>> id(x * 2)

39908384

>>> id("aa")

39908552

>>> x * 2 is 2 * x

False

>>> id(x * 2)

39908552

>>> id(2 * x)

39908384

>>> _

Is Not

is not

Returns True if left operand’s identity is not the same with the identity of the right operand

>>> x = "a"

>>> id(x)

34232504

>>> id("a")

34232504

>>> x is not "a"

False

>>> x * 2

'aa'

>>> x * 2 is not "aa"

True

>>> _

Bitwise Operators

Operation

Operator

Description

Example

Bitwise And (AND)

&

Returns 1 for bits if both operands have 1 on the same place value. Returns 0 for 0-0, 1-0, and 0-1 combinations.

>>> 0b1101 & 0b1001

9

>>> bin(9)

‘0b1001'

>>> _

Bitwise Or (OR)

|

Returns 0 for bits if both operands have 0 on the same place value. Returns 1 for 1-1, 1-0, and 0-1 combinations.

>>> 0b1101 | 0b1001

13

>>> bin(13)

‘0b1101'

>>> _

Bitwise Exclusive Or (XOR)

^

Returns 1 for bits if both operands have 0 and 1 on the same place value. Returns 0 for 1-1 and 0-0 combinations.

>>> 0b1101 ^ 0b1001

4

>>> bin(4)

‘0b100'

>>> _

Bitwise Complement

~

Flips each bit and negates the value

>>> ~0b1010

-11

>>> bin(-11)

'-0b1011

>>> _

Bitwise Left Shift

<<

Moves bits of the left operand to left. The number of shifting of bits is according to the value of the right operand.

>>> 0b1010 << 2

40

>>> bin(40)

'0b101000'

>>> _

Bitwise Left Shift

>>

Moves bits of the left operand to right. The number of shifting of bits is according to the value of the right operand.

>>> 0b1010 >> 2

2

>>> bin(2)

'0b10'

>>> _

Below are truth tables for operator ‘and’, ‘or’, and ‘xor’.

Left Operand

Logical Operator

Right Operand

Result

1

&

1

1

1

0

0

0

1

0

0

0

0

Left Operand

Logical Operator

Right Operand

Result

1

|

1

1

1

0

1

0

1

1

0

0

0

Left Operand

Logical Operator

Right Operand

Result

1

^

1

0

1

0

1

0

1

1

0

0

0

Practice Exercise

Create code for the following scenarios.

1. Create 5 separate expressions that will lead to a result of 10025. You cannot use an arithmetic operator more than once and your first number must be 7.

2. Find the statistical mean of 10 survey respondents’ ages. The ages are 18, 21, 19, 52, 6, 33, 15, 46, 72, and 25.

3. Find the value of x using these details:

1. x = y + (a * b / c)

2. y = a + 151

3. b = c * (144 + y)

4. y = 10

5. c = 7

4. Johnny was born on February 14, 1967. How many days old was he on January 1, 2000?

5. A car was moving 20 miles per hour on a straight road. Every five minutes, it instantly decelerates by 5 miles per hour and keeps that speed for a minute and then instantly accelerates back to 20 miles per hour. How many miles will the car cover if it moves like that for an hour?

Chapter Summary

Throughout your programming career, you will deal with variables and operators. They are the core elements in a program. After all, programs are all about data. Without variables, it will be difficult to keep track and process data. In fact, without operators your program will not process anything.

The more operators you know, the more versatile your program will be. However, it does not mean that you will always use all the operators in your program.

Remember that you do not need to force yourself to use complicated operations just because they make your program look complex. If a regular operator can get you the results you need, use it. Always prioritize simplicity over complexity and aesthetics.

When it comes to identifiers, always make sure that they are contextual. Your variables’ purpose and content should be easily known by just reading their identifiers. Even people who are not working on your program or who do not know how to program should be able to identify your variables.

Congratulations on your progress so far! Now that you know how to process data and where to keep them, it is time for you to know the types of data which are available in Python and you can use in your program.

Chapter 2: Solution

Question 1

>>> 7 * 1432

10024

>>> 7 + 10017

10024

>>> 7 - -10017

10024

>>> 7 / 0.0006983240223463687

10024.0

>>> 7 // 0.0006983

10024.0

>>> _

Question 2

>>> (18 + 21 + 19 + 52 + 6 + 33 + 15 + 46 + 72 + 25) / 10

30.7

>>> _

Question 3

>>> c = 7

>>> y = 10

>>> b = c * (144 + y)

>>> b

1078

>>> a = y - 151

>>> a

-141

>>> x = y + (a * b / c)

>>> x

-21704.0

>>> _

Question 4

To solve this question, we need to find out the difference (in days) between January 1, 2000 and February 14, 1967. There are 33 years counting from year 1967 to year 2000. In order to convert to days we need to multiply this with 365.25.

In addition, there are 44 days between January 1 and February 14. That is from January 1 to January 31 is a total of 30 days. We then have an additional 14 days in February.

Therefore:

>>> ((2000 – 1967) * 365.25) – 44)

12009.25

>>> _

Question 5

Let us begin with what we know.

The car travelled in two phases. In phase 1, it travelled at 20 miles per hour for 5 minutes (1/12hr). In the second phase, it travelled at 15 miles per hour (after 5 miles per hour deceleration) for one minute (1/60hr).

Duration is the amount of time spent in a given phase. From the question, we know that duration1 is 5 times duration 2.

Since the speed and deceleration is in miles per hour, we convert all the time spent in each phase from minute(s) to hour for uniformity sake. Hence 5 minutes is 1/12hr etc.

The car travelled for a total of 1 hour hence totalTime = 1

Therefore, we have the below:

>>> totalTime = 1

>>> time1 = 1/12

>>> time2 = 1/60

>>> speed1 = 20

>>> deceleration = 5

>>> speed2 = speed1 - deceleration

>>> duration1 = totalTime*((time1)/ (time1 + time2))

>>> duration2 = totalTime*((time2)/(time1 + time2))

>>> distance1 = speed1 * duration1

>>> distance2 = speed2 * duration2

>>> totalDistance = distance1 + distance2

>>> totalDistance

19.166666666666668

>>> _

Ever wondered why it’s called Python?

There’s an interesting story about it. While implementing Python, Van Rossum was also reading the published scripts from “Monty Python’s Flying Circus”, a BBC comedy series in the 1970s. Since he wanted a short, unique and slightly mysterious name for his invention, he got inspired by the series and named it Python!

Chapter 3

Simple Data Types

I can’t stress enough the fact that computer programs revolve around data. Because of this, you should endeavor to master the types of data that you will encounter and use in Python programming.

Before anything else, familiarize yourself with the term literals. Literals are pieces of data that are written plainly in your program code. For example:

>>> x = 1

>>> y = "This is a string literal"

>>> _

The number (on line 1) is a numeric literal and the words enclosed in the quotes (on line 2) are string literals.

Numbers

In Python, there are four types of number data types. They are integers, long, float, and complex.

Signed Integers:

Integers (int), or signed integers, are whole numbers. Its value ranges from negative numbers to 0 to positive numbers. Basically, they are numbers without a decimal point. Integers have a numerical limit. If the value of the integer goes beyond a certain limit, the data type of the integer transforms into a long integer.

Long Integers:

Long integers (long) are also whole numbers similar to signed integers. The only difference is that long integers do not have a numerical limit. Note that all integers in Python 3 are now long by default i.e. what was long in Python 2 is now the standard int type in Python 3.

Floating Point Real Values:

Floating point real values (floats) represent real numbers. They are written with a decimal point dividing the integer and fractional parts. Floats can be written using the usual method of typing in numbers:

>>> float (2)

>>> 2.0

>>> _

or it can be written using scientific notation that includes the usage of e in the number.

>>> 2.5e2

>>> 250.0

>>> _

Complex Numbers:

A complex number is a number that can be expressed in the form a + bi, where a and b are real numbers and i is a solution of the equation x^2 = -1. Because no real number satisfies this equation, i is called an imaginary or irrational number. For the complex number, a + bi, a is called the real part and b is called the imaginary part.

An example of an irrational number is the square root of 2. Since the square root of 2 does not provide an exact numerical value, it is much better to use it in form of an irrational number or imaginary number.

String

Strings are combination of numbers, letters, and symbols enclosed within quotations. Remember that anything outside quotation marks is treated as identifiers, keywords, numbers, or operators. You can use either single or double quotes to enclose strings.

For example:

>>> x = "This is a string"

>>> x

'This is a string'

>>> _

Combining/Concatenating strings

You can combine or concatenate strings using the addition operator (+).

For example:

>>> y = "This is "

>>> z = "a string."

>>> x = y + z

>>> x

'This is a string.'

>>> _

Avoiding Type Errors with Conversion Functions

Dealing with multiple data types can be confusing for beginners. For example, do you consider "2" as a number? If you say yes, then you will tend to receive a lot of datatype error. For example:

>>> 2 + "2"

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: unsupported operand type(s) for +: 'int' and 'str'

>>> _

As you can see in the error message, the second operand was considered as a "str" or string. Always remember that most operations will work as intended if you use the appropriate data type.

However, there will be times that you will receive input that are of a different type. For example:

>>> 2 + input()

2

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: unsupported operand type(s) for +: 'int' and 'str'

>>> x = input()

2

>>> x

'2'

>>> _

The keyword input() makes the shell ask for something to be typed on the command line from the user. As you can see, the number 2 was input without quotes, but when its value was checked, it was converted to a string.

You can mitigate this by using conversion functions. For example:

>>> 2 + int(input())

2

4

>>> x = int(input())

2

>>> x

2

>>> _

The example used the int() function to convert literals to integers. Note the word literals. The int() function does not only convert strings, but it also converts other data types. For example:

>>> int(23.5412341231)

23

>>> int(True)

1

>>> int(False)

0

>>> _

Another handy function that convert data types is str(). As it name implies, it converts literals to strings. For example:

>>> str(2)

'2'

>>> str(251.12312)

'251.12312'

>>> str(True)

'True'

>>> str(False)

'False'

>>> _

There are other functions that can be used for data type conversion such as float(), hex(), bin(), and bool(). You can easily guess the data types they result to by their identifiers alone.

Avoiding, Replacing, and Stripping Whitespace

Considering whitespace as a problem is a debatable topic. Whitespaces are tabs, new lines, leading and trailing spaces.

There are two instances where they can be considered an issue: inside a string and within your code. Be that as it may, they are mostly trivial and not code breaking.

Trailing spaces (i.e. all the whitespaces located at the end of a line) from input data often is not a problem caused by programmers but mostly users and other input sources. For example, if you are using Python to create a program to handle server side scripts, it will often encounter inputs that contain trailing whitespace (e.g., HTML text).

To remove both trailing and leading spaces, You can use the strip() method of the string class. For example:

>>> x = "       This       is   spaced        badly.      "

>>> x.strip()

'This       is   spaced        badly.'

>>> _

Note – the internal spaces are preserved.

If the problem is trailing spaces, you can use rstrip() to get rid of it. Conversely, you can use lstrip() to get rid of just the leading space.

>>> x = "       This       is   spaced        badly.      "

>>> x.rstrip()

'       This       is   spaced        badly.'

>>> _

>>> x = "       This       is   spaced        badly.      "

>>> x.lstrip()

'This       is   spaced        badly.    '

>>> _

Another way to remove both the leading and trailing space is to nest the methods together:

>>> x = "       This       is   spaced        badly.      "

>>> x.strip().rstrip()

'This       is   spaced        badly.'

>>> _

Or you can do it this way:

>>> x = "       This       is   spaced        badly.      "

>>> (x.strip()).rstrip()

'This       is   spaced        badly.'

>>> _

Note that strip() and rstrip() also remove leading and trailing tabs and new line characters.

>>> x = "\t       This       is   spaced        badly.      \n"

>>> x.strip()

'This       is   spaced        badly.'

>>> x.rstrip()

'\t       This       is   spaced        badly.'

>>> _

Note that \t and \n are escape character combination for tab and new line respectively. These combinations start with the escape character "\"Escape character combinations help you input irregular characters into your strings such as tabs and new line characters.

It also allows you to type in characters that may pose a problem when you just plainly type them on your keyboard such as \\, \r, \", and \'. For example:

>>> print("\tHello\nWorld!\n\"This is another way to type quotes\"")

Hello

World!

"This is another way to type quotes"

>>> _

How can you remove the repeating spaces in the middle of the string? You can use the replace() method for that. For example:

>>> x = "       This       is   spaced       badly.      "

>>> x.replace("  ", "")

' This is spaced badly. '

>>> _

The replace() method was used to replace two spaces with an empty string. Basically, it will progressively remove all the two spaces until single spaces remains.

Avoiding syntax errors with strings

The primary method of avoiding syntax errors when working with strings is to make sure that you have properly enclosed the string inside a pair of quotation marks.

Improper String:

>>> x = "This is a string.'

File "<stdin>", line 1

x = "This is a string.'

^

SyntaxError: EOL while scanning string literal.

>>> _

Proper String:

>>> x = "This is a string."

>>> x

'This is a string.'

>>> _

Note that you should close a double quotation mark with a double quotation mark, and close a single quotation mark with a single quotation mark. Here is another example:

Improper String:

>>> x = "Then Mark said, "Don’t you dare touch that!""

File "<stdin>", line 1

x = "Then Mark said, "Don’t you dare touch that!""

^

SyntaxError: EOL while scanning string literal

>>> _

If your string has a quotation mark, enclose it with a different quotation mark. For example:

>>> x = 'Then Mark said, "Don't you dare touch that!"'

File "<stdin>", line 1

x = 'Then Mark said, "Don't you dare touch that!"'

^

SyntaxError: EOL while scanning string literal

>>> _

The previous example should have worked, but remember that the word “don’t” uses a single quotation mark, which basically made the interpreter think that the single quote ended the string literal. If you take the single quote out, the statement will work.

>>> x = 'Then Mark said, "Dont you dare touch that!"'

>>> x

'Then Mark said, "Dont you dare touch that!"'

>>> _

The simple rule is to not use the quotation mark you used to enclose the string to prevent errors.

The previous solution worked, but it ruined your intended value. If you need to use both types of quotation marks, you can use concatenation. For example:

>>> x = 'Then Mark said, "'

>>> y = "Don't you dare touch that!"

>>> z = x + y + '"'

>>> z

'Then Mark said, Don't you dare touch that!"'

>>> _

Collections/Sequences

A collection or a sequence is a collection of literals or data in a variable. In other programming languages, it can be considered as an array. There are four types of arrays or collections in Python.

1. List

2. Tuple

3. Set

4. Dictionary

List

A list is a collection that is ordered and changeable. It also allows duplicate members. The comma separator separates the pieces of data or literals assigned to a list. Here is a simple example of a list:

>>> sampleList = ["Data 1", "Data 2", "Data 3"]

>>> sampleList

['Data 1', 'Data 2', 'Data 3']

>>> _

Each data included in the list receives an index according to its position in the assignment. The index starts with 0. In the example, "Data 1" will receive an index of 0, "Data 2" will receive an index of 1, and "Data 3" will receive an index of 2.

You can assign numbers, strings, or a mix of literals in a list. For example:

>>> sampleList = ["Data 1", 11241, 0b101101]

>>> sampeList

['Data 1', 11241, 45]

>>> _

Accessing elements in a list

To access an element or entry in a list, you can just type the name of the list identifiers together with a pair of square brackets containing the index of the data you want to access. For example:

>>> sampleList = ["Data 1", 11241, 0b101101]

>>> sampleList[0]

'Data 1'

>>> sampleList[1]

11241

>>> sampleList[2]

45

>>> _

Index positions

Keep in mind that using a negative index will result in you accessing the list elements in reverse. The last element in the list will have the index of -1, and so on. For example:

Note - 0b101101 is the binary representation of 45

>>> sampleList = ["Data 1", 11241, 0b101101]

>>> sampleList[-1]

45

>>> sampleList[-2]

11241

>>> sampleList[-3]

'Data 1'

>>> _

Using individual values from a list

You can assign an individual value from a list to a variable. For example:

>>> sampleList = ["This is a string", 1, 2, 3]

>>> x = sampleList[0]

>>> x

'This is a string'

>>> _

You can access multiple list items in a sequence by using the colon or slice (:) operator. The left hand side of the colon indicates the starting index of the sequence and the right hand side of the colon indicates where the slice stops. For example:

>>> sampleList = ["Data 1", 11241, 0b101101]

>>> sampleList[1:3]

[11241, 45]

>>> _

Changing, Adding and Removing Elements

Changing the value of an item in the list can easily be achieved by assigning a value to it. For example:

>>> sampleList = ["This will be changed", 1, 2, 3]

>>> sampleList[0]

'This will be changed'

>>> sampleList[0] = "This is a new string"

>>> sampleList[0]

'This is a new string'

>>> sampleList

['This is a new string', 1, 2, 3]

>>> _

Adding an element to a list is as simple as using the addition or concatenate (+) operator. For example:

>>> sampleList = [1, 2, 3, 4]

>>> sampleList = sampleList + [5]

>>> sampleList

[1, 2, 3, 4, 5]

>>> _

An alternative way to do this is to use the assign and add/concatenate (+=) operator.

>>> sampleList = [1, 2, 3, 4]

>>> sampleList += [5]

>>> sampleList

[1, 2, 3, 4, 5]

>>> _

Deleting an item inside a list requires the use of the del keyword and accessing the item that you want to be deleted. For example:

>>> sampleList = [1, 2, 3]

>>> del sampleList[0]

>>> sampleList

[2, 3]

>>> _

Note that when you delete an item in the list, the index of all that items that comes after its position will be shifted left. In the previous example, since you delete the item 0 that contains the value, the items with the index 1 and 2 will become index 0 and 1. So if you access index 0, the program will return the value of 2.

If you do not want that to happen, you can leave and just ignore the value of the item or you can just set it to zero or blank if the value is a string. For example:

>>> sampleList = ["This is a string", 1, 2, 3]

>>> sampleList[0] = ""

>>> sampleList[1] = 0

>>> sampleList

["", 0, 2, 3]

>>> _

Another way of removing an item from the list is using the remove() method. For example:

>>> sampleList = [1, 2, 3]

>>> sampleList.remove(1)

>>> sampleList

[2, 3]

>>> _

Note that the remove() method removes the item, with the lowest index, of the same value that was used as an argument in the parentheses. For example:

>>> sampleList = [1, 2, 3, 1, 1, 1]

>>> sampleList.remove(1)

>>> sampleList

[2, 3, 1, 1, 1]

>>> _

List Operations, Expressions, and Methods

Remember that everything in Python is an object. This means that lists have their innate methods. They also behave as strings, which means they can use string operations such as concatenation. To find out what an object’s innate methods and attributes are, you can use the dir function. For example:

>>> sampleList = [1, 2, 3, 4, 5]

>>> dir(sampleList)

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

>>> _

A few of the important methods you will frequently use with lists are: sort, reverse and count.

A few of the important built-in functions that you will frequently use with lists are: sorted, reversed, and len.

Sorting a list permanently

To sort a list permanently, you need to use list’s sort() method. For example:

>>> numberList = [5, 4, 3, 2, 1]

>>> numberList.sort()

>>> numberList

[1, 2, 3, 4, 5]

>>> _

Sorting a list temporarily

To sort a list temporarily, you need to use the built-in function sorted(). For example:

>>> numberList = [5, 4, 3, 2, 1]

>>> sorted(numberList)

[1, 2, 3, 4, 5]

>>> _

Printing a list in reverse order

Returning a reversed order of a list temporarily is a bit tricky. To do this, you will need to perform a slice. For example

>>> numberList = [1, 2, 3, 4, 5]

>>> numberList[::-1]

[5, 4, 3, 2, 1]

>>> _

Note that this only reverses the order of the items in the list. It does not perform a sort. Here is another example:

>>> numberList = [7, 6, 4, 2, 1, 8]

>>> numberList[::-1]

[8, 1, 2, 4, 6, 7]

>>> _

Finding the length of a list

To find the length of a list, you can use the built-in function len(). For example:

>>> numberList = [5, 4, 3, 2, 1]

>>> len(numberList)

5

>>> _

Avoiding Index Errors when working with lists

To avoid index errors when working with lists, you must remember these:

1. The total count of items in the list. You can always remind yourself and your program about the total count by using len().

2. Lists are zero based. The index always starts with 0.

3. Removing and adding an item on the list always change the total count. Changing the data of an item does not.

Working with Lists

Lists have multiple purposes in programming. For one, lists are an excellent way to reduce the amount of variables you need to create. For example:

>>> x = 135

>>> y = 247

>>> z = 359

>>> total1 = x + y + z

>>> total1

741

>>> a = [135, 247, 359]

>>> total2 = sum(a)

>>> total2

741

>>> _

The example only deals with three values and shows you two different ways you can process them. As you can see, assigning them in a list instead of assigning them to separate variables is a much easier and faster way to process those values.

The example might only show little advantage, but think about a scenario wherein you need to deal with 20 or more pieces of data.

On the other hand, lists are useful when receiving an inconsistent amount of data during runtime. Instead of preparing a set amount of variables ready to receive those data, you can just use a list since lists can hold unspecified number of values.

Looping through an entire list

Another advantage of lists against other regular data types and variables is that you can loop through them with ease. Here is the previous example with the addition of a loop method to work with a list:

>>> x = 135

>>> y = 247

>>> z = 359

>>> total1 = x + y + z

>>> total1

741

>>> a = [135, 247, 359]

>>> total2 = a[0] + a [1] + a[2]

>>> total2

741

>>> total3 = 0

>>> for i in range(len(a)):

...     total3 += a[i]

...

>>> total3

741

>>> _

There are two common ways to loop through a list. The first method is using the “for” loop together with the range() and len() functions. The second method is to use while loop and the len() function.

>>> a = [135, 247, 359]

>>> total1 = 0

>>> for i in range(len(a)):

...     total1 += a[i]

...

>>> total1

741

>>> total2 = 0

>>> while (i < len(a)):

...     total2 += a[i]

...     i += 1

...

>>> _

Since list indices are incremental in nature, you can use loop counters, which also increments per loop, as list indices to scan through a list.

Currently, the simplest and popular method is to use for and in combination without using range() and len(). For example:

>>> a = [135, 247, 359]

>>> total1 = 0

>>> for item in a:

...     total1 += item

...

>>> total1

741

However, this method does not give you easier control with regards to picking the items you only need. For example, if you only want to use the value of the a[0] and a[1], you cannot do that without using a loop counter or index.

For example:

>>> a = [135, 247, 359]

>>> total1 = 0

>>> for i in range(len(a)):

...     if (i == 1):

...         continue

...     total1 += a[i]

...

>>> total1

494

Another method to loop through a list is to use list iteration object. The iteration object allows you to navigate through your list item by item using the built-in function next(). For example:

>>> a = [135, 247, 359]

>>> b = iter(a)

>>> next(b)

135

>>> next(b)

247

>>> next(b)

359

>>> c = iter(a)

>>> for i in range(len(a)):

...     print(next(c))

...

135

247

359

>>> _

Loops will be discussed in-depth in the next chapter.

Avoiding indentation errors

For convenience, Python allows developers to assign items to a list in multiple lines. For example:

>>> sampleList = [

1,

2,

3,

4

]

>>> sampleList

[1, 2, 3, 4]

>>> _

You can even do this:

>>> sampleList = [

1

,2,

3

,4]

>>> sampleList

[1, 2, 3, 4]

>>> _

This can also be done within a code block and it disregards the indentation level:

>>> def randomFunction():

>>>     sampleList = [

1

,2,

3

,4]

print(sampleList)

>>> randomFunction()

[1, 2, 3, 4]

>>> _

However, even if you can do this, do not. You can encounter indentation errors doing things this way. Nonetheless, it does not mean that this “feature” is useless. You can use this technique if the individual items within the list use a lot of horizontal space.

For example:

>>> sampleList = [

"However, even if you can do this, do not.",

"You can encounter indentation errors doing things this way.",

"Nonetheless, it does not mean that this "\feature\" is useless.",

"Do this if the items take a lot of horizontal space."

]

>>> _

Displaying enumerated lists

If you want to display an enumerated list, you can use the enumerate() function. The function allows you to parse through the list, get both index and value, and assign them to variables in the loop statement. For example:

>>> a = [135, 247, 359]

>>> for i, item in enumerate(a):

print(str(i) + ". " + str(item))

0. 135

1. 247

2. 359

>>> _

Since the example is using the concatenation operator, it is important that you convert all the numbers into string to make sure you will not receive a TypeError exception.

Tuple

Tuples are sequences, just like lists. You can assign multiple items or values in it. And you can access its items using indices enclosed in square brackets.

However, the main difference between a tuple and a list is that tuples are immutable. This means that you cannot change the number of items it contains or alter their values.

Also, instead of using square brackets to contain items, it uses parentheses. For example:

>>> sampleList = [1, 2, 3, 4]

>>> sampleList

[1, 2, 3, 4]

>>> sampleTuple = (1, 2, 3, 4)

>>> sampleTuple

(1, 2, 3, 4)

>>> sampleTuple[0]

1

>>> sampleTuple[1]

2

>>> sampleTuple[2]

3

>>> sampleTuple[3]

4

>>> sampleTuple[0] = 10

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: 'tuple' object does not support item assignment

>>> i = iter(sampleTuple)

>>> next(i)

1

>>> next(i)

2

>>> next(i)

3

>>> next(i)

4

>>> _

Another difference between a tuple and a list is that assigning a single item in a tuple requires a comma. For example:

>>> sampleTuple = (1,)

>>> sampleTuple

(1,)

>>> _

The reason for this is the inclusion of parentheses. If you remove the comma, the value will be considered a value inside parentheses as if you are writing an expression.

>>> sampleTuple = (1)

>>> sampleTuple == 1

True

>>> type(sampleTuple)

(class 'int')

>>> sampleTuple[0]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: 'int' object is not subscriptable

>>> sampleTuple = (1,)

>>> sampleTuple == 1

False

>>> type(sampleTuple)

(class 'tuple')

>>> sampleTuple[0]

1

>>> sampleTuple = ("text")

>>> sampleTuple == "text"

True

>>> type(sampleTuple)

(class 'str')

>>> _

Looping through all values in a tuple

Looping through the values in a tuple is similar to looping through a list.

>>> a = (10, 20, 30)

>>> total1 = 0

>>> for i in range(len(a)):

total1 += a[i]

>>> total1

60

>>> total2 = 0

>>> while (i < len(a)):

total2 += a[i]

i += 1

>>> total2

30

>>> total3 = 0

>>> for item in a:

total3 += item

>>> total3

60

>>> for i in range(len(a)):

if (i == 1):

continue

print(a[i])

10

30

>>> b = iter(a)

>>> for i in range(len(a)):

print(next(b))

10

20

30

>>> _

Writing over a tuple

Writing over a tuple is tricky since it is not built to be overwritten. The prime advantage of tuples is that you can be assured that the values in it will be immutable.

Also, since the elements in the tuple, including the tuple object itself cannot be changed and these elements are all objects, they will contain less methods and attributes. Because of its simplistic and static nature and build, they are faster to process and loop into compared to the dynamic list.

And due to those reasons, tuples are often used to store large amounts of data with different types.

Generally, it is not recommended to create code to change tuples. You should have used lists instead if you are going to change its value and contents anyway.

Nonetheless, such situations arise like when the disadvantages of using lists outweighs the disadvantage of creating code to change the value and contents of a tuple.

Python does not allow changing a tuple’s content. However, there are workarounds. One of them is to create a temporary list for your tuple’s content.

You need to convert the tuple to a list using the list() function. Change the values you want in the list. And then assign the list as a tuple using the tuple() function. For example:

>>> sampleTuple = (1, 2, 3, 4, 5)

>>> sampleTuple

(1, 2, 3, 4, 5)

>>> temporaryList = list(sampleTuple)

>>> temporaryList

[1, 2, 3, 4, 5]

>>> temporaryList[0] = 999

>>> temporaryList

[999, 2, 3, 4, 5]

>>> sampleTuple = tuple(temporaryList)

>>> sampleTuple

(999, 2, 3, 4, 5)

>>> _

Dictionary

Dictionary is similar to lists, but instead of numerical indexes, it uses keys. Also, it uses curled brackets ({}) to enclose its items.

Keys are strings that are paired to values. You can access a value inside a dictionary by using its paired key. When assigning an item in a dictionary, you must input both key and value paired with a colon (:) in between them. E.g.

>>> sampleDictionary = {"name" : "admin", "password" : "pas123"}

>>> sampleDictionary["name"]

'admin'

>>> sampleDictionary["password"]

'pas123'

>>> sampleDictionary

{'name': 'admin', 'password': 'pas123'}

>>> _

Working with dictionaries

A dictionary is handy when you have data that have contextual values. It is also a nice alternative to using variables. You can just treat keys as variable names and values as the values of variables. For example:

>>> x = 1

>>> y = 2

>>> z = 3

>>> sampleDictionary = {"x": 1, "y": 2, "z": 3}

>>> _

Accessing values in a dictionary

As mentioned before, you can access a value in a dictionary by using the key of the value you want to access. Having a string key instead of a numerical index is a powerful advantage against list. Since you use a string, you can pair a key to a value with context.

Aside from that, you can still use numerical indices in dictionary. However, note that the dictionary will not automatically increment numerical keys or indices. Also, you are not restricted to start with 0. For example:

>>> sampleDictionary = {999: "sampleValue", "r": "randomValue", 0: "meh"}

>>> print(sampleDictionary[“r”])

'randomValue'

>>> sampleDictionary[999]

'sampleValue'

>>> sampleDictionary[0]

'meh'

>>> _

Adding new Key-Value pairs

Unlike lists, you do not need to remember the current number of items that a dictionary holds to assign new items. You just need to make sure that the name of the key is unique compared to the ones already stored inside the dictionary.

For example:

>>> sampleDictionary["age"] = 9

>>> sampleDictionary["birthday"] = "January 1, 1980"

>>> sampleDictionary

{"age": 9, "birthday": "January 1, 1980"}

>>> _

Starting with an empty dictionary

You can start an empty dictionary by assigning a pair of curly brackets. For example:

>>> sampleDictionary = {}

>>> sampleDictionary

{}

>>> type(sampleDictionary)

<class 'dict'>

>>> _

Modifying values in a dictionary

Modifying values in a dictionary is as simple as assigning a new value to a key. For example:

>>> sampleDictionary["age"] = 9

>>> sampleDictionary["age"]

9

>>> sampleDictionary["age"] = 8

>>> sampleDictionary["age"]

8

>>> _

Removing key-Value pairs

You can remove a key and value pair by using the del function.

>>> sampleDictionary["key1"] = 135

>>> sampleDictionary["key2"] = 247

>>> sampleDictionary["key3"] = 358

>>> sampleDictionary

{'key1': 135, 'key2': 247, 'key3': 358}

>>> del sampleDictionary["key2"]

>>> sampleDictionary

{'key1': 135, 'key3': 358}

>>> _

Looping through a dictionary

You can loop a dictionary like a list, but it is a bit tricky because you need to get both keys and values. To pull this off, you need to use the “for” loop and the items() method of the dict class.

The items() method returns a dictionary’s key and value pairs in the form of a tuple. Since it returns a tuple, the “for” loop statement can iterate on it and start a loop.

For example:

>>> sampleDictionary = {"a": 1, "b": 2, "c": 3}

>>> for key, value in sampleDictionary.items():

print(key + " : " + str(value))

'a': 1

'b': 2

'c': 3

>>> _

Key and value are just variables. You can use any identifier or variables you want to receive data from the items() method. However, it is recommended that you use key and value for readability because both are conventionally used for this purpose.

Nesting

Aside from the usual strings and numbers, you can actually assign lists, tuples, and even dictionaries inside dictionaries, lists, and tuples.

For example:

>>> sampleList1 = [1, 2, 3, 4]

>>> sampleList2 = [5, 6, 7, sampleList1]

>>> sampleList2

[5, 6, 7, [1, 2, 3, 4]]

>>> sampleList2[0]

5

>>> sampleList2 [1]

6

>>> sampleList2 [2]

7

>>> sampleList2 [3]

[1, 2, 3, 4]

>>> sampleList2 [3][0]

1

>>> sampleList2 [3][1]

2

>>> sampleList2 [3][2]

3

>>> sampleList2 [3][3]

4

>>> sampleDictionary = {"a": 10, "b": 20, "ListItem": sampleList2}

>>> sampleDictionary

{'a': 10, 'b': 20, 'ListItem": [5, 6, 7, [1, 2, 3, 4]]}

>>> sampleDictionary["ListItem"]

[5, 6, 7, [1, 2, 3, 4]]

>>> sampleDictionary["ListItem"][3]

[1, 2, 3, 4]

>>> sampleDictionary["ListItem"][3][0]

1

>>> _

To access the values inside nested lists, tuples, and dictionaries, you just need to provide the keys and indices in proper succession. Here is an easier to read example using dictionaries:

>>> name = {"first": "John", "last": "Doe"}

>>> account = {"name": name}

>>> account

{'name': {'first': 'John', 'last': 'Doe'}}

>>> account["name"]["first"]

'John'

>>> account["name"]["last"]

'Doe'

>>> print(account["name"]["first"] + " " + account["name"]["last"])

John Doe

>>> _

Styling your code

Python has its own style guide under its Python Enhancement Proposals. It is written under PEP 008, and it was written by Guido van Rossum, Barry Warsaw, and Nick Coghlan. This section will summarize that document for easier reading.

Some of the styling proposals have been already mentioned in the early parts of this book. However, some of them will be mentioned again in the later parts of this book as reminders.

General Style Guide

- Do not update the style of already written code if it was already readable.

- Make sure that your code styling is consistent throughout a project.

- You can deviate from this styling guide if the recommendations will make your code unreadable.

- Imports should be done in separate statements. Importing will be discussed later in this book.

- Avoid placing unnecessary spaces before and after grouping symbols or delimiters.

- Avoid placing trailing whitespaces.

- Avoid the use of capital I, lowercase L, and capital O as single letter variables. They can easily confuse readers.

Indentation

- Use four spaces for each indentation level.

- If you are going to take advantage of Python’s implicit line joining when using parentheses, use hanging indents.

- Align the indent with the opening delimiter (e.g., "(", "[", "{"). Or align the indent four spaces more than the first character of the parent line’s position.

- Align the closing delimiter with first character of the parent line’s position. Or you can align the closing delimiter with the opening delimiter.

>>> def sampleFunction():

sampleList = [

1, 2, 3, 4,

]

>>> _

Line length

- Limit the length for each line in Python by 79 characters.

- For flowing text or strings, limit the line by 72 characters.

- To improve readability, make the line joining explicit by adding a backslash character at the end of the line.

>>> sampleList = [

"However, even if you can do this, do not.", \

"You can encounter indentation errors doing things this way.", \

"It does not mean that this "\feature\" is useless.", \

"Do this if the items take a lot of horizontal space." \

]

>>> _

Blank lines

- Surround class definitions and top-level functions with two blank lines while methods should be surrounded by one blank line. More about classes, methods, and functions later.

- You can separate statements from unrelated statements with a blank line. Remove all blank lines separating related statements.

Practice Exercise

1. Convert this table to a nested dictionary.

First Name

Last Name

Gender

Age

Position

Location

Employee1

Johnny

Masaki

Male

25

Security

Cleveland Ohio

Employee2

George

Laurie

Male

25

Messenger

San Francisco, California

Employee3

Rowan

Bean

Female

67

Receptionist

London, UK

Employee4

Ford

Harrison

Male

53

Manager

New York, New York

Employee5

Roberta

Meyers

Female

36

Chief Financial Officer

Princeton, New Jersey

2. Display the contents of the above table by using a loop and the print() function.

Chapter Summary

Congratulations on your progress so far. Now, you already know the different types of data that you can use and process in Python. If you were able to perform the above practice exercises, then you have demonstrated a good understanding of the topic discussed. Therefore, you are now ready to proceed to the next chapter.

If you find yourself struggling to complete the practice exercise, don’t worry. Just go through the topic again and have another go at the exercise. You’ll get it.

The next chapter will prepare you to create complex and intelligent programs. In those lessons, you will be able to enhance the way you process the variables and literals you have into something more meaningful.

As long as you remember all the simple rules in using the variables and data types mentioned in this chapter, you can be confident that you can easily whip out a nice program.

Chapter 3: Solution

firstName = [

"Johnny", "George", "Rowan", "Ford", "Roberta"]

lastName = [

"Masaki", "Laurie", "Bean", "Harrison", "Meyers"]

age = [

25, 25, 67, 53, 36]

gender = [

"Male", "Male", "Female", "Male", "Female"]

position = [

"Security", "Messenger", "Receptionist", "Manager", "Chief Financial Officer"]

location = [

"Cleveland, Ohio", "San Francisco, California", "London, UK", "New York, New York", "Princeton, New Jersey"]

employees = {}

for i in range(1, 6):

employees["employee" + str(i)] = {

"firstName": firstName[i - 1],

"lastName": lastName[i - 1],

"age": age[i - 1],

"gender": gender[i - 1],

"position": position[i - 1],

"location": location[i - 1]

}

for i in range(1, 6):

x = "employee" + str(i)

print(

x + " : " +

employees[x]["firstName"] + ", " +

employees[x]["lastName"] + ", " +

str(employees[x]["age"]) + ", " +

employees[x]["gender"] + ", " +

employees[x]["position"] + ", " +

employees[x]["location"]

)

The End

I hope you have gained enough knowledge from this free book to get a feel for Python Programming and our teaching style. If you feel it’s a good match for you and you want to take your knowledge a step further, we invite you to download the advanced version of this book.

In the advanced version, you’ll learn about:

- Conditions and Loops

- Functions and Modules

- Object Oriented Programming

- How to work with files

- How to handle errors and exceptions

- How to test your code

And much, much more!

BONUS – I have enrolled the ebook in the Amazon Kindle Matchbook program. This means that the ebook version will be available to you for FREE when you purchase the paperback version from Amazon.com (the USA store)!

Click Here To Download

Table of Contents

Who Is This Book For?

What Is Python?

Interpreted Not Compiled

Advantages of Python as an Interpreted Language

Scripts

Python as a General Purpose Programming Language

Community Frameworks, Toolkits, Libraries, and Modules

Programming Paradigms and Object Oriented Programming

History, Background, and Evolution

Core Philosophy and Uniqueness

Summary

Chapter 1

Getting Started With Python

Python 2.x vs. Python 3.x

Installing the Interpreter

Using Python Shell and IDLE

Writing Your First Program

Shell, IDLE, and Scripts Syntax

Prompt

Indentation

Indentation Prompt

Python Shell Navigation

IDLE Navigation

Troubleshooting Installation Issues

Practice Exercise

Chapter Summary

Chapter 2

Variables and Operators

Computer Basics

Computer Program

What Are Variables?

Naming Variables

Using Variables

Naming Conventions

Naming by Description

Introduction to Expressions and Python Operators

Expressions

Operators

Arithmetic Operators

Relational Operators

Assignment Operator

Logical Operators

Truth Table

Membership Operators

Identity Operators

Bitwise Operators

Practice Exercise

Chapter Summary

Chapter 3

Simple Data Types

Numbers

String

Combining/Concatenating strings

Avoiding Type Errors with Conversion Functions

Avoiding, Replacing, and Stripping Whitespace

Avoiding syntax errors with strings

Collections/Sequences

Tuple

Dictionary

Styling your code

General Style Guide

Indentation

Line length

Blank lines

Practice Exercise

Chapter Summary

What Comes after This?