Beginner Guide To Python Programming PDF
Beginner Guide To Python Programming PDF
Copyright © 2016
No part of this eBook can be transmitted or reproduced in any form including print, electronic, photocopying,
scanning, mechanical or recording without prior written permission from the author.
While the author has taken the utmost effort to ensure the accuracy of the written content, all readers are advised to
follow information mentioned herein at their own risk. The author cannot be held responsible for any personal or
commercial damage caused by information. All readers are encouraged to seek professional advice when needed.
About the author
John Slavio is a programmer who is passionate about the reach of the internet and the interaction of the internet with
daily devices. He has automated several home devices to make them 'smart' and connect them to high speed internet.
His passions involve computer security, iOT, hardware programming and blogging. Below is a list of his books:
Comments
Literal Constants
Quotes
A Program to Practice
Operators in Python
Expressions
The If Statement
Functions
cPickle
Conclusion
Introduction to Python
At some point in time or the other, a lot of people get the urge to start
programming. However, most of them never make a move towards this field
because computer programming sounds scary. Well, you should know that it’s a
lot easier than it sounds. All it takes is the correct selection of programming
language.
other languages, it did not go obsolete, but in fact, has increased its use with
time. Python is broadly used in making web applications, GUIs (Graphical
user interface), games, etc., and writing and reading the codes in the program
are as simple as reading regular English sentences. Programs written in Python
are required to be processed before running, as they are not written in machine
readable language. Once you learn the basics of Python (as you are a
beginner), you will find it easy to move on to the advanced features that the
program offers to programmers. Below are some features of Python that make
it a favorite.
Outstanding Features of Python
Python is simple
problem and find a solution, rather than worry about the mistakes that he could
make while writing the program.
Python has the simplest syntax that you can find in any programming language;
therefore, even a beginner can learn it easily in a short time.
Python is the best example of Free/Libre and Open Source Software (FLOSS).
This is its strength as FLOSS gives the Python community the opportunity to
Python is portable
the need for changes to the Python file. You can use it on GNU/Linux,
Windows, Macintosh, FreeBSD, OS/2, AROS, Amiga, Solaris, AS/400,
OS/390, BeOS, z/OS, QNX, Palm OS, VMS, Acorn RISC OS, Psion,
We will discuss how you can install Python on various platforms in the next
chapter of this book.
Python is embeddable
Can you now understand why you should learn Python as your first
programming language? If yes, then let’s continue to the next chapter.
Installing Python on Various Platforms
Once you click on the version that you want to install, you will go to the
next page where you can see all the recent changes and features that were
added to it. Scroll down on that page to reach the Files section.
From the Files section, you can download Python. Ensure that you select
the correct Operating System for your download.
Once the download is complete, open the downloaded file and follow
the on-screen instructions.
Once you are on the Customize screen, scroll down to find the “Add
Python.exe to Path”, there you will see a red ‘x’. Click on this icon and
select the “Will be installed on local hard drive” option, then click
“Next.”
Now the command prompt will start which will download and install
Python on your machine.
After the installation is complete, you can exit the setup by clicking on
the ‘finish’ button.
The next step is adding Python to system path variables. If you
downloaded version 3 for Python, this step is not required. However, if
you installed Python version 2, you will have to complete this step.
Doing this step ensures that Python can work perfectly and can run all its
scripts on the Windows machine without creating any conflict with your
operating system.
Start by opening your Start menu on your machine and then typing the
word ‘Environment’. Then select ‘Edit the system environment
variables.’
After that, system properties will open in front of you in a new window.
At the bottom of this window, you will see a button named ‘Environment
Variables…’ proceed by clicking on this button.
Once the window with Environment Variables opens, you will see the
bottom section named as ‘System Variables’. Create the new variable by
clicking on ‘New’.
Now, a new window will open with options to enter the name and
variable value. In the name box, enter the name of your script, and in the
value slot, enter the code. The code is given below
–‘C:\Python27\;C:\Python27\Scripts;’
The above code may change depending on the Python version that you
installed. Now save all the changes and you are done.
Running Few Programs on Your New Install
In the previous section, you learned how to install Python on your Microsoft
Windows machine. Now, it is time to test your Python installation by running
some basic programs in it for a start. Let’s start with opening Python on your
Windows machine.
To open Python, click on Start and type “python”. Two or three options
will appear. Select “IDLE (PythonGUI)”.
Once Python starts, you can test its functioning by using a simple Print
directive as explained in this step. This directive which print whatever
you type on your screen as it is. Begin by typing your first directive
similar to the one in the below image, you can change the green line to
whatever you want.
If you installed Python 3 on your machine, then the symbol >>> must
have caught your attention already. This symbol indicates that you can
perform simple mathematics in Python without needing any sort of
directive. Try doing some of the simple mathematics questions like the
ones shown in this image -
Now, let’s look at other operating systems available and learn how you can
install Python on them.
Installing Python on Linux
You might not know this but for GNU or Linux users, Python comes already
installed by default. To check if you have Python already installed, simply open
the terminal application on your Linux machine, or press Alt+F2 from your
keyboard and then enter gnome-terminal. Now type the following command to
$ python –V
Python 2.7.6
Installing Python on Mac OS X
Just like GNU or Linux, Mac OS X also comes with Python already installed
by default.
To check this, simply press the Command and Space keys together from
your keyboard to open the Spotlight search.
So, that’s it for installing Python on your machine. From now on in this book, it
will be taken for granted that you have Python already installed on your system.
That being the case, why don’t we get used to Python by learning few basics
about it in the next chapter?
Your First Steps towards Learning Python
When using Python for writing a program, you have two choices. One is to use
the Interpreter Prompt to write your program and the other by using a Source
file.
Using the Interpreter Prompt
Begin by opening the Python terminal as we did when we were installing it on
your machine. Once you start the Python program, you will see the >>> symbol
on your screen. Start typing in front of the symbol. This icon is called
Interpreter Prompt. Now, let’s learn how to use this interpreter prompt by
Next to >>> symbol, type: print(‘Hello World’) and press the enter key. You
will now see Hello World printed on your screen.
You will notice in the above program that Python returns the result for your
input as soon as you hit the enter key. What you just typed in Python is known
as single Python statement. At the end, you will notice that the >>> symbol
appears again, which means that you can now write another line in Python.
After writing a program, if you need to quit the interpreter prompt, you can do
so by using Ctrl+D from your keyboard, or by entering exit() if you are using
Linux or Mac machine. However, if you are on Microsoft Windows on your
machine, use Ctrl+Z from your keyboard and then hit Enter key to exit the
interpreter prompt.
Using an Editor in Python
The interpreter prompt is okay for writing the programs in Python. However,
we cannot keep typing our program again and again whenever we want to
execute it. To save time, we need to save our programs in files from where we
can run them as many times as we want when they are needed. The files used to
save the programs are known as source files. For creating the Python source
file, an editor software is required for Python where we can write our program
and save it. Selecting the correct editor program is important as the better the
program is, the easier it will be for you to write in it, therefore saving you a lot
of time. One of the most basic requirements of a good editor is syntax
highlighting, thus coloring all the different parts or lines of your program.
Because of this, you can visualize the program running while seeing it on your
screen.
As a beginner, I recommend that you go for the PyCharm editor software. This
Print(“hello world”)
Now, without selecting any text that you wrote, right click on the line and
select Run ‘hello’ or press F10 from your keyboard.
You will now see that PyCharm shows the end result of your program just
below it. Look at this picture to understand it better –
Saving your program is also easy. Simply right click and select Save ‘hello’.
To save all your programs, select a new location on your computer or create it.
/tmp/py on Mac OS X
/tmp/py on GNU/Linux
C:\\py on Windows
This was the standard method of using an editor to write and save your
programs or projects in Python. This method is also known as using source
files to write programs in Python. Now, let us try to run the program using the
python hello.py
Here, hello.py is the file that you just saved. You will see that Python will
instantly display the output of the program that is present in hello.py file.
If you could follow the process until now, then it is time to congratulate
yourself, as you have written, run and saved your Python program, which is the
biggest challenge for beginners learning the software.
Now, let’s take it to the next step and learn a few more basics of Python before
we start to write programs in it. See you in the next chapter.
Python Basics for Beginners
Of course, you just do not want to write print statement programs in Python.
You would want to create more, I am sure. You would like to give Python some
inputs that you can manipulate to get the desired output, don’t you? But, you
cannot do this as you don’t know basic terms used in Python and their
meanings. However, after reading this chapter, you will be able to quickly
create a simple program as you wish. So, let’s get started!
Comments
You will most often see a symbol # in python programs, this symbol is used for
making comments. The text written next to this symbol is known as a comment.
These are mainly used as a means of creating notes in the program for both
developers and readers, so that they can know where they are, in the program.
For example –
In the above program, the comment tells the reader that what he is seeing is a
simple print statement and nothing else. In Python, the comments can be used
for any of the following –
Explaining the problems that you are trying to find answer for.
Explaining the problems that you are trying to overcome, etc.
Literal Constants
Numbers such as 2,3,4,5, etc., and strings like ‘This statement is a string’ are
examples of “literal constants”. These are called literal constants because you
can only use their value. The number 5 for example, will always represent
nothing other than its value. This is because its value can never be changed, 5
Single Quote
‘This is a quote’
All white spaces i.e. tabs & spaces, within the single quotes, are saved as they
are.
Double Quote
There are times when the single quote comes in between the sentence of the
string, for example – ‘What’s that?’
Python will now get confused as there are 3 single quotes. It will not
understand which quote is the end, the second or the third. To tackle this
problem, we use double quote. For example –
“What’s that?”
Python will know that the string starts and ends with “ and not ‘, and will work
without getting confused.
Triple Quote
You can use the triple quote when you want to specify a multi string in your
program, you can include both single quote and double quote freely inside
triple quote. Below is an example for you to understand properly.
'''
The Format Method
When you are creating a program, sometimes you will come across a situation
where you will need to build strings based on some other information. To do
so, we use the “format” method. It is denoted by format().
age = 23
name = 'Sushant'
This means that the first value is the name and the second value is the age.
Python will now take these values from the information provided to create the
output. The output of this program is –
$ python str_format.py
“escape sequence” and it is denoted by \’. For using it in the above problem,
all we have to do is write it in the following manner –
What\’s that?'
Is same as -
If in a string there is only a single backlash towards the end of line, then this is
an indication for python that the same string continues in the next line without
adding any new line. For example –
"You are at the first statement. \
Is same as -
understanding.
# Filename : sample.py
a=6
print a
a=a+1
print a
print b
7
You are at the first line of multi string.
Explanation – Let’s look at what we just did. First, by using the assignment
operator ( = ), we assigned a value of 6 to the variable a ( 6 is literal constant
here). After this, using the print statement which you are familiar with by now,
we printed the value of a. Now, we add 1 to the initial value of a and stored it
as a final value for our next step. We then printed the final value of a which is
7. In the same way, we created a string b and printed it on our screen.
Now, let’s move to the next chapter of this book and learn some of the python
operators which are often used.
Various Operators & Expressions Used in Python
In this chapter, we will learn various operators along with their precedence
order in Python. Operators in Python are included in expressions that you
write. Thus, it is important that you understand both the operators and
expressions. For a start, you should understand that most statements written in
2+3
+ (plus) operator
3 + 10 = 13
- (minus) operator
5–2=3
* (multiply) operator
This operator gives the result by multiplying the objects. For example –
2*3=6
When applied to strings, the operated repeats it for the given munber. For
example –
** (power) operator
/ (divide) operator
This operator divides the first value from the second. For example –
4/2=2
% (modulo) operator
This operator gives the remainder after dividing the first value from the
second. For example –
13 / 3 = 1
This operator takes the number of bits specified in account and shifts the bits to
left by that number. (Every decimal value is represented by binary digits i.e. 0
and 1 (or bits) in the memory)
4 << 2 gives 16
This works the same way as the left shift, the only difference is that it makes a
shift towards the right.
For example -
The decimal value 4 is represented in bits by 100, when this value is right
shifted by 1 bit, it gives us 10, which is represented by 2 in decimal value.
This operator gives the Bit-wise AND result for the numbers. Example -
7 & 1 gives 1
7 | 1 gives 7
7 ^ 2 gives 5
This operator works on the bitwise inversion method. For a, the bit wise
inversion is –(a+1) For example -
~6 gives -7
Comparisons done using this operator can also be done arbitrarily. For
example –
If both of the operands are numbers, then they are converted to a common type
before applying the operation. Otherwise, this operator always gives the result
as False.
The operator looks like the symbol of comment, however, it works in a totally
different manner. It tells us if the a is less than or equal to b.
This operator works in same manner as the # operator, the only difference is
that it checks for greater than or equal to.
a = 6; b = 1; a >= 1 gives the result as True
Another comparison operator in python which tells if the given numbers are
equal or not. For example -
a = 3; b = 3; x == y is True
Another interesting comparison operator which checks if the two numbers are
unequal or not. For example -
We will now look at Boolean operations. These are kind of tricky, therefore
pay close attention while reading them.
Per this operator, if a is True, then it returns the answer as False. If a is False,
then it gives the answer as True. For example –
In the case, above, Python will not evaluate b. This is because it knows
already that the value to the left of ‘and’ operator is False. Hence, it ignores the
right-hand side value and simply displays the result irrespective of it. This is
For this operator, if a is True, then the answer is given as True, else if a is
False, it will return for the evaluation of b. For example -
Don’t get confused in between and operator and or operator in python. Give
yourself proper time to know how they work.
Operator Precedence Table for Python
Before moving on, let’s first understand what precedence means. Consider an
expression – 5 + 8 * 24.
operator will be solved first. This means that the addition operator has lower
precedence than the multiplication operator. Similarly, operators have different
precedence level in Python. Below is a precedence table for python. In this
table, the operator with lowest precedence is kept at the top while the operator
with higher precedence is kept at the bottom. This means that the table is in
increasing order of precedence for python operations.
**Note - Objects with the same precedence are included in a single row
separated by commas in the table above. You may see that some of these
operators were not discussed before in this chapter. This is because they are a
bit advanced and hence are not fit for beginners.
Expressions
We discussed previously what expressions are. To end this chapter, we have
presented a program for you to do in Python on your machine. Save this
program as expression.py. Then test yourself to see if you know the meaning of
every line written in the program without looking at the explanations provided.
However, I would recommend that you read this chapter again and check to
ensure that you understand what variables, operators, and expressions are in
the program even after reading the explanation.
Sample program –
length = 10
breadth = 3
$ python sample.py
rectangle. These values are used in the program above to calculate the area and
perimeter of the rectangle by using expressions in python. We created an
expression for finding the area, which is later printed on the screen using along
with the statement - The solution for area of rectangle is. After that, we
directly found the value of perimeter by writing the expression inside the print
command next to the line - The perimeter for the same is. Python displays
every result in a neat way, taking care of adding spaces by itself if we forget to
add them ourselves. This makes the program easy to read and also makes the
life of the programmer tension free as python itself takes care of small mistakes
that a user might commit while writing the program.
Control Flow Statements in Python
based on the time. Here, you are asking your program to make some decisions.
In Python, you can do so with the help of control flow statements. There are
many control flow statements in Python, namely:
If statement
While statement
For loop
Continue statement
Let’s learn it with the help of an example, write and save the following
program in your python as if_statement.py
number = 25
if input_guess == number:
else:
print 'Done'
The output that you will get when you will run this program is –
$ python if_statement.py
Done
$ python if_statement.py
Done
$ python if_statement.py
Done
In the program created above, we first asked the user to enter his guess for the
number and then we checked his input against the number we already have.
Firstly, we set any integer for our variable number, like we set it to 25 in the
above program. After that, we recorded the guesses made by the user using the
raw input () function. For now, just remember that function is a reusable piece
of a program. We then waited for the user’s input after supplying a string to the
raw_input function that prints it on the screen. Once the user has entered a
value and hits the enter key on his keyboard, the raw_input () function takes the
entered value as a string. Then with the help of int, this string is changed to an
integer and after that it is stored as a value for variable guess.
After that, we compared the number with the value we already had. If the
number is equal, a message is printed on the screen. You will notice that the
“If” statement has a colon at its end, this way, we are telling Python about the
group of statements that follows. Next, we checked if the input value is less
than the value that we already have (that is 25). If it is so, a message is printed
informing the user that they need to make a guess of higher value than that. You
will notice that there is an elif clause being used in the program above. This
clause combines the two if-else-if else statements and present them as one
combined statement. This makes the program easier to understand and also
reduces the indentation required. After that, we check if the input value is
greater than the value that we already have. If so, then a message is displayed
to the user asking him to guess a lower value than that. Always remember that
the else and elif statements always have a colon towards the end, which is then
followed by their respective group of statements.
Once Python has completed the execution of one if statement along with its elif
and else clause, it then moves to the next if statement. However, we don’t have
another if statement in the program above. What we have in the next statement
in the main block is a simple print ‘Done’ statement. After this, Python sees the
end of the program and simply finishes up everything.
The While Statement
The control flow statement allows the user to repeatedly run a group of
statements if the condition is satisfied. While statement sometimes is also
known as looping statement and is used by many people to create recursive
functions in Python. You can use this control flow statement with the if
number = 25
processing = True
while processing:
if input_guess == number:
processing = False
else:
print 'Nopes, try guessing lower than this.'
else:
print 'Done'
Once you will run this program, your output will be like this –
$ python while_statement.py
Done
You must have noticed up to now that we are using the name guessing game as
a way of explaining the while statement. The advantage here is that the
program keeps running until the user has guessed the number correctly, hence,
we don’t have to run the program again and again for every guess like we did
Before while loop in the program above, we set the processing variable to
True. Then we first moved the if statements and the raw_input to inside of
while loop. Later, we first ensured that the variable processing is True. Once it
is verified, the while loop is executed. The condition is verified again after
executing the while loop, which in the program above is the processing
variable. If the condition is still satisfied, then the group of statements for
while loop is again executed. If it is not, then we run the optional else group of
statements and later we proceed to the next statement. When the while loop
condition is not true, the else statement is executed by the program. The
appropriate statement is displayed to the user depending on the guess he made.
If the guess is correct, the while loop ends and the program terminates with a
repeating itself until its terminating condition is satisfied. The same recursive
function can also be created with the help of the if else statement, as shown in
the example below –
Let’s create a program to find the factorial of a number. We know that the n! in
mathematics is n (n-1)! When n>1. Keeping this in mind, the program created
to find the factorial in Python is as follows:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print factorial(3)
The output of this program will give the factorial value. If N = 1, then the result
displayed will be 1, else the value N will be multiplied with the factorial N-1.
The program will then continue N-1 till it has reached N=1.
However, if you try the program to find the factorial of 3000 instead of 3, you
program using the specified word. This is the reason why the factorial word
was mentioned again before (n-1) in the second to last line of the above
program.
Files & Storing Persistently in Python
We have already learned how to write a program in Python, how to run it and
how to save it. However, we can open and use the files for writing or reading
by creating an object of the file and using its writing, reading or readline
methods appropriately. The ability to write or read the file totally depends on
the mode that you have specified for the file opening. Let’s understand this with
the help of a simple program.
simple = '''\
'''
f = open('simple.txt', 'w')
f.write(simple)
f = open('simple.txt')
while True:
line = f.readline()
if len(line) == 0:
break
print line,
f.close()
$ python io_using_file.py
(‘t’). If you open a file using open(), the file will be opened in text mode with
read mode enabled. In the example, above, we first opened our file in write
text mode and used the write method of the file object. After writing to the file,
we closed it using the close function, close().
After that, we opened the file again for reading. As we didn’t specify any
mode, the text file mode is selected for reading by default. Then, we read each
line of the program, until an empty line is returned by the program. An empty
line means that we have reached the end of our file. At the end, we closed the
However, the save function only saves the file in text format (.txt) which is not
optimal because once your program is written in a text file, it does not contain
any of its original data structure. It is simply a normal text file. If you want to
use this file to continue working, then you must process it and bring it back to
its original data structure.
A solution for this problem is to save the Python data object of your work as
itself. So, when you open your program later after dinner, you can just continue
working on it. Python has a standard module for doing so, called Pickle with
which you can store any plain Python object in a file and can continue working
on it later. The method of storing the data is known as pickling and usually it
has the file extension of .p or .pkl. Also, the method of loading the data is
known as unpickling.
Pickling and unpickling involve the use of reading and writing routines that we
discussed in the previous section of this chapter. Pickling is a module and it
needs to be imported first before you can use it. Let’s see how we can save the
data for a simple program that contains some grades of a few students.
f.close()
In the above program, we imported the pickle module first, then we created a
pickle file with a .p extension where the data will be dumped. We created and
opened this file with writing permission. After that, we used pickle.dumb to
dump the data of a current program to f which is the pickle file.
Pickling was easy, wasn’t it? In the same way, unpickling is also easy, just see
the steps below to load the same program that we dumped before.
f.close()
print mywork
Then we used the pickle.load module to load the data from that file as mywork.
Then we used the print module to simply print all the data that we loaded.
cPickle
If you are trying to dump or store a large volume of data, then you will notice
that the pickle module works at a very slow speed. An alternative available in
Python to solve this problem is to use cPickle. This module works the same as
Pickle, with the only difference being that it is almost 1000 times faster than
the standard pickle module because it is written in C. To use this module, all
you must do is write import cPickle instead of import pickle.
Sample Programs for Practice
Up to this point in the book, we have learned everything that a beginner needs
to know about Python. It is now left for us to start writing some problem-
solving programs. In this chapter, there is a total of 6 sample problems that
have been provided for you to practice. These problems are basic yet effective
Sample Program #1
In this program, you will learn how to find the square root of the positive
numbers.
Program Code –
# This is a program to find out the square root of the given number
number = 25
choice and see if you are able to run the program successfully.
Sample Program #2
In this program, you will learn how to find the area of a triangle with the help
of Python.
Program Code –
a=7
b=5
c=6
p = (a + b + c) / 2
Sample Program #3
In this program, you will learn how to use your Python to convert kilometers to
miles.
Program Code –
kilometers = 6.5
conversion_factor = 0.621371
Sample Program #4
In this program, you will learn how to easily differentiate between odd and
Program Code –
if (number % 2) == 0:
else:
In this question, instead of using the values by default, we asked the user to add
the values that he wants to check for even and odd numbers.
Sample Program #5
In this program, you will learn how to find the LCM of given numbers using
your Python.
Program Code –
if m > n:
greater = m
else:
greater = n
while(True):
L_C_M = greater
break
greater += 1
return L_C_M
number1 = 24
number2 = 54
You can simply change the values of two numbers in order to test the program
for different numbers.
Sample Problem #6
In this program, you will learn how to solve a quadratic equation using your
Python.
Program Code –
import cmath
p=1
q = -2
r = -3
# p = float(input('Enter p: '))
# q = float(input('Enter q: '))
# r = float(input('Enter r: '))
a = (q**2) - (4*p*r)
solution1 = (-q-cmath.sqrt(a))/(2*p)
solution2 = (-q+cmath.sqrt(a))/(2*p)
In this problem, we used the cmath module to create this program. First, we
calculated the discriminant and then we found the roots of the given problem.
Exercise for You
The above programs were simple but the last two had few terms that we did
not discuss in this book. Find out what those terms mean and try to make a new
program using those terms just like in the examples provided for you above.
Conclusion
simultaneously while reading this book. I hope that you have fun in learning
your first programming language. Lastly, I want to say thank you for
downloading this book.
Happy learning!