Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (8 votes)
2K views

Python

Python

Uploaded by

Neekesh Pandey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (8 votes)
2K views

Python

Python

Uploaded by

Neekesh Pandey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Python

Learn Python with Ultimate Zero to Hero


Programming Crash Course for Beginners

Paul Madoff
Zero to Hero

Introduction
I want to thank you and congratulate you for downloading the book, Python: Learn
Python with Ultimate Zero to Hero Programming Crash Course for Beginners.
This book contains proven steps and strategies on how to code with Python.
In the first part of the book, you will be taught of computer programming fundamentals.
It will be assumed that you are a complete noob or beginner when it comes to this
craft. The fundamentals will give you a concrete idea about Python and the things you
will do with it.
Be reminded that you must at least become familiar with the basics of computer
programming even before you learn a programing language. Do not worry; the book
will not revolve around this topic only. Also, it will not certainly revolve around
histories, people, and other things that might seem unnecessarily boring for you to
learn Python.
After that, you will be familiarized with Python as a computer programming language.
The lessons will contain simple and easy to understand explanations. With the
knowledge you will gain from this book, you will be able to create simple programs
and become prepared in learning advanced lessons and techniques.
The book will touch on topics that you can use and test immediately on your computer.
The examples in this book are tested working and correct. In case some of the
examples did not work, please check if you copied the example correctly and if you
installed the same version of Python that was used in this book.
Thanks again for downloading this book. I hope you enjoy it!

Table of Contents
Introduction
Chapter 1: Learning Computer Programming and Python
Chapter 2: Getting Ready With Python
Chapter 3: Statements and Logical and Physical Lines
Chapter 4: Internal Composites of Statements
Chapter 5: Simple Input and Output Options
Chapter 6: Pythons Syntax and Style Tips
Chapter 7: Flow Control, Decision Making and Program Conditions
ZERO TO HERO: Other Books
*Bonus: Free Python Course

Chapter 1: Learning Computer Programming and


Python
Greetings! So, you got this book to learn about using Python, a popular programming
language. It sounds like a nice idea it really is. However, before you go ahead and
learn the intricacies of Python, you should take a few steps back, gather your thoughts,
and ask yourself this question, What is computer programming, and how can I make
programs?
Kudos to you if you answered that question easily. You will have an easy time reading
this book if that is the case. It is possible that you have already learned other
programming languages, too, which will make learning Python easier and more fun.
However, as a reminder, this book is geared toward newbies people who are
beginners when it comes to Python and computer programming. Nevertheless, even if
you are already familiar with computer programming, getting this book will still be
worth it if you have not mastered nor have no idea about Python yet.
Anyway, for the beginners, it is necessary that you are at least familiar with computers
and programs. It is crucial that you are acquainted with computer software and
hardware. In addition, it is important that you know the difference between the two.
On the other hand, it is essential that you are determined in learning computer
programming and Python. Learning computer programing halfheartedly will be a waste
of time. Treat this part of the book as a warning. Put in mind that absorbing everything
in this book would not be easy.
Patience is key in programming. Even if you are not a math genius or a logic whiz, you
can create programs and use Python with the help of this book. Computer programming
is not a skill you can learn overnight. And definitely, learning a new language or a
computer language is not something you can just finish in a week or so. It might take a
while, but the time that you will spend learning and applying the things here will be
worth it.
Of course, this part is not meant to scare you away. The point here is that if you want
to learn programming and Python, you must set aside some time for this. Also, be
prepared to be frustrated. If you think that you are ready, proceed to the next section
and good luck.

What Should You Expect in Learning Programming and Python


What will you get once you learn Python? First, computer programming is a good
hobby to have in your life. Think of programming as a sandbox for big boys like you.
Instead of sand, you will be using variables, functions, keywords, operators, and
literals to build your castle, err, your program. And expect that it will be fun and a
bit frustrating during bad days.

Programming Fundamentals
The main goal in computer programming is to create programs or software. Program
or software is any digital file or group of files that contain instructions or commands,
which tell computers what to do. They are compiled together in a program to achieve
a single or multiple goals.
On the other hand, a computer or its hardware is the one that performs those
instructions. The hardware relies on the instructions of the software in order to be
more usable and functional.
For example, a computers operating system is one large piece of software. Microsoft
Windows is an operating system. Without an operating system, a device or hardware
will have limited function.
However, it does not mean that hardware alone cannot do anything on its own.
Hardware devices also have some instructions in them to function. But in contrast to
the instructions embedded in software, instructions on hardware are very limited and
simple. Instructions on hardware can only do so little. Without programs or apps,
hardware such as smartphones, computers, and even a game console, will become too
simplistic and will be incapable of maximizing their potentials.
That is why you are here to learn computer programming and Python. You are here to
know how to make those programs that will run on those pieces of hardware. With
computer programming, you can create software for computers, smartphones, gaming
console, and even your car.

How to Create Software


So, how can you put all those instructions in a file? How will you be able to create
software? Will you need some powerful computers and high-tech gizmos to create
one? It might sound anticlimactic, but all you need is any functioning computer and a
decent keyboard that can withstand long hours of typing.
You might have already guessed it, but to create a program, you will need to write (or
type if you are pedantic when it comes to terminologies). Anyway, what will you
write and where? You will write the instructions that your hardware needs in order to
perform that tasks you want it to do and you can write that in any text editor of your
choice.
On the other hand, writing code is not the only way to create programs. Some other
programs can minimize the time you need to spend writing or eliminate that task
completely. Those programs will allow you to make software by just dragging and
dropping elements.
However, Python itself is not one of them. Nevertheless, Python has a lot of GUI
(Graphical User Interface) frameworks that can allow you to program without writing
too much. However, take note that even though you can just rely on the GUI to
program, using them still requires you to know how to write and understand Python.

Program Instructions
What are program instructions? Program instructions are commands that tell a
computers processor or the whole computer the things it needs to do. For you to get
an idea on how those program instructions work or how they look like, examine how
your computers music player works. If in case you will create a program like that,
you will need to write instructions like this:

Create a window for the music player

Wait for the user to open a music file

Check the file type of the music file

Prepare the codec for that music file in order for the program to play it

Buffer the music file to the computers memory for faster access

Play the music file

Apply the necessary filters and effects such as reverb and equalizer

Wait for the user to perform any other actions

At first glance, the set of instructions seems easy to do. Well, that example is just
simplified and computer instructions are nowhere simple as that. Despite a music
player being a staple and common program in computers, creating one requires a lot of
hard work, especially if you are going to create one from scratch.
Going back to the example, you cannot just tell the computer that it needs to check the
file type of the music file in one line when writing programs. For example, to achieve
a simple thing like playing a sound on your computer speakers, you will need to write
one, two, or more pages of computer instructions.

Source Code
It has been said that computer programs are files with written computer instructions in
them. However, do take note that before any file with computer instructions becomes a
program, it will be in source code form first.
A source code is a set of computer instructions that is not a program yet. In computer
programming, even before you create a functioning program, you will need to write
and complete your source code first. Once you finish your source code, you will need
to compile it and create a program out of it.
Of course, in some cases, it is possible that a programs source code can run without
the compiling process. In Pythons case, it is possible. After all, Python is an
interpreted language.

Interpreter and Compiler


Source codes are executed in two ways. The first way is to make the source code an
executable program. For a source code to become a program, a compiler must process
it. A compiler is a program that translates the code to a more understandable language
that a computer or device can follow and save it as an executable file.
The second way is to execute the source code using an interpreter. An interpreter is a
small program that reads source code line by line, statement by statement, or computer
instruction by computer instruction.
Instead of translating the source code completely, it will translate a line first, execute
it second, and proceed to the next line to repeat the process until the source code ends.
Python source codes are usually executed using this method. The interpreter possesses
some advantages over compilers. However, at your early days of programming, you
do not need to worry about those yet.
Just put into mind that Python rely mostly on its interpreter. But despite that, it is still
possible for source code written in Python to take advantage of compilers.

Programming Language
For the past few sections, you have been reading a lot about writing computer
instructions. But how exactly do you that? Will you just write sentences on a source
code editor and let the computer run it? Unfortunately, it is not that easy.
For starters, computers cannot understand human language such as English. The
computer hardware is not that smart to begin with. And with all due honesty, a
computers processor can only understand or identify two characters: 0 and 1. It is the
job of compilers and interpreters to convert your source code lines into that kind of
language.
However, even though compilers and interpreters are there to translate your source
code, it cannot still understand plain English. Due to that, you need to compromise
with the computer and need to learn a language that can be translated to its native
language easily and that is programming language.
For years, many programmers have developed their own programming languages to
suit their programming style. They have done that to make it easier for them and other
people to understand computer programming and programming languages. One of
those languages that they were able to develop was Python.
On the other hand, you should know that interpreters and compilers cannot understand
all the programming languages in the world. This is why programming languages
usually come with their own compilers and interpreters.
To make programming languages easier to learn, most of programming languages
based most of the keywords and functions from the English language. Also,
programming language has rules or syntax that you must follow in order for you, the
interpreter, and the compiler to understand the source code that you will write.

Programming in a Nutshell
A program is a set of computer instructions that were written to achieve one or
multiple goals. To create a program, you must write its source code first using a
programming language.
Despite writing your computer instructions using a programming language, the
computer cannot understand it since it can only understand computer language, which
is why it needs help of translators.
There are two types of translators. The first one is the compiler. The second one is the
interpreter. The compiler translate your source code in one go and create a new file
where the translated source code will be saved. That file is an executable program
that your computer can read and follow without any further help.
The second translator is the interpreter. Unlike compilers, it only translates on
demand. It will not read all the contents of your source code and create an executable
file immediately. Instead, it will translate the computer instruction one by one when
they are needed.
Python is an interpretative language. That means that most source code written in
Python will rely on Pythons interpreter in order to run. Source code or programs that
rely on interpreters are usually called scripts. Due to that, Python is also considered a
scripting language.
If you will try to visualize the processes involved in programming language, this is
how it will appear:

Write computer instructions and complete your source code

Compile it and convert it to a standalone program or run an interpreter and let


it run your source code as a script

Computer runs the instructions and provide you results

Chapter 2: Getting Ready with Python


You have now an idea on how computer programming works. Then it is time to
prepare yourself in learning Python. To start, you need some tools and get your
computer ready for writing source code.

Internet Connection
You need an internet connection. Internet connection is vital to your progress in
program development. You can get Python from the net, read some decent tutorials
from websites that focus on Python programming, and retrieve some cool examples
that you can study.

Getting Python
Next, you must acquire Python. You can get the most recent version of Python from
https://www.python.org/. Go to the download page and download the newest stable
version of this programming language. As of this writing, the most recent stable
version is Python 3.4.3.

Stable Release and Python version 2.x.x


You might notice that the site is also offering Python 2.7.9. This version is another
stable release for those who are used to programming Python in version 2.x.x (any
version of Python that falls under Python 2).
That stable release is provided since there are major changes that happened in Python
version 3.x.x. The source code created using Python 2.x.x are mostly incompatible
with version 3.x.x. Unfortunately, most Python programmers are accustomed to version
2.x.x and most of their programs are based on it.
However, for a beginner, it is essential that you must start learning Python using
version 3.x.x for you to be accustomed with the future versions of Python. On the other
hand, once you become efficient in programming in version 3.x.x, it is advisable that
you check out version 2.x.x.
Knowledge on version 2.x.x will allow you to understand code examples or programs
created under that version. Do not worry. It will not be that hard to study it even the
differences between them are major since both are still Python.
Anyway, Python are runnable on computers running on Microsoft Windows or Mac
OSX. You can just download the latest version and install it to your computer.
However, if your computers operating system is neither of the two, you can look for a
Python build that is for your computers operating system in
https://www.python.org/download/other/.
The package installer of Python version3.4.3 is around 24MB, so with a decent
internet connection, you can get it after one or two minutes. Once downloaded, just
open the installer and follow the instructions. Usually, it will take a minute or two for
it to finish the installation.

The Python Interpreter


One of the core files that the installation placed in your computer is the Python
interpreter. Unlike older programming languages, you can directly interact with
Pythons interpreter. To do so, you can just open Python.exe (if your computer is
running on Microsoft Windows). You can go to the location where you installed
Python (usually it is installed in C:\Python34) to access Python.exe. Or you can just
check your program menu that contains the shortcut to the Python interpreter.
Once you open the Python interpreter, a console like window will appear and you will
be welcomed by this message:
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
The welcome message will provide you with the version number, current date and
time, and some information about your operating system. After that, some helpful
commands are listed that you can input to know more about the Python installation in
your computer and get some help.
Unfortunately, the help command is not that helpful yet at this point. And using it may
only confuse you.
Anyway, in the interpreter, you will see that there are three greater than signs
(chevrons) and after that, you will see a blinking cursor. You will input your line of
code after that cursor. And once you press enter on the console, that line of code will
be processed by the interpreter.
The interpreter will translate it to machine code, let the computer process the code,
and then once the computer finishes, the interpreter will provide you with the result of
the code. After that, the three greater signs prompt will be back and you can type
another line of code.

What to Do with the Interactive Python Interpreter


During your early days in learning and coding using Python, you will be using Pythons
interactive interpreter. In this program, you will write snippets of code and learn
what they do and how they can be used. The book will instruct you to place most of the
examples in the Python interpreter for you to understand quickly their functions and
effects.
Traditionally, computer programming mostly rely on compilers. Before you can see
the effects of the computer instructions that you will write, you will need to finish your
source code (or write a functioning code block), compile it, and then execute it. Due to
that, this method becomes time consuming.
Thankfully, you do not need to undergo that in order to learn how to program in
Python. Interpreters usually do not work this way. On other interpretative language, the
interpreter will only run if the source code is executed.
With Python, you can use an interactive interpreter. With it, you can try out anything
that you learn immediately without thinking too much about you completing your
program.
For you to have a concrete idea about that, try typing this into the interpreter:
>>> print ("This is a line of text that will be displayed")
This is a line of text that will be displayed
>>> _
Note: You do not need to place the three greater than signs on the interpreter. The
underscore represents the blinking cursor.
In the first line of the example, a line of code is sent, instructing the computer to
display text on the interpreters console window. The line used the print function of
Python. To let the interpreter know the text to print, the example enclosed the text
inside parentheses and double quotes. Those parentheses and double quotes are
essential and more information about them will be provided later.
The second line in the example shows the computer and the interpreters response to
the first code. As soon as the example pressed enter, the computer and interpreter
provided the result of the line of code.

Since the line of code was completely processed by the computer and the interpreter,
the interpreter provided the command prompt again to let you know that it is ready to
take another line of code from you.
That is how Pythons interactive interpreter works. Take full advantage of it. Even if
you advanced further in learning Python, you will still need to use it.

Programming Mode or Scripting in Python


When you start writing multiple lines of code in Python, the interactive interpreter
becomes a nuisance. After all, you do not need the immediate feedback anymore since
you already know what will happen if you input a certain line of code. Due to that, you
would want to focus of creating a program without the feedback and the interactive
console.
In that event, you would want to immerse yourself on Pythons programming mode.
This is not really an actual mode in Python. It is just a method of programming using
Python. And if you are going to create a small program, it is more appropriate that you
call this method scripting.

Source Code Editors


When scripting, instead of typing on the interpreter, you will need a source code
editor. Actually, you can use a regular text-editing program such as Notepad in
Microsoft Windows. However, it is much more advisable that you use a decent source
code editor because it has features that are geared towards programming.
One of the decent source code editors that you can get easily is Notepad++ for
Windows, Eclipes or Editra for Mac, and Emacs or gedit for Linux distros. Of course,
you are not limited to those since those are just suggestions of the author. However,
when choosing a source code editor, be sure that it has the following features:

Syntax Highlighting: This feature provides different font color and styling for
different elements in your source code. For example, comments in your source
code will be highlighted with green and keywords will be highlighted with
blue.

print ("This is a line of text that will be displayed")


#This is a comment line.

Syntax Folding: When your source code becomes too huge (contains too many
lines of codes), maintaining it or just looking for a line in it becomes difficult.
With syntax folding, your blocks of code can be folded or minimize to make
your source code appear less cluttered.

Customizable Syntax Highlighting and Folding: This is not necessary, but it


gives you control of the styling and behavior of syntax highlighting and syntax
folding.

Auto-Completion: This feature might not be up to your preferences or not.


Autocomplete can make you code faster by providing suggestions before you
can finish typing your code.

Python Support: Of course, the source code editor that you must choose should
have Python support. Without it, those previous features will not work.
Although, most popular source code editors nowadays can support multiple
programming languages, so it will not be difficult to find a source code editor
that you will like to use.

Alternatively, if you are on the go or you need to use a different computer or device

that does not have the source code editor of your choice, you can use web based
source code editors. Aside from having the features mentioned previously, they can
also run your source code on the web.

Chapter 3: Statements and Logical and Physical Lines


Now, thanks to the previous chapter, you are ready to learn Python. As you read, make
sure that you keep your computer and Python interpreter handy. But before that, you
should know the basic structure and syntax of Python.

Statements
A program is a compilation of computer commands and instructions. Each line or lines
of code you write in Python are called a statement. A statement is the smallest element
in a program or source code. It contains other basic elements in a programming
language such as variables, operators, and expressions. And usually, one statement
equates to one command, instruction, or specified action.
A statement is like a regular imperative (commanding) statement or sentence in the
English language. Just like a sentence in the English language, statements also follow
grammar rules, which are called syntax rules in computer programming.
For example, to complete a sentence, you must end the sentence with a period. In most
programming languages, to complete a statement, you must end the statement with a
semicolon (;).
In Python, you can use a semicolon to end a statement. However, it is not necessary. A
carriage return and line break combination (it is produced by pressing the enter key),
which is usually referred to CRLF, is enough to let Python know that the statement that
you wrote is finished. In interactive mode, the enter key will also signal the interpreter
that the statement you wrote needs to be executed.
In some cases, using a semicolon to signify the end of a statement is useful. One of the
scenarios you might want to use it is when you want to enter two statements in one
line. For example:
>>> print ("This is a statement"); print ("This is another statement")
This is a statement
This is another statement
>>> _
However, do not try putting two statements in one line without separating them using
the semicolon. This is what will happen if you do that.
>>> print ("This is a statement") print ("This is another statement")
File "<stdin>", line 1
print ("This is a statement") print ("This is another statement")

^
SyntaxError: invalid syntax
>>> _

Physical Lines and Logical Lines


A physical line is a line of code. It does not necessarily mean that it is a statement. A
physical line is one line of text in your source code editor or one line of code that you
ended with a carriage return and line feed combination.
On the other hand, logical lines are statements. Statements do not equate to one
physical line most of the time. In some cases, a statement or logical line can span into
multiple physical lines. A physical line becomes a logical one when it is ended with a
semicolon or it is a complete and valid statement.

Explicit and Implicit Physical Joining


It is advisable that when coding, it is essential that you keep your statements in one
logical line. It means that you should not snip a statement into multiple physical lines
and you should not put multiple statements in one physical line. As of now, you only
know how to put multiple statements in one physical line with the use of a semicolon.
Now, check this example on how to create a statement in multiple physical lines.
>>> print \
... ("As you can see \
... when you pressed the enter key \
... after the backslash \
... the chevron prompt \
... changed into an ellipsis. \
... In interactive interpreter mode, \
... the ellipsis means that \
... you are writing a statement \
... with multiple physical lines. \
... The backslash character is there \
... to tell the interpreter that \
... you want to do join multiple \
... physical lines. \
... Despite being included in the \
... value that needs to be displayed by print \
... the backslash characters will not appear.")
As you can see when you pressed the enter key after the backslash the chevron prompt
changed into an ellipsis. In interactive interpreter mode, the ellipsis means that you are
writing a statement with multiple physical lines. The backslash character is there to
tell the interpreter that you want to do join multiple physical lines. Despite being
included in the value that needs to be displayed by print the backslash characters will
not appear.

>>> _
Despite appearing messy in the interactive mode, this is useful when you are writing in
a source code editor. Putting a long statement in one physical line can be distracting
and troublesome because source code editors are not set to word wrap by default.
Even if they do, the line counter will be messed up and might confuse you. Also, it
might force you to use the horizontal scroll bar, which is a pain for some people.
Using the backslash character to fuse multiple physical lines to become one statement
is called explicit joining. Another method that you can use to fuse multiple physical
lines into one statement is to use implicit joining.
Unlike explicit joining, you do not need to place any special character to do implicit
joining. If you know the rules behind implicit joining, Python will automatically do it
for you. Well, the rule is that you can do it with statements that use parentheses, curly
bracers, and square brackets. For example:
>>> print ("This is the first line"
... ". This is the second line."
... " The key in implicit joining "
... "is to let the Python interpreter think "
... "that you are not yet finished in your "
... "logical line. To do that, "
... "you must let parentheses, curly "
... "braces, and square brackets hanging. "
... "Do not put the closing bracket "
... "until you are finished with your statement. "
... "However, take note that you must make sure "
... "that you close the values within those brackets. "
... "For example, you must close the text in this "
... "statement in double quotes to make sure "
... "that you will not receive a syntax error. "
... "And to end this statement, just supply "

... "the closing bracket, which is a parenthesis.")


This is the first line. This is the second line. The key in implicit joining is to let the
Python interpreter think that you are not yet finished in your logical line. To do that,
you must let parentheses, curly braces, and square brackets hanging. Do not put the
closing bracket until you are finished with your statement. However, take note that you
must make sure that you close the values within those brackets. For example, you must
close the text in this statement in double quotes to make sure that you will not receive
a syntax error. And to end this statement, just supply the closing bracket, which is a
parenthesis.
>>> _

Chapter 4: Internal Components of Statements


To create a statement or instruction for the computer to follow, you will need to fill a
statement with some necessary components. The components needed to be added
depends on what type of action you want to happen.
Just like in a sentence, programming statements also have parts. In sentences, you need
noun, verb, adjectives, adverbs, and punctuation. In a statement, you need variables,
operators, expressions, literals, functions, and keywords.

Literals or Data
Programs need data in order to function or to have a purpose. Literals are fixed values
that you can manipulate in order to achieve a goal. For example, the numbers 1, 2, 3,
and so forth are literals.
Literals are not limited to numbers alone in Python. Text or strings are also literals.
There are multiple types of literals in Python. And two of the important literals that
you should learn are strings and numerical literals.
Numerical Literals
Any plain number in Python you can see is a numerical literal. Numerical literals can
be shown in Python in multiple forms. You can type them as integers, plain integers,
floating points, or imaginary numbers. On the other hand, you can show them in binary,
octal, decimal, and hexadecimal. Also, you can use scientific notation to present them.
By the way, you should never separate one number with commas. For example:
>>> 123,456,789
(123, 456, 789)
>>> 123456789
123456789
>>> _
Python will misinterpret it if you separate the place value of your numerical literals
with comma.
String Literals
String literals are text enclosed inside single or double quotes. Take note that you
should never forget enclosing your strings inside quotes since you will receive an
error or an undesirable result may happen if you do not. For example:
>>> "This is a string"
'This is a string'
>>> This is a string
File "<stdin>", line 1

This is a string
^
SyntaxError: invalid syntax
>>> _
In typing strings in Python, you might encounter some difficulties or errors when you
include certain or symbols. For example, if you use double quotes in your text:
>>> print ("And Rudolph said, "Why do I have a red nose?"")
File "<stdin>", line 1
print ("And Rudolph said, "Why do I have a red nose?"")
^
SyntaxError: invalid syntax
>>> _
Since the example included a double quote in the string, the interpreter thought that the
example has terminated the string on the second instance of double quote the double
quote after Rudolph said. Due to that, the interpreter was confused on the following
characters after that, thus it returned an invalid syntax error.
There are three ways in order to overcome that. First, you can use a different quote to
prevent string termination. In the examples case, you can use a single quote to contain
the string with the double quotes. For example:
>>> print ('And Rudolph said, "Why do I have a red nose?"')
And Rudolph said, "Why do I have a red nose?"
>>> _
Another method is to use triple quotes. This method can prevent you from having
errors with strings with single or double quotes in them. Triple quotes are just three
single quotes put together. For example:

>>> print ('''And Rudolph said, "Why do I have a red nose?"''')


And Rudolph said, "Why do I have a red nose?"
>>> _
And the last method is to use escape characters to insert the double quotes. To do that,
you need to use the backslash character. For example:
>>> print ("And Rudolph said, \"Why do I have a red nose?\"")
And Rudolph said, "Why do I have a red nose?"
>>> _
To prevent the interpreter to misinterpret the next double quote, the example used a
backslash character to escape the meticulous check that the parser is doing. Due to
that, the double quote was just treated as a string character instead of a string
terminator.

Escape Sequences
In Python, there are multiple escape sequences that can help you prevent having
problems with some signs and symbols. Some of those escape sequences are:
Sequence

Purpose

\\

Escape sequence for backslash

\'

Escape sequence for single quote

\"

Escape sequence for double quote

\n

Escape sequence for Linefeed (LF)

\r

Escape sequence for Carriage Return (CR)

\t

Escape sequence for horizontal tab

Note: To create a line break in your string, you can insert both \r and \n in the string.
For example:
>>> print ("This is the first line. \r\nThis is the next line.")
This is the first line.
This is the next line.
>>> _
Also, you do not need to place a space after the escape sequence. If you do put a space
after it, it will be included on the string. For example:
>>> print ("This is the first line. \r\n This is the next line.")
This is the first line.
This is the next line.
>>> _

Operators
You now know about data and literals, so what will you do with them? Manipulate
and evaluate. How? You need to use operators. In programming, multiple types of
operators exist for programmers to come up with useable results and data. As a
beginner, you will be learning the most basic ones today, which are arithmetic
operators.
By the way, operators are signs and symbols that are used in order to create an
expression that can be evaluated. Usually, operators are placed in the middle of
operands. Operands can be literals, variables, or functions that return a value. For
example:
>>> 1 + 2
3
>>> _
In the example, the arithmetic operator addition (+) was used. It was placed between
two operands, which are numerical literals. By the way, in the interpreter mode, you
can just perform expressions like that. However, if you do place a line of code like
that in programming or scripting mode, you will receive an error.
Also, operators in programming are similar with Mathematical operators. The only
difference is that programming operators are greater in number and functions. Anyway,
since it was entered on the interpreter, it immediately evaluated the expression. And
the result of 1 + 2 was 3.
Arithmetic Operators
In programming, a lot of Math will be involved. But do not fret; you do not need to
become a master of calculus to pull off a decent program. Truth be told, most common
programs only require basic Mathematical operations such as addition, multiplication,
division, and subtraction. Below are the arithmetic operators in Python you can use.

Operator

Operator Name/Description

Example

Addition: adds the value of the two 1 + 1 equates to 2

operands

Commutative, associative, and identity laws apply to addition


in Python.
1 + 2 is equal to 2 + 1
1 + (2 + 3) is equal to (1 + 2) + 3
1 + 0 is equals to 1 and 2 + 0 is equals to 2

Subtraction: subtracts the value of 5 2 equates to 3


the left operand to the left. Also, you It is the same as:
can treat it as an addition operation
with the right operand being negated. 5 + (-2) equates to 3
On the other hand, you can perform addition with the
subtraction operator, for example:
1 (-1) equates to 2
This is possible because Python allows and understands
double negation.

Multiplication:
operands

multiplies

both 2 * 3 equates to 6
Commutative, associative, distributive, and identity laws
apply to addition in Python.
3 * 6 is equal to 6 * 3
3 * (6 * 9) is equal to (3 * 6) * 9
3 * (6 + 9) is equal to (3 * 6) + (3 * 9)
5 * 1 is equals to 5 and 34 * 1 is equals to 34
Note: Always put the multiplication operator when
multiplying a value to an expression enclosed in parentheses.
If you try multiplying like this:
5(4 * 23)
You will get an error.

Division: divides the left operand 5 / 5 equates to 1


with the right operand
10 / 2 equates to 5
13 / 4 equates to 3.25
Note: You will get an error if you try to divide a number
with 0.

Modulus: divides the left operand 5 % 5 equates to 0


with the right operand, but instead of 10 % 3 equates to 1
providing the quotient, it will only
15 % 6 equates to 3
provide the remainder
Modulus can be achieved by using floor division and a bit
intricate expression. For example:
5 - ((5 // 5) * 5) equates to 0
10 ((10 // 3) * 3) equates to 1
Modulus also does not allow 0 on the right operand.

**

Exponent:
provides
exponential 5 ** 2 equates to 25
power to the left operand.
3 ** 3 equates to 9
15 ** 0 equates to 1

//

Floor division: divides the left 10 // 3 equates to 3 instead of 3.33


operand with the right operand, but 15 // 6 equates to 2 instead of 2.5
any fractional component in the
Floor division does not allow division by zero.
quotient will be removed.

Take note, just like normal Mathematical expression, you can group your operands
using the parentheses. Also, all the expressions within the deepest grouping of
parentheses are always evaluated first. Exponents are evaluated next before
multiplication and division. Addition and subtraction get processed last.

Variables
If your program needs a lot of literals and will involve a lot of evaluation of
expressions, tracking and taking note of those literals become difficult processes. You
will need a place where you can store them and recall them for later use.
That is the function of variables. Variables are storage locations where you can store
your literals (numbers and text) and the result of your expressions or operations. You
might be already familiar with the concept of variables in Mathematics. Remember the
x, y, and z your Mathematics professors or teachers talked about during class? It is
almost the same as the variables in computer programing.
Of course, there are differences between them. First of all, variables in programming
does not only store numbers, but they can also store strings. For example:
>>> x = "this is a string"
>>> x
'this is a string'
>>> print (x)
this is a string
>>> _
On the other hand, the value of variables in programming can be changed anytime.
Instead of having a fixed or unknown value, the last value that you assign to a variable
will be its value. For example:
>>> x = 2
>>> x
2
>>> print (x)
2
>>> x = 124
>>> x
124
>>> print (x)

124
>>> _
Take note that so long as you do not assign a value to the variable, its value will
remain unchanged.
As you might have noticed, to create a variable in Python, you just need to assign a
value to it. To assign a value to a variable, you just need to use the assignment
operator (=). Take note of that since you might get confused to the = (equals sign) later
on. Also, always make sure that when assigning variable, you need to place the
variable on the left of the assignment operator and place the value on the right of the
assignment operator. For example:
>>> x = 2
>>> y = 4
>>> z = 9
>>> print (x, y , z)
249
>>> _
Heres a tip: you can actually assign values to multiple variables in one physical line
or logical statement. You just need to use the comma (,) separator. For example:
>>> x, y, z = 23, 15, 541
>>> print (x, y , z)
23 15 541
>>> _
Note that you must put the values respectively to the sequence of the variables to
prevent any mistake on your assignments.

Identifiers
Identifiers, sometimes called as labels or lexical tokens, are names in programming
that makes it easier to recall, invoke, or use a variable, function, class, object, and
etcetera. Since variables are intangible entities in programming (they are only
storage location after all and calling them using their address on the memory is a tough
job), you need identifiers in order to use them.
However, before you can create an identifier for a variable (or other elements), you
must know the following rules or naming conventions in Python:

No identifiers should duplicate each other. If you are going to use an identifier
similar to a functions identifier such as print, you will receive an error.

Identifiers are case sensitive. The variable named x is different from the
variable named X.

Identifiers should be at least one letter or underscore long.

Identifiers should start with a letter or an underscore. Do not start with a


number or any other symbol.

Identifiers can contain letters, numbers, and underscores. However, numbers


without letters or underscores are invalid and are automatically considered
numerical literals.

Expressions
Expressions are combinations of literal, variables, functions that return a value, and
operators. They can be assigned to a variable. But do note that the expression itself
will not be assigned, but instead, the result of the expression will be. For example:
>>> x = 1 + 1
>>> print (x)
2
>>> y = 2
>>> z = x + y
>>> print (z)
4
>>> a = z + 3 + (y * x)
>>> print (a)
11
>>> _
These components alone cannot provide you with enough power to create a decent
program. However, they are essential building blocks you will need. In the next
chapter, some functions will be discussed. Those basic functions will allow you to
give your program some use.

Chapter 5: Python Simple Input Output Functions


Take a rest from the technical details of computer programming with Python. Now,
you will learn some basic commands and functions that you can use in your future
programs.
In this chapter, you will know how create output and receive input. Output in
programming refers to data or objects that your program or computer generates for the
user or produces to your computers output devices such as your monitor, speaker, and
printers.
On the other hand, input in programming refers to data or objects that your program or
computer receives from the user or receives from your computers input devices such
as your keyboard, mouse, microphone, scanner, camera, and etcetera.

Basic Output
The most basic output function you can do as of now (and until much later in your
study of Python) is print. You have seen this function in most of the examples in the
earlier chapters. The main purpose of print is to produce output in your programs
console by displaying text.
To use the print function, you must follow this syntax:
print ("The text you want to print")
Always make sure that you always enclose the value or text you want to display using
print in parentheses. If you do not do that, you will receive an error like this:
>>> print "The text you want to print"
File "<stdin>", line 1
print "The text you want to print"
^
SyntaxError: Missing parentheses in call to 'print'
>>> _
You can use the print function to display the value of a variable. This method is a good
way to check the values of your variables in case you are not programming or running
on Pythons interactive interpreter. For example:
>>> a = "This is a string"
>>> b = 1234567890
>>> print (a)
This is a string
>>> print (b)
1234567890
>>> _
Also, you can put multiple values or arguments for the print function. For example:

>>> print ("First Value", "Second Value", "Third Value")


First Value Second Value Third Value
>>> _
This is a good way if you want to display multiple values or variables in one
statement. For example:
>>> x = "The big brown"
>>> y = "fox jump over"
>>> z = "the lazy dog."
>>> print (x, y, z)
The big brown fox jump over the lazy dog.
>>> _
Do not forget to use commas to separate the values you want to print. Also, take note
that displaying values this way will make Python generate spaces between the values.
On the other hand, you can use print to display the result of an expression. For
example:
>>> print (1 + 2 - 3 * 4 / 5.0)
0.6000000000000001
>>> _

Basic Input
Since you will be limited on a program console in your early days in Python, you will
be somehow stuck with one input function, which is input. The purpose of the input
function is to retrieve text from a user using a prompt. When the interpreter parses the
input function, it will pause the program and allow the user to type something and
submit his input by pressing the enter key. For example:
>>> input ()
_
The program will not progress until the user presses the enter key. By its own, input is
good in pausing programs and letting the user progress the program by himself. On the
other hand, aside from pausing the program, you can use the input function to display
text before the input cursor. For example:
>>> input ("Press enter key to continue... ")
Press enter key to continue... _
Of course, you would want to retrieve the text that the user will type on the input
prompt. To do that, you must assign the input function to a variable. The text or string
that the input function will return will be directly assigned to the variable. For
example:
>>> x = input ("Input a string for the variable x: ")
Input a string for the variable x: 3819451
>>> x
'3819451'
>>> _
Now, take note that the input function only returns string. That means that in the
previous example, the variable x does not have the numerical value 3819451 instead it
has a string '3819451'. To check:

>>> x + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
>>> _
To get around this, you must convert the data that the input function will receive. And
you can do that by using the int() or float() functions of Python. But they will be
discussed in another time.

Chapter 6: Pythons Syntax and Style Tips


As of now, you have become familiar with some of Pythons syntax. And to complete
your fundamentals with this programming languages syntax, read on.

Indentation and Space or Whitespace


Pythons syntax is a bit strict when it comes to whitespace. First, you must not put a
space before a statement without good reason. The only reason you will put a space or
trailing spaces before a statement is when the statement is inside a code block or you
want to raise its depth to the programs structure.
If ever you just suddenly placed a space before a statement, especially at the first line
of your program, then you will receive an error. For example:
>>> print ("Hello World!")
File "<stdin>", line 1
print ("Hello World!")
^
IndentationError: unexpected indent
>>>
Spaces at the start of a statement are considered an indentation. You will get an
indentation error if you suddenly indent one of your statements.
Spaces in Python are important. They separate identifiers, keywords, operators, and
almost all elements in Python. These spaces improve the readability of your code. And
it will help your code become less prone to errors.
In some cases, Python is lax when it comes to spaces. Sometimes, you can get away
without using spaces between the elements in your statements. For example:
>>> a=1+1
>>> a
2
>>>
However, it is not a good practice. But if you want to code like that, it is up to you.
Just remember that doing that will raise your chances of receiving syntax errors and
reading your source code will become difficult.

Comments
In programming, comment is an essential tool that can make your life easier. They can
be used to remind you something about your code, mark a part of your source code, or
provide explanation in case your forget something. And when you are coding a
complex and long source code, you will definitely thank comments for helping you
maintain your source code with ease.
If you are collaborating with another programmer, it will be much easier for you to go
on coding since you will not need to talk and ask each other on the things you have
done in your source code if you put comments. It saves time and reduce the chances of
the two of you blotching each others part of source code.
Unlike statements, the interpreter ignores comments. To create a comment, place a
pound or hash (#) sign before the comment. You can write virtually anything after the
pound sign, and Python will just ignore them. For example:
>>> #This is a comment
... #Python will just ignore lines after the pound sign
... #Even if I use signs and symbols anywhere here
... #Such as *^@)(*@_$(*Y@($*_(*0
... #Python will not return an error
... #This is a handy tool that you should use often
... #If you are in the interpreter and you want to escape the comment block
... #Just press enter on the next line
...
>>>
Comments become more useful if you write your code in a source code editor. Thanks
to those programs syntax highlighting feature, comment lines have different font color.
Usually, they have green font color.

Style Guide
Just like in publication or regular essay writing, programmers follow style guides.
Style guides are there to improve the readability of your code readability of your
code to humans that is. You do not need to follow any style guide that some company
or experts use or made. You can create one of your own. As long as it will make your
code more organized and clutter free, then your own style is good. Here are some
pointers when it comes to style:

Follow a naming style for your identifiers and stick with it. Do not just
randomly create identifiers for your variables or functions. One style is to
create an identifier that briefly describes the purpose of the object you are
naming. For example, exampleVariable, example_variable, or var_example are
good identifiers for an example variable that you want to use in your program.

Always put space between elements. This can never be stressed enough.
Surely, you will find it irritating to read a source code that lacks a lot of
whitespace.

Choose between spaces or tabs. Do not use both.

Deviate from your style when necessary.

Chapter 7: Flow Control, Decision Making, and Program


Conditions
Aside from providing output and getting input from the user, a program must be
capable of providing the necessary output when certain conditions are met. In
programming, you can do that by practicing program flow control using conditional
statements.

Conditional Statements
Conditional statements are statements that allow programs to execute a code whenever
a condition or requirement is satisfied. Conditional statements can be separated into
two parts. The first part is the Boolean expression or Boolean condition. The second
part is the block of statements or statements that will be executed once the Boolean
expression is satisfied.
Boolean Expressions
Boolean expressions are operations that may or not involve comparison operations,
logical operations, or both. Boolean expressions only produce truth-values as a result
when the expression is processed or evaluated.
Truth-values
Truth-values are constants and there are only two truth-values: True or False. Usually,
the constant True is equivalent to 1 and the constant False is equivalent to 0 in some
programming languages. However, in Python, any number aside from zero and nonnull values are equal to True. And zero and null are equivalent to False.
Comparison or Relational Operators
Comparison operators are used to compare two values. Typically, they are when
comparing numbers or showing the relationship between two numbers. Some of the
comparison operators that you can use in Python are:

Operator

Operator Name

True

==

Is equal operator

Returns True if the two Returns False if the two 1 == 1 = True


values being compared are values being compared are 1 == 2 = False
equal
unequal

!=

Is not equal operator

Returns True if the operands Returns False if


are not equal
operands are equal

>

Greater than operator

False

Example

the 1 != 2 = True
1 != 1 = False

Returns True if the left Returns False if the left 2 > 1 = True
operand has a greater value operand has a lesser value 2 > 2 = False
than the right operand
than the right operand
2 > 3 = False

<

Less than operator

>=

Greater than
operator

<=

Less than or equal operator

or

Returns True if the left Returns False if the left 2 < 3 = True
operand has a lesser value operand has a greater 2 < 2 = False
than the right operand
value than the right
2 < 1 = False
operand

equal Returns True if the left Returns False if the left 2 >= 1 = True
operand has a greater value operand has a lesser value 2 >= 2 = True
than or is equal to the right than the right operand
2 >= 3 = False
operand

Returns True if the left


operand has a lesser value
than or is equal to the right
operand

Returns False if the left 2 <= 3 = True


operand has a greater 2 <= 2 = True
value than the right
2 <= 1 = False
operand

If Statement
The if statement is one of the simplest conditional statements in programing. Despite
the if statement having the same function across different programming languages, the
syntax of the if statement in Python is a bit different. Nevertheless, it still follows the
same concept. Below is an example of an if statement:
>>> x = 3
>>> if (x == 3):
... print ("x is equals to 3 that is why this message appeared.")
...
x is equals to 3 that is why this message appeared.
>>> _
In the example, the variable x was given a value of 3. Then the if statement was
created. The statement created a comparison between x and 3. It checks if variable xs
value was equal to 3. Just below the if statement is an indented print statement. Take
note that all the indented statements that falls under the if statement will be executed if
the Boolean expression returns a True value.
If ever the Boolean expression returns False, the indented statements below the if
statement will be ignored. For example:
>>> y = 4
>>> if (y == 5):
... print ("Will this work?")
...
>>> _
In this case, the Boolean expression returned False since the value of variable y is not
equal to 5. And since the if statement received False, it did not execute the print
statement under it.
To simplify things, here is the syntax for the if statement:
if (<place Boolean expression here>):

<insert indented statements to be executed if Boolean expression returns true>


Do not forget the colon after the expression. It signifies that the if line is done and it is
time to put the indented statements. Also, do not forget to enclose your Boolean
expression inside parentheses.
Another thing to note is that always put indentation on the statements you want to
execute if the Boolean expression returns True. If you do not indent the statements
below the if statement, it will be not be included on the if statement block.
When indenting, choose space or tab only. One space is enough as an indentation. On
the other hand, it does not matter how many spaces you use for indentation as long as
the succeeding statements for the if block has the same indentation. For example:
>>> x = 1
>>> if (x == 1):
... print ("text")
... print ("text")
File "<stdin>", line 3
print ("text")
^
IndentationError: unexpected indent
>>> _
On the other hand, if you are finished with the if block, you can place statements that
you want to execute after the if statement is processed. You do not need to worry about
indentation.

Else and Elsif


What if you want your program to do something else if ever the if statements Boolean
expression returns False? In that case, you need to use the else statement. Else
statement is like an if statement. However, else do not need to have a Boolean
expression.
The statements under else will be read in case the previous if statement returns False.
That is a simplified explanation, and the behavior of the else statement might change
depending on how you will use it. Nevertheless, below is an example on how to use
the else statement together with an if statement.
>>> x = 3
>>> if (x >= 4):
... print ("x is more than or equal than 4")
... else:
... print ("x is less than 4")
...
x is less than 4
>>> _
As you can see, you can just follow up an if statement with an else statement to capture
the False return of ifs Boolean expression. Since x >= 4 returned False, the
interpreter ignored the statement block for if. Instead, it processed the statement block
of else.
Take note, if statements can stand-alone. However, else statements cannot. They need
to be combined or used with if statements.

Conclusion
Thank you again for downloading this book!
I hope this book was able to help you to learn how to program and use Python as a
programing language.
The next step is to:

Practice programming Python

Learn how to use loops

Familiarize yourself with object oriented programming

Finally, if you enjoyed this book, then Id like to ask you for a favor, would you be
kind enough to leave a review for this book on Amazon? Itd be greatly appreciated!
Click here to leave a review for this book on Amazon!
Thank you and good luck!

Check Out Other Books by ZERO to HERO


Below youll find some of our other popular books that are popular on Amazon and
Kindle as well. Simply click on the links below to check them out. Alternatively, you
can visit my author page on Amazon to see other work done by me.

Programming Languages
HTML: Learn HTML Programming With Ultimate Zero to Hero Programming Crash
Course for Beginners
PHP: Learn PHP & mySQL Programming With Ultimate Zero to Hero Programming
Crash Course for Beginners
R: Learn R Programming With Ultimate Zero to Hero Programming Crash Course
for Beginners
Ruby: Learn Ruby Programming With Ultimate Zero to Hero Programming Crash
Course for Beginners
Java: Learn Java Programming With Ultimate Zero to Hero Programming Crash
Course for Beginners
Python: Learn Python Programming With Ultimate Zero to Hero Programming Crash
Course for Beginners

* BONUS *: FREE Python Course!


I know how important it is to implement what you learn, or even learn by taking
action. As my Thank You for downloading this book I provide you with FREE
Python course where more than 900k students are enrolled! With this course you will
learn and use more of Python programming language, a very widespread language!
So what are you waiting for? Click here to get started now!
Or go to:http://bit.ly/1JFUYOc
We want you to succeed in your goal to mastering Python! Please make use of this
course, it will help you a lot!

Copyright 2014 by Zero to Hero - All rights reserved.


This document is geared towards providing exact and reliable information in regards
to the topic and issue covered. The publication is sold with the idea that the publisher
is not required to render accounting, officially permitted, or otherwise, qualified
services. If advice is necessary, legal or professional, a practiced individual in the
profession should be ordered.
- From a Declaration of Principles which was accepted and approved equally by a
Committee of the American Bar Association and a Committee of Publishers and
Associations.
In no way is it legal to reproduce, duplicate, or transmit any part of this document in
either electronic means or in printed format. Recording of this publication is strictly
prohibited and any storage of this document is not allowed unless with written
permission from the publisher. All rights reserved.
The information provided herein is stated to be truthful and consistent, in that any
liability, in terms of inattention or otherwise, by any usage or abuse of any policies,
processes, or directions contained within is the solitary and utter responsibility of the
recipient reader. Under no circumstances will any legal responsibility or blame be
held against the publisher for any reparation, damages, or monetary loss due to the
information herein, either directly or indirectly.
Respective authors own all copyrights not held by the publisher.
The information herein is offered for informational purposes solely, and is universal
as so. The presentation of the information is without contract or any type of guarantee
assurance.

The trademarks that are used are without any consent, and the publication of the
trademark is without permission or backing by the trademark owner. All trademarks
and brands within this book are for clarifying purposes only and are the owned by the
owners themselves, not affiliated with this document.

You might also like