ecesem7.files.wordpress.com · Chapter 1 Introduction to Python and setting up Python Development...
Transcript of ecesem7.files.wordpress.com · Chapter 1 Introduction to Python and setting up Python Development...
Chapter 1 Introduction to Python and setting up
Python Development Environment
1.1 Why Python?
Python is considered as one of the most versatile programming languages. If you
have even a little experience in programming, then you will soon notice the
difference. Let's take a look at the features of Python.
1.2 Features of Python
1. It has simple easy-to-use syntax.
2. It can run on almost any platform including Windows, Linux's all distros(All
versions of Linux), Mac OS X, Unix etc.
3. You can even combine the pieces of other programming languages like C, C++,
etc with python to utilize the best of both worlds.
4. It's large standard library support makes real life programming much easier.
5. Other than that, it's open source, and have a huge community support working
actively with Python programming.
6. It's Object Oriented (also called OO Programming or OOP) which makes it
more applicable to be used in real world application programming.
7. Also, it can not only be used to write complex programs but can also be used to
design applications with GUI(Graphical User Interface).
8. Python is an Inerpreted language, as its the Interpreter which executes the
python code line by line, which makes it easier to debug. But it is a topic of never
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
ending discussion that is Python compiled? Well, technically it is, from user
written code to bytecode, and the bytecode is then sent to the Interpreter to
execute it.
9. Python has numerous implementations like CPython(The Standard
implementation of python), Jython(Targeted for integration with java
programming language) etc.
As far as its simplicity of syntax is concerned, let's see an example code. Consider a
program where you want the user to enter something from the keyboard and you
want to save that value in a variable. For C++, a popular programming language,
here is how you will be writing it:
#include<iostream>
using namespace std;
int main(){
int x;
cin >> x;
return 0;
}
For Core Java, another popular programming language, it will be:
import java.util.Scanner;
class Test{
Scanner input = new Scanner(System.in);
public static void main(String args[]){
int x;
x = input.nextInt();
}
}
And in Python, it is (*drum roll*):
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
x = input()
No kidding. That's all it will take. No file importing, no curly braces, no semicolons
and just one line. It's really not necessary to understand that code piece right now. It
was just meant to demonstrate you that how Python can be a programmer's relief.
Another thing that can be noticed in above code is, in the case of C++ and Java user
can only type any integer as the input to variable x, because we have declared
value x as an integer by specifying the code: int x;. In case of Python, programmers
don't have to explicitly specify the data type while declaring a variable, python's
compiler will do that itself, based on the type of value assigned to the variable.
1.3 Few things about the course
To be precise there are currently two releases of Python that are available on their
official website i.e., Python 2.x and Python 3.x. In this course we will be dealing
with Python 2.x, the reason behind this is because it is ideal to learn Python 2.x first.
Python 2.x is legacy, Python 3.x is the present and future of the language
Python 2.x is what has been used in the programming world until recently when
Python 3.x stable version was released. Hence, for beginners Python 2.x is more than
perfect to use, because you will find plenty of resources for it on the Internet.
Moreover, Python 3.x has a poor library support, as it is very new, which means we
will have less options to find and use ready-made functions/libraries. Certainly, this
is not suitable for a beginner, but you can shift to Python 3.x once you get a hold over
Python programming. So, let's get started with Python 2.x.
Also, there is not too much difference between Python 3.x and Python 2.x, the major
change is in the way how you print anything. It was just print in Python 2.x and in
Python 3.x they made it print(), yes added the brackets.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
1.4 Applications of Python
One can say, you can do almost anything with Python.
1. Web Application: Python can be used to develop scalable and secure web
applications. Frameworks like Django, Flask, Pyramid etc are amazing to design
and develop web based applications.
2. Computer Software or Desktop Applications: As python can be used to
develop GUI too, hence it is a great choice for developing desktop
applications. Tk is an open source widget toolkit which can be used to develop
desktop applications with python. Kivy is another such platform.
3. Scientific Computing Application: For its amazing computational power and
simple syntax, python is used for scientific computing applications. Python
libraries like SciPy and NumPy are best suited for scientific computations.
4. AI and ML(Artificial Intelligence and Machine Learning): Python is at the
fore front of the paradigm shift towards Artificial Intelligence and Machine
Learning.
5. Image Processing: Python is known for its image processing capabilities, which
includes traversing and analysing any image pixel by pixel. There are numerous
python libraries available for image processing, for example: Pillow, scikit-image
etc.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Starting with something that you might already be using: Websites
like Instagram, Reddit, Mozilla, have been developed using Python. There are
various web frameworks like Django (most popular one) and Pyramid, based on
Python, which can be used to develop modern web applications.
1.5 Installing Python
Steps to set up Python environment in your Windows system:
1. Go to python.org/download
2. Download the latest release for Python 2.x for 32-bit or 64-bit depending upon
your PC.
3. Open Installer and follow these steps:
Click on Next, once you have checked the selected options in the window.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
4. Once these steps had been followed, the installation will begin.
5. You can check whether the installation was successful by typing python -
V in cmd. If it returns the Python version that you have installed, then
congratulations you're all set.
1.6 Set Environment Variable
Windows users will also have to set the Environment Variable path with the
location of python directory, where it is installed. To set the path variable:
1. Right click on My Computer → Properties. Then in the left sidebar, click on the
last option with Advanced system settings
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
2. A new window will be opened, click on the button Environment Variable
3. Then to add a new User variable, click on New
4. Then write path as the variable name and copy the path of Python folder in the
value.
5. And it's done.
If you have a Macbook or you are using Ubuntu Operating System, then you do not
have to do anything, as Python comes pre installed with these operating systems.
1.7 Introduction to IDLE - Default Python IDE
In this section, you will get familiar with the development environment which has been
used throughout this tutorial series to run python code. It's probably the best
environment to write and execute the python code while learning. Moreover, there is no
extra installation required since it comes bundled with Python's compiler. So, if you
have followed the installation steps as given in the last chapter, you might already be
having IDLE in your system.
It's time to open IDLE now, you can do it by typing IDLE
in Windows/Mac/Linux search bar and it should appear.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
This is pretty much how it looks. You can see the cursor blinking right after >>>. This is
where you will be writing your code. Also, the current running version of Python is also
mentioned at the top.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
In IDLE we write code line by line. One line will handle one thing. You type whatever
you want in that line and press enter to execute it. IDLE works more like a terminal or
command prompt - You write one line, press enter, it executes.
We can also create python file which will contain the complete multiline program and
can execute that using IDLE as well. A python script has an extension .py.
Python takes some time to compile, its compilation is not fast, thus writing the example
code in a file, then compiling the whole code again and again gets tedious and is not
suited for beginners. When we open the IDLE, a session is created, which saves all the
lines of code that you write and execute in that one window as a single program. This is
the reason why, what you wrote above may affect what you will write later, eg. using a
variable. Here is a preview of how we will be typing in IDLE.
IDLE is pretty neat in its own way. You can choose custom colours for the background
and text, to give it your own style. There is an auto-complete feature, which predicts
what you are typing and suggests it (pretty much like Google search).
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Above all, it is available for all major operating systems!
Chapter 2 Basic Syntax & First Program
In this tutorial we will try to understand the syntax of python programming. Although,
syntax is something that you will understand as you will see more and more programs
and examples, but there are a few things that you must know beforehand.
2.1 Python Syntax Rules
1. Python is case sensitive. Hence a variable with name yoyostudytonight is not same
as yoYoStudytonight
2. For path specification, python uses forward slashes. Hence if you are working with
a file, the default path for the file in case of Windows OS will have backward slashes,
which you will have to convert to forward slashes to make them work in your
python script.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
For window's path C:\folderA\folderB relative python program path should
be C:/folderA/folderB
3. In python, there is no command terminator, which means no semicolon ; or
anything.
So if you want to print something as output, all you have to do is:
print "Hello, World!"
Oops! we just shared the first python program too with you. Yes, just one single
statement.
4. In one line only a single executable statement should be written and the line
change act as command terminator in python.
To write two separate executable statements in a single line, you should use
a semicolon ;to separate the commands. For example,
print "Hello, World!" ; print "This is second line"
Live Example →
5. In python, you can use single quotes '', double quotes "" and even triple quotes '''
""" to represent string literals.
word = 'word'
sentence = "This is a one line sentence."
para = """This is a paragraph
which has multiple lines"""
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
6. In python, you can write comments in your program using a # at the start. A
comment is ignored while the python script is executed.
# this is a comment
print "Hello, World!"
# this is a
# multiline comment
7. Line Continuation: To write a code in multiline without confusing the python
interpreter, is by using a backslash \ at the end of each line to explicitly denote line
continuation. For example,
sum = 123 + \
456 + \
789
Live Example →
Expressions enclosed in ( ), [ ] or { } brackets don't need a backward slash for line
continuation. For example,
vowels = ['a', 'e', 'i',
'o', 'u']
8. Blank lines in between a program are ignored by python.
9. Code Indentation: This is the most important rule of python programming. In
programming language like Java, C or C++, generally curly brackets { } are used to
define a code block, but python doesn't use brackets, then how does python knows
where a particular code block ends. Well python used indentation for this.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
It is recommended to use tab for indentation, although you can use spaces for
indentation as well, just keep in mind that the amount of indentation for a single
code block should be same.
if True:
print "Yes, I am in if block"
# the above statement will not be
# considered inside the if block
the correct way would be,
if True:
# this is inside if block
print "Yes, I am in if block"
Also, the following code will give error, as the statements are differently indented:
if True:
# this is inside if block
print "Yes, I am in if block"
# this will give error
print "me too"
again, the correct way to do so is to keep all the statements of a particular code
block at same indentation.
if True:
# this is inside if block
print "Yes, I am in if block"
print "me too"
So these are some basic rules that you must know so that it becomes easier for us to
learn various concepts of python programming in the coming tutorials.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
2.2 First Python Program
We already shared the first python program with you while learning the syntax. Yes, we
were not joking, it's just one single line, nothing above it, nothing below it. To
print Hello, World! on screen, all you have to do is:
print "Hello, World!"
Live Example →
You can write and execute this code in IDLE, or you can save this code in a python code
file, name it test.py(you can name it anything, just keep the extension of the file as .py).
To run the test.py python script, open IDLE, go to the directory where you saved this
file using the cdcommand, and then type the following in command prompt or your
terminal:
python test.py
This will execute the python script and will show you the output in the line below.
From the next tutorial we will start learning the various concepts of python
programming language.
Chapter 3 Python Numbers, Variables and built-
in Math Functions
In this section, we will be learning about Numbers and various Math functions available
in python language. In Numbers, we will see some of the most commonly used math
operators that we can use to perform various operations on the numbers in python.
Under Math functions section, we will learn about some shortcuts (called functions),
which are very helpful in calculating some of the complex mathematical expressions
like power, sine/cosine, factorials etc. So, let's begin. We recommend keeping the IDLE
open, while reading, so that you can practice and learn simultaneously.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
3.1 Numbers
In Python we have 6 basic mathematical operators, they are:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulo
6. Power
Most of you must be familiar with all of the above operators except for
the modulo operator. Don't worry we will explain it. Let's start from the beginning.
3.1.1 Addition
As you might have guessed it's just simple addition of numbers. In order to test the
operator, just go to IDLE and type a number, then addition sign +, and then another
number to add to the first number. Press Enter. This must look like this.
Example: Taking 8 and 19 as example,
>>> 8+19
27
On pressing return(or enter), the answer will appear just below the code line. And this
is how the output will be displayed, all the time - just below your code line. As you'll hit
the enter key, output will appear in the line below.
Don't stop with this example, try using the addition operator with other numbers. Try
number with decimal places, like 4.5 + 5.5 and so on.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
3.1.2 Subtraction
Just like addition, subtraction has the same syntax. Just change the operator to -. Again,
pick some random numbers and try.
Example: We took 89.33 and 23.67, which gave the output 65.55.
3.1.3 Multiplication
Same again! Just change the operator to *, also known as an asterisk. You do know that
it's used for multiplication, right? Go ahead and try it in you IDLE.
Example: Take any two numbers and multiply them using the * operator, just like we
did below.
3.1.4 Division
Use / sign this time. And try with random numbers. Caution: If you're a beginner, you
might find some difficulty in this one. How? Let's see. Let's take some integer numbers
(numbers without decimal) like 16 and 2, and divide them.
>>> 16/2
8
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Very well. Next, try with 15 and 2. What do you expect the answer would be? Well,
according to proper mathematics the answer should obviously be 7.5, but if you actually
try this in IDLE, the answer will turn out to be 7. This happened, because if we perform
any mathematical operation on an integers then the answer would be an integer. In our
case, 15 and 2 both are integers, hence, our answer is 7, as the answer has to be an
integer.
You might be wondering if it had to be an integer, why it turned out to be 7 and why not
any other integer number. Well, that is because the answer is determined as the closest,
smaller integer to the original answer. In our case, the original answer is 7.5, thus the
nearest integer to it is 7 and 8, and since we have to pick the smaller one; 7 is picked as
the answer. In mathematics, it is also known as floor function (it's there in Python too).
Now talking about the solution to the above problem, all you have to do is, convert any
one of the integers(that you want to divide) into decimal, i.e. write 15.0 instead of 15
and/or 2.0 instead of 2.
3.1.5 Power
This mathematical operator is not usually found in common programming languages. In
fact, Python is the only language we know which does have an operator for this. In rest
of the languages, they use some pre-defined functions (shortcut as we mentioned
before) to calculate this. Getting to the point, just put two asterisks like ** between any
two numbers. Example, to calculate 2 to the power 10, you have to write:
>>> 2**10
1024
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
With that, we now know about all the commonly used mathematical operators of
python. Now you can try to combine multiple operators and use them to form one
expression. We will recommend using brackets so that python can understand what
you want as the answer, i.e. instead of writing 2-9.0/2, write 2-(9.0/2).
Remember BODMAS, how a mathematical expression with multiple operators is solved
in mathematics.
3.1.6 Modulo
Modulo operator is denoted by % percentage sign. If you are familiar with the computer
programming world, chances are you already know this function. In case you don't, no
need to worry. You know division, right? Then you know what remainder is, correct?
This Modulo operator, when used with two operands, returns the remainder as the
answer. Here are some quick examples.
12%2 = 0, since 2 perfectly divides 12.
13%2 = 1, since dividing 13 with 2 leaves 1 as remainder.
19%5 = 4, because, again, 19/5 leaves 4 as the remainder.
It is used in pretty much the same way as it has been explained here.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
To see all the Math operators covered above, live in action, click on the Live Example
button,
3.2 Math Functions in Python
As you learn more about python, you might decide to create a scientific calculator for a
project or anything. For that, along with simple mathematical operations, you will have
to evaluate some complex mathematical operations as well, like trigonometric
operations, logarithmic operations etc. Forget about the calculator, there can be various
situations where you might need these functions. Like a software for civil engineers to
calculate various parameters of any structure that they are building, or any aerospace
software - where they need various kinds of calculations about satellite trajectory,
shuttle trajectory and what not. In a nutshell, the complex mathematical operations are
used in various real life programs and softwares, hence you must know about them.
Now in Python, some nice guys have already created code pieces (libraries) for almost
every mathematical function. We can use these codes without any hesitation and the
plus point is, we won't have to re-write it again. Forget about rewriting, we don't even
have to know what the complete code is. We only need a few key information to be able
to use these readymade code pieces.
Alright, so unofficially function part had already begun. We'll learn about functions in
detail in later chapter, thus we'll keep this one short.
Function can be described as a piece of code that may or may not take some value(s) as input,
process it, and then finally may or may not return any value as output.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
As you can see in the figure above, here input x is given to a function f and it is giving
some value f(x) as the output. Although in general programming world, depending upon
the purpose of the function, input and output are completely optional. But for a
mathematical function, it's very important to have both.
For example, in the trignometric function sin(x), there must be some value of x in order
to calculate and return the answer, and that pretty much establish why mathematical
functions have both inputand output.
In python, there are two types of pre-defined functions.
Inbuilt functions: These are the functions which doesn't require any other(external) code
file (known as, Modules or Library Files). These are a part of the python core and are just
built within the Python compiler hence there is no hassle of importing these
modules/libraries in our code.
The second type of functions require some external files(modules) in order to be used. The
process of using these external files in our code is called importing. So all we have to do is
import the file into our code and use the functions which are already written in that file.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
It's time to try some of the functions. Let's begin with power functions.
3.2.1 Power - pow(x,y)
I know what you might be thinking. We just tried that, didn't we? Well, we did saw
something that can calculate power, but it was an operator and this one is an inbuilt
function (yes, the first type). So, with that just consider this one as an alternative way to
calculate power.
Since this one is an inbuilt function, you don't need to import any other library files
(or modules), hence it's pretty easy to implement.
Since power function will be needing two numbers(inputs) to perform the operation,
i.e. base and exponent, hence we will have to provide two numbers to the function. Go
ahead, open the IDLE and write:
>>> pow(3,2)
Now let's analyse what we did and what will happen. First, we wrote pow, which is
simply the name of the function that we are trying to call. This will tell the python
compiler to look out for an inbuilt function named pow and discover what it can do.
Next, within the brackets we wrote two numbers separated with a comma, i.e. 3 and 2.
Here the first number 3 is base and the second number 2 is an exponent, and we are
trying to calculate 32.
Once the python compiler has ensured that all the syntax (the grammar of
programming) is correct, it will look for the implementation of the function pow and use
it to find 32. So as you might have expected, the output would be:
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
With that, we now know, how a function is called. Especially for math functions, we can
generalise it as following:
>>> functionName(input1, optionalInput2, optionalInput3, ...)
The values inside brackets that had been separated by commas, which we mentioned to
you as input to functions, are called Arguments. As in pow(x, y) example given above, 3
and 2 were the arguments. There can be any number of arguments in a function. And as
we discussed earlier, for a mathematical function there usually is at least one argument
present. Let's see some another inbuilt mathematical functions.
3.2.2 Absolute - abs(x)
Absolute function, also known as Modulus (not to be confused with Modulo), returns
the non-negative value of the argument value. Therefore, absolute value of any non-
negative number is the same, while for negative numbers, their positive value is
returned.
Example: absolute value of -3 will be 3, absolute value of -8.74 will be 8.74 and so on.
Syntax:
>>> abs(-99.99)
Since -99.99 is a negative number, it's positive counterpart will be the output, i.e. 99.99.
Now let's try some functions where we have to import some modules(or library files).
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
3.2.3 Sine - sin(x)
Since we know sine is a trigonometric function, hence it accepts only one value as an
argument, i.e. x. Here x should be in radians, so you better not confuse it with a degree.
As we mentioned before we won't be able to use this function directly. If you do, you
might get an error, something like this, which will say name sin is not defined.
This is because the compiler doesn't know what it is supposed to do when it
encounters sin()function, as we have not defined this function but we are trying to use
it. So, in order to use it, we will have to import python's math module which consists
the implementation of the sin() function, which will guide the python compiler to
understand what to do when sin() is called.
What we are about to do is called importing a module and it's most oftenly done to use
already available ready-made functions. Importing a module takes just one extra line:
>>> import math
Hit enter, and you're done. Now in order to use the sin() function, go to a new line and
type:
>>> math.sin(3.14159)
Since 3.14159 is approximately the value of π hence the answer would be near to zero.
As you can see after math.sin(3.14159) statement, the answer returned was something
like 2.653589335273e-6, it might seem a little messy but it is an equivalent
representation of 2.653589335273 × 10^-6, or 0.000002653589335273.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Because of approximation in the value of π, the answer too just got deviated a little bit
from 0, but you can see the value is almost zero. And at the same time, you can see how
accurate the results are.
Now of course there are several other functions available inside math module,
like floor() (floor function; We mentioned this one in division
operator), exp() (Exponential function), log()(Logarithmic function), sqrt() (Square root)
and a lot more.
3.3 Variables in Python
This lesson deals with variables. Those who already know some programming must be
familiar with the concept of variable and its importance. Variable is an important
element of programming world, visually, you can consider variable as a box, that is
capable of storing some value within it.
In more formal terms, variables are used to store information to
be referenced and manipulated in a computer program.
They also provide a way of labelling data with a descriptive name, so our programs can
be understood more clearly by the reader and ourselves. It is helpful to think of
variables as containers that hold information. Their sole purpose is to label and store
data in the memory. This data can then be used throughout your program.
Let's see some examples. A variable is supposed to have a name. There are some rules to
assign a name to the variable.
The variable name can consist of alphabet(s), number(s) and underscore(s) only.
The first character in variable's name cannot be a number. Hence i-am-
variable, variable!, 1variable, #variable, are all invalid variable names.
While i_am_variable, variable, variable1, _variable, are all valid names.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
3.3.1 Storing value in a variable
Time to see how we can store a value in our variable. Consider a variable (or a box, if
you like it casually) named x. We want this variable (or box) to store a number, say 11.
Then in order to do that just go to IDLE and type:
>>> x = 11
And press Enter key. With that our variable gets created, named x, and with a default
value 11stored in it, using the equal to = operator. Remember, Equal to operator is
always used to assign a specific value to any variable. Variable's name will always be on
the left side and it's value will be on the right. Let's create another variable, say y and
assign it value 25.
>>> y = 25
Now in the current IDLE session, python is dealing with two variables, x and y, which
have values 11 and 25 respectively. If you want to check the value of any variable in
IDLE, simply type the name of that variable in a new line and press the Enter key. The
value stored in it will be printed on the IDLE screen in a new line.
>>> x
11
>>> y
25
Now try to look at the below code, what do you think this will do?
>>> x = y
As you can see on the LHS(Left Hand Side) we have x and y on the RHS(Right Hand
Side), hence as we explained before, the value on the right will get assigned to the
variable on the left. Since y has a value 25 stored in it, this statement will modify the
value inside x from 11 to 25. And hence if you ask again for the value of x, it'll be 25 now.
In this case, we just over-wrote the value inside xvariable.
>>> x
25
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Once you are done with the above example, let's be more creative this time while
naming our variables. Let's create a variable and assign your name as its value. So here
we are having a box named name, which is capable of storing any word. The process is
quite similar to what we did above but with just a tiny change. Watch carefully,
>>> name = "Sudytonight"
As you can see, we quoted our website's name within the double quotation marks. This
is because we don't want python compiler to get confused. Since Studytonight is a
word (or more precisely, stringin the programming world), we will have to surround it
with quotation marks. By doing so we tell python that it is a word. But, what is supposed
to happen if we write Studytonight without the quotation marks? Like this,
>>> name = Studytonight
Since there is no quotation marks, python will consider Studytonight as another variable
and will try to find the value stored within it so that it can further assign it to the
variable name. But since we never declared any variable with the name Studytonight,
python won't be able to find any value for it and in the end, it will throw an error saying
that the variable with name Studytonight is not defined.
Also, you can use both single quotation as well as double quotation in order to represent
a word (or string).
>>> name = "Studytonight.com"
>>> name = 'Studytonight'
Live Example →
Both are fine.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Try to use the variables as the arguments for the function. For example,
>>> x = 3
>>> y = 2
>>> pow(x, y)
9
>>> z = -7
>>> abs(z)
7
Next, you can try to save the answer of any mathematical function in a variable. Like,
>>> p = pow(5, 2)
>>> import math
>>> q = math.log(x)
Try using mathematical operators with these variables. Like,
>>> x+y
5
>>> x-y
1
Try using these variables in a mathematical expression including some mathematical
function and operators, all together, like,
>>> x = pow(x**y, p+2)
In the above code, python will first calculate the expression on the RHS(Right Hand
Side) first, and will use the old value for variable x, which is 3 and once the expression is
solved the answer will be stored in the variable x, which will become its new value.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
3.4 Modules and Functions in Python
In one of the previous section, we learnt about the math module. We also checked some
of its functions like the sin, log, etc., and also learned how they are used. Now just like
the math module, there are several other modules available in python library which can
be used directly inside any python program. Some of them are so important that
programmers literally can't make any real-life app without these modules.
In this lesson, we will revisit Modules and the Functions within them and will try to
have a better understanding of them.
3.4.1 Functions lie inside the Module
Consider modules as, just another piece of python code, saved somewhere within the
python package and you can reuse the code from the module files in any other (or your)
python code file. Now try to recall what we did after importing the math module. We
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
tested some of the functions defined inside the math module,
like math.floor(8.4), math.sin(3.14159) etc.
NOTE: pow(5,2), math.floor(8.4), sin(3.14159) are all examples of calling a function.
To see how we can use the import statement to import external modules
like math module, checkout the live example,
Now if, what we have written above is just a way to call and use these functions. Where
is the actual logic(code) to perform these complex mathematical operations stored? i.e.
calculating power, floor, or sine for the provided value(s). All this (code or logic), reside
inside the module file and is called Function definition. Function definition sets the
rules that how a function will interpret the input provided, perform some operation on
it and further what is to be returned as the output or result.
In fact, it is the function definition itself that decides the type and number of input(s)
and output (output is always one, but inputs can be multiple) for the functions. These
inputs have an official term for them, they are known as Parameters.
Parameter: Structure that defines the type of the input accepted, while defining the
function.
Argument: The actual value that is inserted as an input while calling/using the function.
Suppose we have created a module file StudyTonight.py (.py implies that it's a python
code file; Yes! you can create a module file yourself too, it's just python code after all).
Inside the module file, we have defined a function that can solve a quadratic
equation ax2 + bx + c = 0. Let the name of the function be qSolver(a, b, c).
All you have to do to use this function is, provide the value of a, b and c, i.e., coefficient
values of the equation, and the function will print whether the two solutions are real or
not and what are they. So, lets see how can we import the module and use the function.
Step 1: First import the module.
>>> import StudyTonight
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Step 2: Next call the function with appropriate arguments, i.e., for 2x2-6x+3=0, a=2, b=-
6 and c=3. Hence we will call,
>>> qSolver(2, -6, 3)
You don't have to try this function on IDLE since this won't work. Why? Well because
we hadn't actually created any module named StudyTonight.py in your local
system(laptop/computer). This was just to explain to you how module and functions
actually work and how we can create custom modules with functions defined by us. You
have to follow the same steps in order to call every function from the modules.
There are already many modules available for python. Some might have already been
installed in your system when you installed python, while others can be easily
downloaded from the internet. It all depends on what you need.
3.4.2 How to use a function defined inside a
module
Following are the things you should know while using a function defined inside a
module:
1. You must know which module contains that function.
2. Check if it's already in your system. If it is, then all good, otherwise go ahead and download
it from the internet.
(NOTE: You can check by importing that module in IDLE. Error means it's not
there.)
3. Next, identify the name of the function that you want to use.
4. Next, call the function. <module-name> is module's name, <function-name> is function's
name and <agrument-1>, <argument-2>... are the arguments of functions.
>>> <module-name>.<function-name>(<argument-1>, <argument-2>, ...)
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Note that the number of arguments depend on the function we are using. In some cases,
function might not accept any argument. It entirely depends on which function you are
calling, hence you must check the documentation to see the function definition before
using any function. Above called function may or may not return any value (function's
output). In some cases, we are often require to store the output for future use. We do so
by storing it in a variable, which we have already learnt in the last tutorial.
>>> variable-name = <module-name>.<function-name>(<argument-1>, <argument-2>, ...)
This only make sense when the function returns any value (output). Also, functions can
only return one output value or none at all.
Let's use what we have understood till now, to use a function lower() which is defined in
the stringmodule.
3.5 Additional Topic (What is String?)
String is just a term used to refer to a word like "Studytonight" or sentences
like "Studytonight is a good website".
They must be enclosed in single or double quotes ('...'/ "..."). In the previous chapter, we
have already explained how they can be stored in a variable. Variable which stores a
string inside them are called string variables.
Now the string module is different from the above explained String. This one is just a
module with name string with functions defined to perform various operations on
string variables.
So, the string module consists of some functions which deal with operations on strings.
In the example below, we will use lower(), which is used to convert every character of a
string to lowercase.
1. We already know that string is the library/module which consists of the function lower().
2. Import the string module to check if it's available. Since it's a basic module, it's very likely
that it will be there.
3. Check the documentation and find the function lower() in the module's page. It will give
you the information required to use it.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
4. It only has one argument which is a string. So create a string variable with value as "Let's
StudyTonight".
5. Next call the function,
>>> string_variable = "Let's StudyTonight"
>>> string.lower(string_variable)
Or, if you want to be direct and don't waste memory on saving a variable, just do it
like,
>>> string.lower("Let's StudyTonight")
Calling a function like we did above will only print the result when we hit enter. Just
like this,
As you can see, the returned value is having all uppercase letters (Capital letters)
converted to lowercase, i.e. L to l, S to s and T to t. In case you used a variable, keep in
mind that using a function like this doesn't modify the value of the original variable.
Thus even after using the function, the value of string_variable will remain as it was
before. So if you want, you can save the modified value in some other variable, or even
in the same variable itself, like:
>>> string_variable = string.lower(string_variable)
This statement is perfectly valid since python will compile everything from right to left,
i.e., it will first use string.lower() to get the modified string and then later assign the
output value to the string_variable variable using the = (equal to) operator.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Chapter 4 Input and Output in Python
If you think about it, you will realise that most of the real world programs or softwares
that you use, requires some input from the user.
Be it any smartphone application, like Facebook or Instagram where you have to first
input your email/username and password to login, then some posts in form of text or
photos in order to make it available on your profile. Or, in any ticket booking software
where you first have to specify the train/bus/movie name; etc.
Software is a bundle of programs, working together to perform a task or solve a
problem, that makes our life easier. And in order to perform any task or solve the
problem, the software must know the parameters of the problem(or, task to perform).
This is where programs take input from the user. Also, after taking these inputs the
program must process them and return some result. This is where outputcomes into the
picture.
In this chapter we will learn how to create a program in python that can take some
input from the user and print it back.
4.1 Taking Input from user
So lets say, you want to make a simple calculator in python. For that, you would have to
take one or maybe two input values from the user, then perform the user requested
mathematical operation on the input numbers and return the output. For simplicity,
let's just fix the user requested mathematical operation is addition for now.
We can add more operations to our simple calculator later, but let's stick to addition for
now. In order to perform addition, you will have to take two numbers as input from the
user (much like an ordinary calculator). The inputs must be assigned to or stored
in variables (say x and y). Now, below is the code, to accept user input, let’s see:
>>> x = input()
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Write the above code line in the IDLE and just press the Enter key. You will notice that
the cursor will not move to the new >>> line. Rather, it will start waiting for the user
input.
This is the time when you enter any number from the keyboard (lets say, 3). Just enter
any number and press the Enter key again and now you will see the newline with >>>.
And just like that, using the input() function (yes, it is a built-in function) you just stored
a value in the variable x. In order to make it more fancy, try this:
>>> x = input("Enter the first number:")
Live Example →
Now you will notice that the next line will print the message: "Enter the first
number:" and will wait for the user input. As you might have already guessed, printing a
message like this will inform the user that they should enter a value/number/input for
the program to proceed ahead. A good program should always have such intuitive
messages.
Next, ask for the value of y variable.
>>> y = input("Enter the second number:")
Now, its time to play around a little. Try taking input for variable x or y again and this
time instead of typing a number try typing any alphabet or any string. As you press the
Enter key, you will see python will throw an error.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
This clearly shows that input() method is not capable of handling anything other than
numbers. Then, of course there must be some other way to take words and other non-
number characters as input.
raw_input() is the function which helps us to do that. This function can take any non-
numeric data as input, be it a string or a character. Every input,
with raw_input() function, is stored in the form of a string during the input.
NOTE: Remember, there is huge difference between a number 1 and a string "1". The
number 1 is just a number to python which can be added, subtracted, multiplied etc., while
a string "1" isn't a number, instead it's a symbol (anything between double/single quote is
a symbol). Python can't do any mathematical operations on a string. We will discuss this in
later lessons.
Thus, if you use raw_input() and input any number, python won't be able to do any
mathematical operation on it. Now try to create a code snippet that can accept your
name. Remember, name is a string, hence we will have to use raw_input().
4.2 The Output
Now how can we display the input values on screen? You might think that all we have to
do is just type the variable and press the Enter key. Well, it is true that we have been
doing this the whole time, but this only works when you are working on IDLE.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
While creating real world python programs you have to write statements that outputs
the strings, or numbers explicitly.
We use the print statement to do so. Consider, printing a popular statement "Hello,
World". To do so, just type,
>>> print "Hello, World"
Don't forget the quotes, double or single, both will do just fine. Press the Enter key and
you will see the statement being printed at the bottom. If you try to just write "Hello,
World" and remove print statement, like,
>>> "Hello, World"
You will see that this will also print the line, however this time with quotes around it.
This is how you can differentiate among the two methods. Next, lets try printing a
number:
>>> print 9
Now try, printing two strings together. Create two variables, a and b. Assign them two
string values,
>>> a = "Hello"
>>> b = "World"
Now print them together.
>>> print a + b
HelloWorld
This is how it must appear. This is the example, showcasing how python can interpret
one single thing in two ways. Here the + operator, is used to join two strings instead of
performing mathematical addition (which is actually impossible to perform on two
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
strings anyways). Since, the mathematical addition of two strings doesn't make any
sense, hence whenever python encounter two strings with a + operator in between
them, it will just join them both.
The above operation can be performed in an another way as well:
>>> print "Hello" + "World"
HelloWorld
Now try printing a number and string together.
>>> print 5 + " is a number"
You will get an Error. Can you guess why?
This was because we tried to join an integer with a string. So lets establish a rule here
that-
"While printing we can't mix up two literals of different types."
Solution? We will have to convert the number 5 into a string. One way can be,
>>> print "5" + " is a number"
Or,
>>> print str(5)+ " is a number"
str() function, is just another built-in function that can be used to convert an integer into
a string. It is quite useful when it comes to converting a numeral variable (variable
consisting of numbers) into string. Like,
>>> x = 1
>>> print str(x)+ "st rule of Fight Club we don't talk about Fight Club"
1st rule of Fight Club we don't talk about Fight Club
To conclude, let's finish our calculator with addition function. So, far this is what we
have done:
>>> x = input("Enter the first number")
>>> y = input("Enter the second number")
Now, its time for the output.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
>>> print x+y
Or,
>>> print str(x+y)
Both will give the same output. Though, result of x+y will be a number, while the result
of str(x+y)will be a string.
Chapter 5 Data Types in Python
Let's do a quick overview of the data types that are available in Python. Of course,
this will become more and more clear as you use practice python more.
First, let's understand what Data Types are? As the name itself suggests, these are
some different types of data that the python compiler understands. Just like the
Computer can understand only binary numbers (i.e., 1 and 0), so that is the one and
only data type that a Computer can understand but python has more. As far as
Python, programmers are provided with various ways of representing data - like
your name, roll number, marks, to the height of Mt. Everest, world population etc.
Basically, anything that holds some raw information.
5.1 Types of data in Python
Data in Python can be one of the following 5 types:
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
1. Numbers
2. None
3. Sequences
4. Sets
5. Mappings
5.1.1 Numbers
Number is a data type that we have already dealt with in the previous lessons. We
used them with mathematical operators, in functions, with variables, and in input-
output tutorial as well, we guess everywhere till now, and that's what make them
crucial. As you might have noticed at a few places in the previous tutorials, we have
mentioned about Integers and Floating point numbers, well this is where we'll learn
the difference between them. Numbers are further divided into three more types:
5.1.1.1 Integers and Boolean
This set comprises of all the Integers like 1, 2, 3,..., 0, -1, -2, -3,... and Boolean values
(the one that computer understands) which are true or false (1 or 0 respectively).
5.1.1.2 Floating Point Numbers
This set deals with the numbers having decimal point values (or any real number).
For example, 1.2, 4.76832, 8.0 are all floating point numbers.
5.1.1.3 Complex Numbers
Yes, unlike any other programming language, there is a data type for complex
numbers in Python. Type either 1+2j or 1+2J in IDLE and it won't return any error
because it's a perfectly valid complex number in python language. We know,
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
traditionally we have been using iota (or i) for representing complex numbers but
python opted for j instead i. Which is totally fine. Who are we to judge?
5.1.2 None
Think of a scenario where you don't want the variable to have any value. What will
do? You can't use 0 because it's a number after all. That is where None comes into
picture. Just put:
>>> x = None
And x will have no value.
5.1.3 Sequence
A Sequence is an ordered collection of items, indexed by positive integers. It is a
combination of mutable (a mutable variable is one, whose value can be changed)
and immutable (an immutable variable is one, whose value can not be changed)
data types. There are three types of sequence data type available in Python, they are:
Strings
Lists
Tuples
5.1.3.1 String
It is an ordered sequence of letters/characters. They are enclosed in single quotes
(' ') or double quotes (" "). The quotes surrounding the string are not part of the
string. They only inform the compiler about where the string begins and ends. They
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
can have any character or sign, including space in them. These are immutable. A
string with length 1 represents a character in python. You know we have used
strings on several occasions in earlier tutorials. Basically, they help us to store and
implement literature words in Python. For
example, "Saharsh", 'Saharsh', "123", '123' are all strings.
5.1.3.2 Lists
It is also a sequence of values of any type. Values in the list are
called elements/items. Lists are mutable and indexed/ordered. The list is
enclosed in square brackets [ ]. For example, [2, 6, 8, 3, 1] or ["Python", "Java",
"C++"] are both lists. You can notice that it's no different from the list we use in our
daily life. A List is just a bunch of numbers or strings that are kept together inside
the square bracket, sequentially. Each element of the list can be accessed by using
it's index number.
5.1.3.3 Tuples
They are a sequence of values of any type and are indexed by integers. Tuples are
enclosed in curved brackets i.e., (). Tuples are also pretty much like Lists, except that
they are immutable, hence once we assign it some value, we cannot change it later.
At the same time, it is faster in implementationthan List.
5.1.4 Sets
Set is an unordered collection of values of any type with no duplicate entry. It
is immutable (their values can't be changed later; try to keep that definition in
mind).
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
5.1.5 Mapping
This data type is unordered and mutable. Dictionaries fall under Mappings.
Dictionaries
Dictionaries pretty much like our dictionary can store any number of python objects.
What they store is a key-value pair, which is accessed using the key. Dictionary is
enclosed in curly brackets { }.
5.2 String in Python
This isn't the first time that we are encountering Strings since we have started learning
python. In many of the previous tutorials we have used strings in examples or discussed
about it, so it shouldn't be an ambush for you. Nonetheless, this chapter will give you
more insight about how they can be used, manipulated and implemented in python
world. We will also checkout some handy string functions to manipulate string. So,
without wasting time let's jump right into it.
5.2.1 What is a String?
String can be defined as a sequence of characters, and that's the most basic
explanation of string that you can provide. In this definition, we can see two important
terms, first being sequence and other is characters. What is Sequence data type and
how Strings are a type of sequence. Just for revision, in python, Sequence is a data type
which is made up of several elements of same type, i.e., integers, float, characters,
strings etc.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Note: There is a unique code provided to all existing characters. The coding convention
had been labelled as Unicode format. It consists of characters of almost every possible
languages and in fact emoticons too (yes, emoticons had been declared as characters too).
Hence, strings can be considered as a special type of sequence, where all its elements
are characters. For example, string "Hello, World" is basically a sequence ['H', 'e', 'l', 'l',
'o', ',', ' ', 'W', 'o', 'r', 'l', 'd'] and its length can be calculated by counting number of
characters inside the sequence, which is 12.
Note: Yes, space, comma everything inside those quotes will be a character if the length is
1.
Generally in programming languages there is a different data type dedicated to
characters only, while in Python, there is no character data type. Instead characters are
just treated as a string of length 1.
5.2.2 Declaration of Strings
>>> mystring = "This is not my first String"
>>> print mystring
This is not my first String
Live Example →
You can access each individual character of a string too. Just like accessing each element
of a Sequence, we can use index numbers for this purpose. To access first character
of mystring, we can do following:
>>> print mystring[0]
T
Since T is the first character of our string This is not my first String, hence it will have
index number as 0 (zero). Similarly, for further characters we can use index 1, 2, 3 and
so on, i.e., in order to access ith element we will have to use (i-1)th index.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
There is another trick to access elements of the sequence from its end. For example, if
you want to access the last element of the sequence just do the following:
>>> print mystring[-1]
Writing -1 in the index will imply that you are asking for the 1st element from the last.
Similarly, in order to access 2nd last element use -2 as index, for 3rd last use -3 and so
on, i.e., for ith element from the last use -ith as the index. So that settles the
generalization for accessing each character from both forward and backward side in a
string. Note that positive index number implies you are accessing character from the
forward side, while negative index number means you're accessing it from the rear end.
We can conclude the what we have covered till now in a simple table. Consider a
string PYTHON. For this each character can be accessed in two ways - from the front, or
from the rear end.
Characters P Y T H O N
Forward Index 0 1 2 3 4 5
Backward Index -6 -5 -4 -3 -2 -1
5.2.3 Escape Sequence
Suppose you want a string to store a quote by Mahatma Gandhi.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
"You must be the change you wish to see in the world" - Gandhi
This is the exact line you want to display in the console. And you also wish to have the
quotes surrounding this sentence. As you go ahead and print the statement, you will see
that it isn't that simple.
Python will instantly return a syntax error. This is because of those extra double quotes
that we added. In above image you can notice that Gandhi's quoted text is in black
colour, while "- Gandhi" is in green. Also, if you have used IDLE enough you might know
that all the characters inside the string are highlighted in green in the IDLE (it can be
other colours too depending upon text editor, python version, OS etc). This clearly
means that Python isn't treating You must be the change you wish to see in the world part
of the sentence as a string. Therefore, this concludes that whenever we open a quote
and close it, to declare a string, whatever we write after the closing quote, is just
considered as some python keyword.
Like for the above quotation text, we started the string with two double quotes and
wrote You must be the change you wish to see in the world just next to it, since
double quote was already closed before this phrase, hence Python considered the entire
sentence as some non-understandable python keywords. After the phrase, another
double quote started, then came - Gandhi after that and finally the closing double quote,
since - Gandhi part is within a pair of double quotes hence its totally legitimate.
Now you understand the problem that we can face if we use uneven number of double
quotes. Now let's see how we can actually have a quote in a string. Well, there are two
ways to do so:
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
1. First one is a bit compromising. You can use single quotes inside of double quotes,
like:
>>> print "'You must be the change you wish to see in the world' - Gandhi"
‘You must be the change you wish to see in the world' - Gandhi
Hence, it's legitimate to use single quote inside double quotes, however, reverse is
not true, i.e.,
>>> '"You must be the change you wish to see in the world" - Gandhi'
Will give an error.
2. Second one is for those who hate to compromise, or just want to use the double
quotes. For you people, there is something called escape sequence or literally
speaking, a back-slash\. You can use it like:
>>> print "\"You must be the change you wish to see in the world\" – Gandhi"
Can you guess what happened? We used backslash or escape sequence at two
places, just before the quotes which we directly want to print. If you want to inform
the compiler to simply print whatever you type and not try to compile it, just add an
escape sequence before it. Also remember, you must use one escape sequence for
one character. For example, in order to print 5 double quotes, we will have to use 5
backslashes, one before each quote, like this:
>>> print "\"\"\"\"\""
5.2.4 Operations on String
String handling in python probably requires least efforts. Since in python, string
operations have very low complexity compared to other languages. Let's see how we
can play around with strings.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
1. Concatenation: No, wait! what? This word may sound a bit complex for absolute
beginners but all it means is - to join two strings. Like to join "Hello" with "World",
to make it "HelloWorld". Yes, that's it.
>>> print "Hello" + "World"
HelloWorld
Yes. A plus sign + is enought to do the trick. When used with strings, the + sign joins
the two strings. Let's have one more example:
>>> s1 = "Name Python "
>>> s2 = "had been adapted "
>>> s3 = "from Monty Python"
>>> print s1 + s2 + s3
Name Python had been adapted from Monty Python
Live Example →
2. Repetition: Suppose we want to write same text multiple times on console. Like
repeat "Hi!" a 100 times. Now one option is to write it all manually,
like "Hi!Hi!Hi!..." hundred times or just do the following:
>>> print "Hi!"*100
Suppose, you want the user to input some number n and based on that you want a
text to be printed on console n times, how can you do it? It's simple. Just create a
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
variable n and use input() function to get a number from the user and then just
multiply the text with n.
>>> n = input("Number of times you want the text to repeat: ")
Number of times you want the text to repeat: 5
>>> print "Text"*n
TextTextTextTextText
3. Check existence of a character or a sub-string in a string: The keyword in is
used for this. For example: If there is a text India won the match and you want to
check if won exist in it or not. Go to IDLE and try the following:
>>> "won" in "India won the match"
True
Amongst other datatypes in python, there is Boolean datatype which can have one
of the possible two values, i.e., either true or false. Since we are checking if
something exists in a string or not, hence, the possible outcomes to this will either
be Yes, it exists or No, it doesn't, therefore either True or False is returned. This
should also give you an idea about where to use Boolean datatype while writing
programs.
Go ahead, try out some more examples of the in keyword, where you can take any
string and substring or character as input one by one from the user and then
print true or false using the in keyword.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
4. not in keyword: This is just the opposite of the in keyword. You're pretty smart if
you guessed that right. Its implementation is also pretty similar to the in keyword.
>>> "won" not in "India won the match"
False
You can see all the above String operations live in action, by clicking on the below Live
example button. Also, we suggest you to practice using the live compiler and try
changing the code and run it.
Live Example →
5.2.4 Converting String to Int or Float datatype
and vice versa
This is a very common doubt amongst beginners as a number when enclosed in quotes
becomes a string in python and then if you will try to perform mathematical operations
on it, you will get error.
numStr = '123'
In the statement above 123 is not a number, but a string.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Hence, in such situation, to convert a numeric string into float or int datatype, we can
use float() and int() functions.
numStr = '123'
numFloat = float(numStr)
numInt = int(numFloat)
Live Example →
And then you can easily perform mathematical functions on the numeric value.
Similarly, to convert an int or float variable to string, we can use the str() function.
num = 123
# so simple
numStr = str(num)
5.2.5 Slicing
Slicing is yet another string operation. Slicing lets you extract a part of any string based
on a start index and an end index. For example, if we have a string This is Python
tutorial and we want to extract a part of this string or just a character, then we can use
slicing. First lets get familiar with its usage syntax:
string_name[starting_index : finishing_index : character_iterate]
String_name is the name of the variable holding the string.
starting_index is the index of the beginning character which you want in your sub-
string.
finishing_index is one more than the index of the last character that you want in
your substring.
character_iterate: To understand this, let us consider that we have a string Hello
Brother!, and we want to use the slicing operation on this string to extract a sub-
string. This is our code:
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
>>> str = "Hello Brother!"
>>> str[0:10:2]
Live Example →
Now str[0:10:2] means, we want to extract a substring starting from the
index 0 (beginning of the string), to the index value 10, and the last parameter
means, that we want every second character, starting from the starting index. Hence
in the output we will get, HloBo.
H is at index 0, then leaving e, the second character from H will be printed, which
is l, then skipping the second l, the second character from the first l is printed, which
is o and so on.
It will be more clear with a few more examples:
Let's take a string with 10 characters, ABCDEFGHIJ. The index number will begin
from 0 and end at 9.
A B C D E F G H I J
0 1 2 3 4 5 6 7 8 9
Now try the following command:
>>> print s[0:5:1]
Here slicing will be done from 0th character to the 4th character (5-1) by
iterating 1 character in each jump.
Now, remove the last number and the colon and just write this.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
>>> print s[0:5]
You'll see that output are both same.
You can practice by changing the values. Also try changing the value of the character
iterate variable to some value n, then it will print every nth character from starting
index to the final index.
5.2.6 Built-in String Functions in Python
For the final portion, we will see some really useful string functions to work with strings
in python. Below we have mentioned a few useful string functions.
5.2.6.1 len(string)
len or length function is used to find the character length of any string. len returns a
number and it takes a string as an argument. For Example,
>>> s = "Hello"
>>> len(s)
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
5
5.2.6.2 find(subString)
In case you want to find the position of any character or of a subString within any given
string, you can use the find function. It's implementation is a little different than a
normal function but it's not tough to understand. Obviously to find a subString in a
string, we will have to provide both the main string and the subString to be found, to the
funtion. For Example,
>>> s = "Hello"
>>> ss = "He"
>>> print s.find(ss)
0
Since, He is present at the beginning of the string Hello, hence index 0 is returned as the
result. It can be directly implemented/used as follows(in case you hate useless typing;
which every programmer do):
>>> print "Hello".find("He")
0
5.2.6.3 string_name.lower()
lower() function is used to convert all the uppercase characters present in a string into
lowercase. It takes a string as the function input, however the string is not passed as
argument. This function returns a string as well.
>>> print "Hello, World".lower()
hello, world
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
5.2.6.4 string_name.upper()
upper() is used to turn all the characters in a string to uppercase.
>>> print "Hello, World".upper()
HELLO, WORLD
5.2.6.5 string_name.islower()
islower() is used to check if string_name string is in lowercase or not. This functions
returns a boolean value as result, either True or False.
>>> print "hello, world".islower()
True
>>> print "Hello, World".islower()
False
5.2.6.6 string_name.isupper()
isupper() is used to check if the given string is in uppercase or not. This function also
returns a boolean value as result, either True or False.
>>> print "HELLO, WORLD".isupper()
True
>>> print "Hello, World".isupper()
False
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
5.2.6.7 string_name.replace(old_string, new_string)
replace() function will first of all take a string as input, and ask for some subString
within it as the first argument and ask for another string to replace that subString as the
second argument. For Example,
>>> print "Hello, World".replace("World", "India")
Hello, India
5.2.6.8 string_name.split(character, integer)
Suppose you're having a string say,
>>> mystring = "Hello World! Welcome to the Python tutorial"
Now we can use the split() function to split the above declared string.
If we choose to split the string into two substring from the exclamation mark !. We can
do that by putting an exclamation mark ! in the character argument. It will basically split
the string into different parts depending upon the number of exclamation marks ! in the
string. All the sub-pieces of the string will be stored in a list. Like,
>>> print mystring.split("!")
['Hello World', ' Welcome to the Python tutorial']
You can store these values to another variable and access each element of it like this:
>>> myNEWstring = mystring.split("!")
>>> print myNEWstring[0]
>>> print myNEWstring[1]
Hello World
Welcome to the Python tutorial
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
In the example below we have broken the string into 2 subStrings from a full stop !
Chapter 6 Lists in Python
In the last section, we discussed about strings and the various properties and
functions of strings, like how it can be thought of as a collection of various characters
just like a list. In other words, the list is an ordered set of values enclosed in square
brackets [ ].
An important difference to be noted is that list is mutable, i.e. it's values can be
modified.
As it is nothing but a set of values, we can use the index in square brackets [ ] to
identify an value belonging to the list.
The values that make up a list are called its elements, and they can be of any type.
We can also say that list data type is a container that holds a number of elements in a
given order. For accessing an element in the list, indexing is used, which can be
called from both forward and backward direction (similar to strings).
6.1 Constructing a List
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
As already explained, the list is a collection of similar type of data. This data can be
an integer, a float, a complex number, a string or any legitimate datatype in
python. The list is always provided with some name, similar to a variable, and each
element is accessed by their index number. Python has both forward and backwards
index number, so for each element there exists one positive and one negative
number to access that element (discussed in the next topic). While defining a list, we
have to enclose each element of the list within square brackets, and each element is
separated by commas.
Suppose, if you want to create an empty list (which is possible in case you want to
add the elements later in the program or when user gives the input), then you can
initialize it by declaring empty square brackets,
>>> myEmptyList = []
For example, list of some integers will be,
>>> myIntegerList = [9, 4, 3, 2, 8]
A list of float values,
>>> myFloatList = [2.0, 9.1, 5.9, 8.123432]
A list of characters,
>>> myCharList = ['p', 'y', 't', 'h', 'o', 'n']
A list of strings,
>>> myStringList = ["Hello", "Python", "Ok done!"]
Live Example →
These were some basic methods to create a list. Now let's try some other methods.
6.2 Deriving from another List
Suppose there is an existing list,
>>> myList1 = ['first', 'second', 'third', 'fourth', 'fifth']
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
And now you want to create a new list which consists some or all the elements
of myList1, then you can you do a direct assignment for complete copying of
elements or use slicing, and take only some elements.
For complete copying,
>>> myList2 = myList1
Use slicing, for copying only the first three elements,
>>> myList2 = myList1[0:3]
Live Example →
For copying last three elements,
>>> myList2 = myList1[-4:-1]
6.3 Adding Serial Numbers in a List
Suppose you want to add serial whole numbers (i.e., 0, 1, 2, 3, ...) into your list and
just don't want to write all of them one by one, do not worry, there is a shortcut for
doing this.
For storing 0 to (n-1) numbers in a list use range(n) function.
>>> myList1 = range(9)
This will create a list with numbers 0 to 8 inside it.
>>> myList1 = range(5, 9)
Live Example →
This will create a list having numbers 5, 6, 7, 8 i.e., argument's first number to
the (argument's last number - 1).
This range() function can be used for various usecases.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Suppose you want to create a list with squares of all whole numbers. Although there
exists various programming approaches for this problem but here is a one line
method in python. We will be introducing something new, so it can get a little tricky.
>>> myQuickList = [x**2 for x in range(5)]
The final list will contain elements like [0, 1, 4, 9, 16], i.e. x**2 where x is varying
from 0 to (5-1).
for is the keyword here that you may not be familiar with. for is one of the keywords
that makes programming do a lot of mundane and redundant task for a programmer,
for example, it can create loops of execution. Although there will be a whole chapter
dedicated to this, the important thing to note here is that for is the keyword which is
responsible for iterating (or repeating) x in range 0 to 4 and finally storing the
iterated value's square i.e. (x2) in the list.
6.4 Appending to a List
Appending basically means adding to the existing. If you remember we told you
how you can create an empty list in python by just declaring an empty square
bracket. Now, what to do when you actually have to insert some elements inside the
list? This is where append function comes in use. You can add any number of
elements to the end of the list in one line without any hassle.
>>> emptyList = []
>>> emptyList.append('The Big Bang Theory')
>>> emptyList.append('F.R.I.E.N.D.S')
>>> emptyList.append('How I Met Your Mother')
>>> emptyList.append('Seinfeld')
Live Example →
So, that will basically create a list of some of the best sitcoms (and isn't empty
anymore). If you print the list.
>>>print emptyList
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
['The Big Bang Theory', 'F.R.I.E.N.D.S', 'How I Met Your Mother', 'Seinfeld']
6.5 Indexing of elements
We have already covered about using index to access the sequence of characters in a
string. Similarly, in python, index numbers can be used to access the elements of a
list too. Let's create a list of strings and try to access individual strings using index
numbers. Here is an example,
>>> fruitsList = ["Orange", "Mango", "Banana", "Cherry", "Blackberry", "Avocado", "Apple"]
As you can see in the code above, we have a list with 7 elements. To find the number
of elements in a list, us the function len just like for strings.
>>> len(fruitsList)
7
Live Example →
For every element in the list, following are the index numbers that we should use:
(try to understand how we assigned the index numbers.)
Element Forward index Backward index
Orange 0 -7
Mango 1 -6
Banana 2 -5
Cherry 3 -4
Blackberry 4 -3
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Avocado 5 -2
Apple 6 -1
6.6 Utilising list elements in Python
Till now, we have created a list and accessed individual elements of that list, now its time
to learn how to use all of the elements in a list by iterating over them, using loops.
When you have a list with hundred or a thousand elements, and you want to access a
few of them or all of them to perform some operation or calculation on them, it would
be very hectic to use index numbers to access all the elements. In such cases, we use an
iterative method, to iterate over all the list items. To understand how to iterate over list
elements, we will be using loops. Don't worry loops will be covered in details in the next
chapter.
Chapter 7 Introduction to Loops
Loops are used for doing redundant and repetitive tasks.
7.1 Using for loop
Let's start with for loop. For iterating over a list, a for loop will need two things - First, a
reference variable to store the element being iterated and second, a source (list or
a range(), as in the previous case). When a for loop executes, elements of the source are
one by one copied to the reference variable for utilizing(performing operations) them
inside the loop. For example,
for x in range(0,5):
print x
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
0
1
2
3
4
In the above case, x is our reference variable in which, each element in the range(0, 5) is
getting stored, iteratively(one by one), simple enough.
Also, you must know that range(0, 5) returns a list with elements 0 to 4 in it.
7.2 Using while loop
Another way of iterating is by using the while loop. The while loop requires one
condition to function. The loop keeps on iterating till that condition is true. As soon as it
becomes false, the loops get terminated. For example,
i = 0
while i < 5:
print i
i = i+1
0
1
2
3
4
You can see that both the loops returned the same output, but the while loop, used the
condition i < 5 in order to get the output. In simple english, it implies that "while i is less
than 5, keep printing i and keep incrementing the value of i". Do you know why we
increment the value of i, everytime after printing its value? Well, it's because if we
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
hadn't incremented its value, the value would have remained the same as it was
declared initially, which is, i = 0, and the condition i < 5, would have always
been true and hence the loop would have never ended. Such condition leads to
something that we call an infinite loop.
7.3 Using Loops with List
Enough about loops, now let's see how we can use them to access the List elements.
Take a list with any type of element. Now, using the for loop we can access each element
of the list very easily. For accessing the elements, we have to use a reference
variable and our list variable as source.
myList = ['Last Of Us', 'Doom', 'Dota', 'Halo', ' ']
for x in myList:
print x
Last Of Us
Doom
Dota
Halo
7.4 Iterate two Lists simultaneously -
zip() method
Suppose there are two lists and you want to ADD each element of the first list serially to
each element of the second list and save it to a third (empty) list.
We can achieve this by executing a while loop like shown in below code, but this is not
the right way.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
i = 0
A = [1, 2, 3, 4]
B = [5, 6, 7, 8]
C = []
while i < len(A):
C.append(A[i]+B[i])
i=i+1
In the above code, we will have to add a lot of conditions to make sure that it runs
without error all the time. For example, What if the size of both the list is not same?
We will have to do something different in such case because we have to iterate over the
elements of two different lists, together. This can be done using the function zip().
Suppose the two lists are,
>>> A = [9, 8, 7, 6, 5]
>>> B = [3, 4, 5, 6, 7]
Then, let's create an empty list to save the results.
>>> C = []
Then the iteration process will require two reference variables, one for each list.
for x, y in zip(A, B):
C.append(x+y)
zip() function can accept any number of list arguments. In this case, we have passed two
lists A and B. Since both A and B have 5 elements, hence zip() will make the loop iterate
5 times. But, what if both the lists have different number of elements? Suppose A
have n elements and B have melements, if m < n then zip() will make loop m times,
otherwise n times.
Another approach to this problem could have been using the index number of the list A
and B.
for i in range(0,5):
C.append(A[i]+B[i])
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Although while using this technique it is necessary to know the size of both the lists
prior to appending, while the previous approach (zip function) can be used in almost
any situation.
7.5 Deleting an element from a List
It may happen, that you might have to delete some elements from your list. Below we
have listed some methods to do the same:
7.5.1 pop( ) function:
This method requires the index number of the element that you want to delete. For
example, if you want to delete the 5th element of the list, then just do it like:
>>> myList.pop(4)
7.5.2 del keyword:
This also requires the index number.
>>> del myList[4]
This will delete the 5th element of the list. We can combine this with slicing to delete
sequence of elements together, like if we want to delete all elements from index 3 to 6,
then:
>>> del myList[3:7]
This will remove all elements from index 3 to 6.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
7.5.3 remove( ) function:
This function, instead of index number, requires the value that has to be deleted. For
example,
>>> myList = ['Apple', 'Orange', 'Apple', 'Guava']
>>> myList.remove('Apple')
This will remove the first 'Apple' element from the list. Other elements with value
'Apple' won't be deleted. i.e., our list will be:
>>> print myList
['Orange', 'Apple', 'Guava']
7.6 Convert a List to String
If you want to convert your list into a string to print it as output, you can do it easily.
7.6.1 Without using any loop
Here is the code, if you do not want to use for or while loop for coverting list to string.
mylist = ['butter', 'jam', 'curd']
myStr = ', '.join(mylist)
print myStr
butter, jam, curd
If you have a list of int values, then
mylist = [1, 11, 111]
myStr = str(mylist).strip('[]')
print myStr
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
1, 11, 11
7.6.2 Using for loop
If we have a list of int values,
mylist = [1, 11, 111]
myStr = ''.join(str(e) for e in mylist)
print myStr
1, 11, 11
7.7 More functions for Lists
7.7.1 . insert(int, item)
This function is used to insert values, anywhere in the list. The first argument of the list
takes the index where the items will be inserted and second is the value that has to be
inserted. For example,
>>> myList = ['Python', 'C++', 'Java', 'Ruby', 'Perl']
>>> myList.insert(1, 'JavaScript')
>>> print myList
['Python', 'JavaScript', 'C++', 'Java', 'Ruby', 'Perl']
Notice how the value 'JavaScript' got inserted at index the 1.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
7.7.2. reverse()
As obvious by the name, it is used to reverse the order of the elements in the list.
>>> myList.reverse()
7.7.3. sort()
One of the most important functions in real life applications is sort(). Sorting arranges
all the elements of the List in ascending or descending order.
>>> myList.sort()
If the list consists of numbers then this will make the sequence in ascending order, if the
list consists of strings then the elements will be sorted in lexicographic ascending order.
What if you want to sort in descending order?
>>> myList.sort().reverse()
This will first sort the elements in ascending order and then we have used
the reverse() function to reverse the list.
Chapter 8 Dictionaries in Python
In this chapter, we will learn what a Dictionary is? How it can be used? and some
useful functions used for manipulating Dictionary.
Dictionaries are much like lists with an extra parameter called keys. Recall, how in
lists and strings, we used the index as the parameter to access each element of the
string/list. The main differentiating factor between a list and a dictionary would be,
that instead of the index we use keys to access the elements of a dictionary (or
values to access keys, works both ways).
Also, unlike an index, keys can be of any data type varying from integer to string.
This makes them more flexible to use.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
8.1 Creating a Dictionary
Since we have flexibility in providing the key for each element in the dictionary, we
will have to define each key explicitly. Below we have a dictionary in tabular format.
For each element in the dictionary we have a key linked to it.
Key Value
Key-1 Element-1
Key-2 Element-2
Key-3 Element-3
Key-4 Element-4
Key-5 Element-5
A dictionary in python can be created as:
>>> myDictionary = {'Key-1': 'Element-1', 'Key-2': 'Element-2', 'Key-3': 'Element-3', 'Key-4': 'Element-4'}
Notice the curly braces that are used here, unlike square braces in the list. Here Key-
1, Key-2... are the keys for Element-1, Element-2... respectively. Therefore, if you
want to access any element of a dictionary, you should know the key for that
element. For example, to access element of Key-3, then just use,
>>> myDictionary['Key-3']
'Element-3'
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Also, in a dictionary, each element must have a unique key, since a key is used to
uniquely identity each element of the dictionary, however, the reverse is not true,
which means that elements can be repeated, but key must be unique.
8.1.1 Dictionary with integer keys:
>>> integerDictionary = {10: "C++", 20: "Java", 30: "Python", 40: "Ruby", 50: "C#", 60: "Perl"}
>>> integerDictionary[30]
"Python"
8.1.2 Dictionary with string as keys:
>>> identity = {"name": "StudyTonight", "type": "Educational", "link": "https://studytonight.com", "tag":
"Best place to learn"}
>>> print identity['name'] + ": " + identity['tag']
StudyTonight: Best place to learn
To create an empty dictionary, do the following:
>>> emptyList = {}
The above line of code successfully initialized an empty dictionary. We can easily
add elements to an empty dictionary after its initialization. Suppose you want to
add Delhi with key India to your dictionary, then do it like,
>>> emptyList["India"] = "Delhi"
And this element will get appended to the dictionary.
>>> emptyList
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
{"India": "Delhi"}
8.2 Accessing elements of a dictionary
Elements stored in a dictionary can be accessed just like lists in python, i.e, using
the for loop. However, while iterating over each element, we will get the key and not
the value of the element, therefore, to access the value of the element, we have to use
the key just like index, For example: myDictionary[key].
for i in myDictionary:
print "Key: " + i + " and Element: " + myDictionary[i]
Key: Key-1 and Element: Element-1
Key: Key-2 and Element: Element-2
Key: Key-3 and Element: Element-3
Key: Key-4 and Element: Element-4
Key: Key-5 and Element: Element-5
8.3 Deleting element(s) in a dictionary
Elements can be deleted using del keyword, which is similar to how its done in a list.
For example, considering our website details dictionary,
>>> identity = {"name": "StudyTonight", "type": "Educational", "link": "http://studytonight.com", "tag":
"Best place to learn"}
If we want to delete the link key and the value associated to it, then
>>> del identity["link"]
will delete that element.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
>>> identity
{"name": "StudyTonight", "type": "Educational", "field": "tag": "Best place to learn"}
8.4 Appending element(s) to a dictionary
Suppose you want to add an extra element to your already initialized list which has
elements, then, all you have to do is:
>>> identity["email": "[email protected]"]
And it will be added to the dictionary.
>>> identity
{"name": "StudyTonight", "type": "Educational",
"tag": "Best place to learn", "email": "[email protected]"}
8.5 Updating existing element(s) in a
dictionary
The update() function is used for merging two dictionaries into one. The common
values of both the lists get overwritten by the latter dictionary. For example, let's
assume that there is another dictionary containing the list of the available courses
on StudyTonight, along with the list used in the example above.
So now we have 2 lists - identity and courseAvail
>>> courseAvail = {"Java": "Full-course", "C/C++": "Full-course", "DBMS": "Full-course"}
Suppose we want to copy all elements of courseAvail to the list identity, then we just
have to do th following:
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
>>> identity.update(courseAvail)
Note: In this case dictionary identity will get updated, and there would be no effect
on dictionary courseAvail.
8.6 Dictionary Functions in Python
Let's check out some important functions that are quite helpful when we are playing
around with dictionaries in python.
8.6.1 len()
As you might have already guessed, it gives the number of elements stored in the
dictionary or you can say just the number of keys in it.
>>> len(myDictionary)
5
8.6.2 clear()
If we ever need to delete all elements of the dictionary using the del keyword, for
each key value, that would be quite troublesome. Hence clear() function makes
emptying a dictionary, a single line task.
>>> myDictionary.clear()
>>> myDictionary
{}
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
8.6.3 values()
Suppose you don't want to access the keys while displaying the value stored in the
dictionaries, then values() function can be used. This function will show all the values
stored in the dictionary.
>>> myDictionary.values()
{"Element-1", "Element-2", "Element-3", "Element-4", "Element-5"}
8.6.4 keys()
This function is opposite to the function values(). As the name suggests, in case you
want to view only the keys for a dictionary, then you can use the keys() function.
>>> myDictionary.keys()
{"Key-1", "Key-2", "Key-3", "Key-4", "Key-5"}
8.6.5 items()
In case you want to display both, keys and values with a representation, where both
are well mapped, then use the items() method.
>>> myDictionary.items()
{('Key-1': 'Element-1'), ('Key-2': 'Element-2'), ('Key-3': 'Element-3'),
('Key-4': 'Element-4'), ('Key-5': 'Element-5')}
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
8.6.6 has_key()
To check if a particular key exists in the dictionary, this function can be used. If
the key that you are looking for exists then it returns True, otherwise False.
>>> myDictionary.has_key("Key-2")
True
>>> myDictionary.has_key("Key-6")
False
8.6.7 cmp():
In case you ever need to compare two dictionaries, cmp() function can be used to do
so. It can return 3 possible values, i.e., 1, 0 or -1. If both dictionaries are equal, then 0.
If second have greater elements than first, then -1 and 1 for the reverse. It can be
used like
>>> x = {1: 1, 2:2, 3:3}
>>> y = {1:1, 2:2, 3:3}
>>> cmp(x, y)
0
Since both are same, hence the output is 0.
Now let's add one an extra element to x.
>>> x[4] = 4
>>> cmp(x, y)
1
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Now that x is having more elements, hence the output is 1. Also, if we
compare y with x, then
>>> cmp(y, x)
-1
The output becomes -1, because y has less elements.
Chapter 9 Tuples in Python
Tuples are a lot like lists, and that's why we can define them in a pretty similar way
as we did to define the lists. Simply put, a tuple is a sequence of data.
What makes them different from lists is that tuples are immutable, i.e., the data
inside the tuples can't be modified, which is opposite in the case of lists. Other than
this, tuples are very similar to lists and that would make it much easier for us to
understand as we already know about lists.
9.1 Defining a Tuple
To define a tuple, we just have to assign a single variable with multiple values
separated by commas, and that variable will be known as a Tuple.
>>> myTuple = 1, 2, 3, 4
If you try to print it in IDLE,
>>> print myTuple
(1, 2, 3, 4)
You can see in the above example, that myTuple variable is actually a collection of
integers 1, 2, 3 and 4. Also, note those circular brackets which appears while
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
printing, around the integers, these will actually help you to distinguish between
lists and tuples. Because in case of lists, we have square brackets around the list
elements.
You can obviously add data of different types in a single tuple,
>>> secondTuple = 1, 2, "python", 4
>>> print secondTuple
(1, 2, "python", 4)
An empty tuple can be created using the tuple() function or by just using an empty
bracket ().
>>> emptyTuple = ()
>>> anotherEmptyTuple = tuple()
The above statements will create tuples with no elements in it. And the compiler
would know that emptyTuple and anotherTuple are tuples, with no elements in them.
9.2 Indexing in Tuples
Indexing in tuples is also pretty similar to that in lists, the first element has
index zero, and it keeps on increasing for the next consecutive elements.
Also, backward indexing is also valid in tuples, i.e., the last element can be accessed
using the index -1 and the consecutive previous numbers by -2, -3and so on. Let's
take an example,
>>> example = "apple", "orange", "banana", "berry", "mango"
>>> example[0]
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
'apple'
In the table below we have marked the tuple elements for both forward and
backward indexing:
Value Forward Indexing Backward Indexing
apple 0 -5
orange 1 -4
banana 2 -3
berry 3 -2
mango 4 -1
9.3 Adding Elements to a Tuple
As we know, that tuples are immutable, hence the data stored in a tuple cannot be
edited, but it's definitely possible to add more data to a tuple. This can be done using
the addition operator. Suppose there is a tuple,
>>> t = (1, 2, 3, 4, 5)
In case you want to add another element, 7 to the tuple, then you can do it as
follows:
>>> t = t + (7,)
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
As you can see, we used the addition operator to add(7,) to the tuple t.
>>> print t
(1, 2, 3, 4, 5, 7)
Hence, we can add any kind of element to a tuple, using the + operator.
If we try to think, what else can we do with the + operator, we might realize that it
can be used to combine two tuples as well. For example:
>>> print (1, 2, 5, 8) + (2, 9, 4)
(1, 2, 5, 8, 2, 9, 4)
You can use a tuple(s) to create another tuple.
9.4 Deleting a Tuple
In order to delete a tuple, the del keyword is used. In order to delete a tuple
named myTuple(which we defined earlier), follow the example below:
>>> del myTuple
And myTuple will be deleted from the memory.
9.5 Slicing in Tuples
Slicing in tuples, works exactly the same like in the case of lists. Let's start with an
example:
>>> t = (1, 2, 3, 4)
>>> t[2:4]
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
(3, 4)
Here, t[2:4] means, slice the tuple starting from index 2 upto the index 4, and take
that slice out.
Slicing can be done backwards as well using the negative indexes for traversing the
tuple from backward direction.
9.6 Basic Operations and Functions
The various operations that we can perform on tuples are very similar to lists. In
fact, you just saw the + operator with tuples, it works with tuples just like it works
with a list. Some other operators for tuples include:
9.6.1. Multiplication
Multiplying a tuple by any integer, x will simply create another tuple with all the
elements from the first tuple being repeated x number of times. For
example, t*3 means, elements of tuple t will be repeated 3 times.
>>> t = (2, 5)
>>> print t*3
(2, 5, 2, 5, 2, 5)
9.6.2 Addition
Using the addition operator, with two or more tuples, adds up all the elements into a
new tuple. For example,
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
>>> t = (2, 5, 0) + (1, 3) + (4,)
>>> print t
(2, 5, 0, 1, 3, 4)
9.6.3 in keyword
in keyword, can not only be used with tuples, but also with strings and lists too. It is
used to check, if any element is present in the sequence or not. It returns True if the
element is found, otherwise False. For example,
>>> t = (1, 2, 3, 6, 7, 8)
>>> 2 in t
>>> 5 in t
True
False
9.6.4 len() function
As you might have already guessed, this function is used to get the number of
elements inside any tuple.
>>> t = 1, 2, 3
>>> print len(t)
3
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
9.6.5 cmp() function
This is used to compare two tuples. It will return either 1, 0 or -1, depending upon
whether the two tuples being compared are similar or not.
The cmp() function takes two tuples as arguments, where both of them are
compared. If T1 is the first tuple and T2 is the second tuple, then:
if T1 > T2, then cmp(T1, T2) returns 1
if T1 = T2, then cmp(T1, T2) returns 0
if T1 > T2, then cmp(T1, T2) returns -1
9.6.6 max() and min() function
To find the maximum value in a tuple, we can use the max() function, while for
finding the minimum value, min() function can be used.
>>> t = (1, 4, 2, 7, 3, 9)
>>> print max(t)
>>> print min(t)
9
1
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Chapter 10 Python Relational and
Logical Operators
Relation and Logic are the fundamental bricks of a program that defines its
functionality. With these fundamentals, you decide what should be the flow of
execution and what conditions should be kept to make sure the flow stays that way.
In every programming language including python, to manage the flow of any
program, conditions are required, and to define those conditions, relational and
logical operators are required.
Remember those days when your mathematics teacher in school used to ask you if 3
is greater than 2, say yes, otherwise no, that is pretty much what we do in
programming world too.
You provide the compiler with some condition based on an expression, compiler
computes the expression and executes the condition based on the output of the
expression. In the case of relational and logical expressions, the answer will always
be either True or False.
Operators are the conventional symbols, that bring one, two or more operands
together to form an expression. Operators and operands are two key deciding
factors of the output.
Now let's see some operators that are available in python language.
10.1 Python Relational Operator
Relational operators are used to establish some sort of relationship between the two
operands. Some of the relevant examples could be less than, greater than or equal
to operators. Python language is capable of understanding these types of operators
and accordingly return the output, which can be either True or False.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Let's checkout a few relational expressions. Open your IDLE and try this:
>>> 5 < 9
True
Since 5 is less than 9, thus the output returned is True.
The list of operators available includes:
1. Less than → used with <
2. Greater than → used with >
3. Equal to → used with ==
4. Not equal to → used with !=
5. Less than or equal to → used with <=
6. Greater than or equal to → used with >=
You can try each of the operators to practice with some numbers (or even strings).
>>> "abc" > "aaa"
>>> "abc" == "bcd"
True
False
10.2 Python Logical Operators
Logical operators, as the name suggests are used in logical expressions where
the operands are either True or False. The operands in a logical expression, can be
expressions which returns Trueor False upon evaluation. There are three basic types
of logical operators:
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
1. Logical AND: For AND operation the result is True if and only if both operands
are True. The keyword used for this operator is and.
2. Logical OR: For OR operation the result is True if either of the operands is True.
The keyword used for this operator is or.
3. Logical NOT: The result is True if the operand is False. The keyword used for this
operator is not.
Let's see a few examples:
>>> True and False
False
>>> not True
False
Now, we also know that the relational expressions return a Boolean value as their
output, therfore know we can combine relational and logical expressions to create
something more meaningful. For example,
>>> (2 < 3) and (2 < 5)
True
>>> (2 < 3) and (2 < 1)
False
Taking a bit more realistic programming example, consider you have a variable x as
input and you want to check if the user entered value is between some range, say 0
to 100, then:
>>> x = int(raw_input())
25
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
>>> (x > 0) or (x < 100)
True
Chapter 11 Conditional Statements
In the last chapter, we studied about the logical and relational expressions and tried
to understand their usage with help of various examples. We also saw examples
about how multiple relational expressions can be put together with the help of
logical operators to create meaningful logical expressions.
We also mentioned how these logical and relational expressions can be used to
control the flow of execution.
In this section, we will learn some more ways to control the flow of execution. In
programming, there are two ways to achieve this, and they are known
as conditional statements and looping.
In this tutorial, we will be discussing about the conditional statements, so let's begin.
11.1 Conditional Statements
There will be various situations while writing a program when you will have to take
care of different possible conditions that might arise while execution of the program.
In such situations, if conditions can be used.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
11.1.1 The if condition
Syntax for using the if keyword is as follows:
if [conditional expression]:
[statement(s) to execute]
if keyword and the conditional expression is ended with a colon. In [conditional
expression] some conditional expression is introduced that is supposed to return a
boolean value, i.e., True or False. If the resulting value is True then the [statement to
execute] is executed, which is mentioned below the if condition with
a tabspace(This indentation is very important).
Taking a real-life example, let's say in a savings bank account a user A, has Rs.1000.
The user A, visits the ATM to withdraw money from his savings account. Now the
program which handles the ATM transactions should be able to perform in every
situation, like the program should be aware of the user's bank account balance, and
should not allow the user to withdraw money more than the available balance in his
account. Also, the program must update the account balance once the user has
withdrawn money from the account, to keep the records updated. Let's write a small
piece of code to stop user from withdrawing money more than the available account
balance.
>>> savingAmt = 1000
>>> withdrawAmt = int(raw_input("Amount to Withdraw: "))
>>> if withdrawAmt > savingAmt:
print "Insufficient balance"
Amount to Withdraw: 2000
Insufficient balance
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
In the above program if the user enters any amount more than Rs. 1000, a message
is displayed on the screen saying "Insufficient Funds".
There are two more keywords that are optional, but can be accompanied
with if statements, the are:
else
elif (also known as else if)
11.1.2 The else condition
Talking about else, let's first see how it is used alongside the if statement.
if[conditional expression]:
[statement to execute]
else:
[alternate statement to execute]
Continuing with the bank account-ATM example, if you noticed in the program
above, we forgot to subtract the withdrawn amount from the savings account
balance. Since now we have an additional else condition to use, we can print a
warning with the message, "Insufficient balance" if the saving amount is less than
the withdraw amount, or else we can subtract the withdrawn amount from the
savings account amount to update the account balance. So the if condition written in
the previous example, will get an additional else block.
if withdrawAmt > savingAmt:
print "Insufficient balance"
else:
savingAmt = savingAmt - withdrawAmt
print "Account Balance:" + str(savingAmt)
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
And with the else block introduced, in case there is sufficient balance,
the withdrawAmt will be subtracted from the savingAmt and the updated account
balance will be displayed on screen.
With if and else, now we can diverge the flow of execution into two different
directions. In case of a savings account, there will be only two cases, you have
sufficient money or you don't, but what if we come across some situation where
there are more than two possibilities? In such cases, we use yet another statement
that is accompanied with the if and else statements, called elif (or else if in proper
English).
11.1.3 The elif condition
elif statement is added between if and else blocks.
if[condition #1]:
[statement #1]
elif[condition #2]:
[statement #2]
elif[condition #3]:
[statement #3]
else:
[statement when if and elif(s) are False]
With this, you can add as many elif blocks as you want depending upon the
possibilities that may arise.
Let's say you are given a time and you have to tell what phase of the day it is-
(morning, noon, afternoon, evening or night). You will have to check the given time
against multiple ranges of time within which each of the 5 phases lies. Therefore, the
following conditions:
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
1. Morning: 0600 to 1159
2. Noon: 1200
3. Afternoon: 1201 to 1700
4. Evening: 1701 to 2000
5. Night: 2000 to 0559
Below we have a simple program, using the if, elif and else conditional statements:
if (time >= 600) and (time < 1200):
print "Morning"
elif (time == 1200):
print "Noon"
elif (time > 1200) and (time <= 1700):
print "Afternoon"
elif (time > 1700) and (time <= 2000):
print "Evening"
elif ((time > 2000) and (time < 2400)) or ((time >= 0) and (time < 600)):
print "Night"
else:
print "Invalid time!"
Notice the logical operators that have been used in each condition in the program,
this example demonstrates how you will generally be using them with if-else
statements.
11.1.4 Nesting if-else statements
Simply put, nesting if else means that you will be writing if-else statements inside
another if-else statements. Syntactically,
if[condition #1]:
if[condition #1.1]:
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
[statement to exec if #1 and #1.1 are true]
else:
[statement to exec if #1 and #1.1 are false]
else:
[alternate statement to execute]
Needless to say you can write the same if-else block inside an else block too. Or in
fact you can add an elif condition, according to your needs. Although if you think
about it, nested if-else is actually an alternative to elif. And just like we created a
program which printed the phase of the day by checking the range of time, that can
be done without using elif as well, by nesting if and elseonly.
if (time >= 600) and (time < 1200):
print "Morning"
else:
if (time == 1200):
print "Noon"
else:
if (time > 1200) and (time <= 1700):
print "Afternoon"
else:
if (time > 1700) and (time <= 2000):
print "Evening"
else:
if ((time > 2000) and (time < 2400)) or ((time >= 0) and (time
< 600)):
print "Night"
else:
print "Invalid time!"
As you can see in the above program, all we did was, we started by adding a
condition to the ifblock, and then used another if-else block in its else block. And we
kept on doing the nesting until all the conditions were taken care of. This, however,
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
is a little tedious than using elif. However, that's not all it is about. Nesting is very
useful in various other situations, and in some cases, it's the only way forward.
Also, if you remember our first example while explaining the if statement, the
savings bank account example. There is actually a quicker way to do it, a one-line
way because, it's python. The following is the logic:
if (saving > withdraw) then saving = (saving - withdraw), else saving will remain as
it is and there will be no transaction.
>>> savingAmt = savingAmt - withdrawAmt if (savingAmt > withdrawAmt) else savingAmt
Chapter 12 Loops in Python
In this section, we will see how loops work in python. Looping is simply a functionality
that is commonly used in programming for achieving repetitive tasks. It can vary from
iterating each element of an array or strings, to modifying a whole database.
The thumb rule for using loops is:
If you're writing a similar piece of code, again and again, it's time to go for the loops.
Instead of doing,
>>> a = 1
>>> b = 2
>>> c = 3
>>> d = 4
and so on, do it like,
>>> a = []
>>> {run a loop in this line to store 1, 2, 3, 4 in list a}
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
In the second code snippet, we will be using a loop, where we will only have to write
whatever tedious task we have to achieve, only once, and then put it on a loop. With this,
we will be able to achieve an iterative flow for execution.
In python, there are two ways to achieve iterative flow:
1. Using the for loop
2. Using the while loop
12.1 The for loop
Let us first see what's the syntax,
for [ELEMENT] in [ITERATIVE-LIST]:
[statement to execute]
else:
[statement to execute when loop is over]
[else statement is completely optional]
for loop is frequently used to iterate elements of lists. Considering the above syntax, let's
say there is a list myList:
>>> myList = [8, 9, 2, 3, 4, 6]
If we want to iterate all the elements of the list myList using the for loop:
for i in myList:
print i
As we can see we are using a variable i, which represents every single element stored in
the list, one by one. Our loop will run as many times, as there are elements in the lists.
For example, in myList there are 6 elements, thus the above loop will run 6 times.
During the first iteration, the value of i will be 8, while in next it will be 9 and so on,
uptill 6, in the last iteration. Doing so, one can easily use these individual list element
values inside the loop, as in our case, we have printed them.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
Besides this, there is another way of doing it. If you can recall, our old traditional way of
accessing an element of the list by index - myList[i]. Although, in this case, we will be
using another function range() (or alternatively xrange() can also be
used). range() function has already been mentioned in the previous sections too. If you
can remember range() function can return you a list of numbers according to the
arguments that you provide. For example:
>>> range(5)
[0, 1, 2, 3, 4]
Or,
>>> range(5, 10)
[5, 6, 7, 8, 9]
Or,
>>> range(2, 12, 2)
[2, 4, 6, 8, 10]
xrange() function is also pretty much the same, although it's a little faster.
We can use range() function along with the for loop to iterate index number
from 0 to len(myList). It will be pretty much like:
for i in xrange(0, len(myList)):
print myList[i]
As you might have noticed, in this case, we will be iterating over a temporary list which
contains the index numbers of the actual list. This temporary list is generated
using xrange() function.
The else block in for loop
The else block with the for loop, is executed, once all the elements of the list are iterated
or there are no more elements left to iterate in the list. It'll be safe to say
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
that else statement is executed at the end of the loop. Although, as already mentioned in
the syntax, it's completely optional to use and in fact, it's not even frequently used.
Looking at some more complex examples, let's say there is a list of lists:
>>> bigList = [[1, 3, 6], [8, 2,], [0, 4, 7, 10], [1, 5, 2], [6]]
How do you think, we will be accessing each element of the list?
The answer is, using a loop within another loop. Since there are lists within a list, thus
the outer loop will help in accessing each list of the bigList, and inside that loop, for
every list element we will be using another loop.
for i in bigList:
for j in i:
print "Element of list within a list - ", j
Element of list within a list - 1
Element of list within a list - 3
Element of list within a list - 6
Element of list within a list - 8
Element of list within a list - 2
Element of list within a list - 0
Element of list within a list - 4
Element of list within a list - 7
Element of list within a list - 10
Element of list within a list - 1
Element of list within a list - 5
Element of list within a list - 2
Element of list within a list - 6
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
12.2 The while loop
It's time to learn about the while loop.
Syntax:
while [condition]:
[statement to execute]
else:
[statement to execute if condition is false]
[else statement is completely optional]
Again, in the while loop too, there is an else block, although it's optional and rarely used.
In the first statement, while loop sets a condition, then a statement, and the compiler
following the flow of execution, first checks the condition provided in the condition
block, if the condition holds True, then the statement is executed.
Once the statement is executed, the compiler checks the condition again, if
it's True again then the statement is again executed, otherwise the else block is executed
(if provided) or simply the flow control breaks out of the while loop (if else statement is
not mentioned).
Here is an example:
Caution: Don't try this example in IDE or IDLE or anywhere.
while True:
print "I am printing because the condition is True"
Since here we have set our condition to be True, hence the compiler will execute the
statement the first time. In next iteration, the condition will still be True again and thus
the statement will be executed again. This will keep on happening and as you might
have guessed there will be no end for this loop. Such kind of looping is called infinite
loop and should be avoided in programs.
Time for another example:
i = 0
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
while i < 5:
i=i+1
print "i =", i
In this case, in the first iteration condition i < 5 is checked, since 0 < 5, hence the
statement is executed. During execution, value of i is incremented by 1.
The for loop, is frequently used for iterating elements of a list, while loop on the other
hand, is capable of serving several purposes, and it can iterate a list too! The logic is
pretty much similar for accessing an element using indices. Run the loop
from 0 to len(myList) and simply access the elements. And, there will be no need of
using range() or xrange() function.
myList = [8, 9, 2, 3, 4, 6]
i = 0
while i < len(myList):
print myList[i]
i = i+1
Quickly going through the example for lists within a list:
bigList = [[1, 3, 6], [8, 2,], [0, 4, 7, 10], [1, 5, 2], [6]]
i = 0
j = 0
while i<len(bigList):
while j<len(bigList[i]):
print “Element of list within a list -”,bigList[i][j]
j=j+1
i=i+1
12.3 The continue keyword
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
continue keyword is used inside the loops for altering the loop execution.
Using continue inside the loop will skip the current statement execution, and it will
check the condition again. Suppose there is a string,
>>> name = "StudyTonight"
So let's have a quick example demonstrating use of continue keyword:
for i in name:
continue
print i
It will print nothing. Let's see why? In the first iteration, first element of the
list name will be picked, i.e. "S", the next statement inside the for loop is continue, thus as
soon as this keyword is found, the execution of rest of the for loop statements is skipped
and the flow gets back to the for loop starting to get the next element and check the
condition. Same steps are followed by the next element of our string, i.e., "t" and
the continue interrupts the flow again, and this will happen everytime the execution
flow reaches the continue keyqord.
So, now if we want to write a program with a loop which prints only
the lowercase letters of the string stored in the name variable, then, we can use
the continue keyword to skip those letters which are not lowercase.
for i in name:
if not i.islower():
continue
print i
if condition checks whether the element i is in lowercase, using islower() function. If it is
not in lowercase then the rest of the statements are simply skipped and
the print statement is never executed, although, if i is in lowercase then the if statement
returns False and continuestatement is not executed.
The continue keyword works in the exact same way for the while loop as well.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM
12.4 The break keyword
break keyword is used inside the loop to break out of the loop. Suppose while iterating
over the characters of the string stored in the variable name, you want to break out of it
as soon as the character "T" is encountered. This is how it can be done:
for i in name:
if i == "T":
break
print i
Now, as soon as the if condition gets the character "T", the compiler will execute
the breakstatement and flow of execution will get out of the loop.
FOURSTEPS TRAINING SOLUTIONS PVT LTD WWW.FOURSTEPSOLUTIONS.COM