Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Introduction

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 65

Python Introduction

Python is a general purpose, dynamic, high level and interpreted programming language. It
supports Object Oriented programming approach to develop applications. It is simple and easy to
learn and provides lots of high-level data structures.

Python is easy to learn yet powerful and versatile scripting language which makes it attractive
for Application Development.

Python's syntax and dynamic typing with its interpreted nature, makes it an ideal language for
scripting and rapid application development.

Python supports multiple programming pattern, including object oriented, imperative and
functional or procedural programming styles.

Python is not intended to work on special area such as web programming. That is why it is
known as multipurpose because it can be used with web, enterprise, 3D CAD etc.

We don't need to use data types to declare variable because it is dynamically typed so we can
write a=10 to assign an integer value in an integer variable.

Python makes the development and debugging fast because there is no compilation step included
in python development and edit-test-debug cycle is very fast.

Python 2 vs. Python 3


In most of the programming languages, whenever a new version releases, it supports the features
and syntax of the existing version of the language, therefore, it is easier for the projects built in
the language to switch in the newer version. However, in the case of python, the two versions
python 2 and python are very much different from each other.

The two differences which can be pointed out here is

1. Python 2 uses print as a statement and used as print "something" to print some string on
the console. On the other hand, Python 3 uses print as a function and used as
print("something") to print something on the console.
2. Python 2 uses the function raw_input() to accept the user's input. It returns the string
representing the value which has typed by the user. To convert it into the integer, we need
to use the int() function in python. On the other hand, Python 3 uses input() function
which automatically interpreted the type of input entered by the user. However, we can
cast this value to any type by using primitive functions (int(), str(), etc.).
3. In python 2, the implicit string type is ASCII whereas, in python 3, the implicit string
type is Unicode.
4. Python 3 doesn't contain the xrange() function of python 2. The xrange() is the variant of
range() function which returns a xrange object that works similar to Java iterator. The
range() returns a list for example the function range(0,3) contains 0, 1, 2.
5. There is also a small change made in Exception handling in python 3. It defines a
keyword as which is necessary to be used. We will discuss it in Exception handling
section of this tutorial.

Python Features

Python provides lots of features that are listed below.

1) Easy to Learn and Use

Python is easy to learn and use. It is developer-friendly and high level programming language.

2) Expressive Language

Python language is more expressive means that it is more understandable and readable.

3) Interpreted Language

Python is an interpreted language i.e. interpreter executes the code line by line at a time. This
makes debugging easy and thus suitable for beginners.

4) Cross-platform Language

Python can run equally on different platforms such as Windows, Linux, Unix and Macintosh etc.
So, we can say that Python is a portable language.

5) Free and Open Source

Python language is freely available at offical web address.The source-code is also available.
Therefore it is open source.

-
6) Object-Oriented Language

Python supports object oriented language and concepts of classes and objects come into
existence.

7) Extensible

It implies that other languages such as C/C++ can be used to compile the code and thus it can be
used further in our python code.

8) Large Standard Library

Python has a large and broad library and prvides rich set of module and functions for rapid
application development.

9) GUI Programming Support

Graphical user interfaces can be developed using Python.

10) Integrated

It can be easily integrated with languages like C, C++, JAVA etc.

Python History and Versions

 Python laid its foundation in the late 1980s.


 The implementation of Python was started in the December 1989 by Guido Van Rossum at CWI
in Netherland.

 In February 1991, van Rossum published the code (labeled version 0.9.0) to alt.sources.
 In 1994, Python 1.0 was released with new features like: lambda, map, filter, and reduce.
 Python 2.0 added new features like: list comprehensions, garbage collection system.
 On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify fundamental flaw of the language.
 ABC programming language is said to be the predecessor of Python language which was
capable of Exception Handling and interfacing with Amoeba Operating System.
 Python is influenced by following programming languages:

 ABC language.
 Modula-3

Python Applications

Python is known for its general purpose nature that makes it applicable in almost each domain of
software development. Python as a whole can be used in any sphere of development.

Here, we are specifing applications areas where python can be applied.

1) Web Applications

We can use Python to develop web applications. It provides libraries to handle internet protocols
such as HTML and XML, JSON, Email processing, request, beautifulSoup, Feedparser etc. It
also provides Frameworks such as Django, Pyramid, Flask etc to design and delelop web based
applications. Some important developments are: PythonWikiEngines, Pocoo,
PythonBlogSoftware etc.

2) Desktop GUI Applications

Python provides Tk GUI library to develop user interface in python based application. Some
other useful toolkits wxWidgets, Kivy, pyqt that are useable on several platforms. The Kivy is
popular for writing multitouch applications.

3) Software Development

Python is helpful for software development process. It works as a support language and can be
used for build control and management, testing etc.

4) Scientific and Numeric

Python is popular and widely used in scientific and numeric computing. Some useful library and
package are SciPy, Pandas, IPython etc. SciPy is group of packages of engineering, science and
mathematics.
5) Business Applications

Python is used to build Bussiness applications like ERP and e-commerce systems. Tryton is a
high level application platform.

6) Console Based Application

We can use Python to develop console based applications. For example: IPython.

7) Audio or Video based Applications

Python is awesome to perform multiple tasks and can be used to develop multimedia
applications. Some of real applications are: TimPlayer, cplay etc.

8) 3D CAD Applications

To create CAD application Fandango is a real application which provides full features of CAD.

9) Enterprise Applications

Python can be used to create applications which can be used within an Enterprise or an
Organization. Some real time applications are: OpenErp, Tryton, Picalo etc.

10) Applications for Images

Using Python several application can be developed for image. Applications developed are:
VPython, Gogh, imgSeek etc.

There are several such applications which can be developed using Python

How to Install Python (Environment Set-up)

In this section of the tutorial, we will discuss the installation of python on various operating
systems.

Installation on Windows
Visit the link https://www.python.org/downloads/ to download the latest release of Python. In
this process, we will install Python 3.6.7 on our Windows operating system.
Double-click the executable file which is downloaded; the following window will open. Select
Customize installation and proceed.
The following window shows all the optional features. All the features need to be installed and
are checked by default; we need to click next to continue.
The following window shows a list of advanced options. Check all the options which you want
to install and click next. Here, we must notice that the first check-box (install for all users) must
be checked.
Now, we are ready to install python-3.6.7. Let's install it.
Now, try to run python on the command prompt. Type the command python in case of python2
or python3 in case of python3. It will show an error as given in the below image. It is because
we haven't set the path.
To set the path of python, we need to the right click on "my computer" and go to Properties →
Advanced → Environment Variables.
Add the new path variable in the user variable section.
Type PATH as the variable name and set the path to the installation directory of the python
shown in the below image.
Now, the path is set, we are ready to run python on our local system. Restart CMD, and type
python again. It will open the python interpreter shell where we can execute the python
statements.

SETTING PATH IN PYTHON

Before starting working with Python, a specific path is to set.

 Your Python program and executable code can reside in any directory of your system, therefore
Operating System provides a specific search path that index the directories Operating System
should search for executable code.
 The Path is set in the Environment Variable of My Computer properties:
 To set path follow the steps:
Right click on My Computer ->Properties ->Advanced System setting ->Environment Variable -
>New

In Variable name write path and in Variable value copy path up to C://Python(i.e., path where
Python is installed). Click Ok ->Ok.

Path will be set for executing Python programs.

1. Right click on My Computer and click on properties.

2. Click on Advanced System settings

3. Click on Environment Variable tab.


4. Click on new tab of user variables.

5. Write path in variable name


6. Copy the path of Python folder

7. Paste path of Python in variable value.


8. Click on Ok button:

9. Click on Ok button:
irst Python Program

In this Section, we will discuss the basic syntax of python by using which, we will run a simple
program to print hello world on the console.

Python provides us the two ways to run a program:

 Using Interactive interpreter prompt


 Using a script file

Let's discuss each one of them in detail.

Using a script file


Interpreter prompt is good to run the individual statements of the code. However, we can not
write the code every-time on the terminal.

We need to write our code into a file which can be executed later. For this purpose, open an
editor like notepad, create a file named first.py (python used .py extension) and write the
following code in it.

1. Print ("hello world"); #here, we have used print() function to print the message on the con
sole.

To run this file named as first.py, we need to run the following command on the terminal.

$ python3 first.py

Hence, we get our output as the message Hello World ! is printed on the console.

Get Started with PyCharm


In our first program, we have used gedit on our CentOS as an editor. On Windows, we have an
alternative like notepad or notepad++ to edit the code. However, these editors are not used as
IDE for python since they are unable to show the syntax related suggestions.

JetBrains provides the most popular and a widely used cross-platform IDE PyCharm to run the
python programs.

PyCharm installation
As we have already stated, PyCharm is a cross-platform IDE, and hence it can be installed on a
variety of the operating systems. In this section of the tutorial, we will cover the installation
process of PyCharm on Windows, MacOS, CentOS, and Ubuntu.

Windows

Installing PyCharm on Windows is very simple. To install PyCharm on Windows operating


system, visit the link https://www.jetbrains.com/pycharm/download/download-
thanks.html?platform=windows to download the executable installer. Double click the installer
(.exe) file and install PyCharm by clicking next at each step.

How to execute python

To execute Python code, we can use any approach that are given below.

1) Interactive Mode
Python provides Interactive Shell to execute code immediatly and produce output instantly. To
get into this shell, write python in the command prompt and start working with Python.
Press Enter key and the Command Prompt will appear like:

Now we can execute our Python commands.


Eg:

2) Script Mode
Using Script Mode, we can write our Python code in a separate file of any editor in our
Operating System.
Save it by .py extension.

Now open Command prompt and execute it by :


NOTE: Path in the command prompt should be location of saved file.where you have saved your
file. In the above case file should be saved at desktop.

3) Using IDE (Integrated Development Environment)


We can execute our Python code using a Graphical User Interface (GUI).

All you need to do is:

Click on Start button -> All Programs -> Python -> IDLE(Python GUI)
We can use both Interactive as well as Script mode in IDE.

1) Using Interactive mode:

Execute our Python code on the Python prompt and it will display result simultaneously.
2) Using Script Mode:

i) Click on Start button -> All Programs -> Python -> IDLE(Python GUI)

ii) Python Shell will be opened. Now click on File -> New Window.

A new Editor will be opened. Write our Python code here.


Click on file -> save as

Run code by clicking on Run in the Menu bar.


Run -> Run Module

Result will be displayed on a new Python shell as:

Python Variables

Variable is a name which is used to refer memory location. Variable also known as identifier and
used to hold value.

In Python, we don't need to specify the type of variable because Python is a type infer language
and smart enough to get variable type.

Variable names can be a group of both letters and digits, but they have to begin with a letter or
an underscore.

It is recomended to use lowercase letters for variable name. Rahul and rahul both are two
different variables.

Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals used in the
program. The rules to name an identifier are given below.
 The first character of the variable must be an alphabet or underscore ( _ ).
 All the characters except the first character may be an alphabet of lower-case(a-z), upper-case
(A-Z), underscore or digit (0-9).
 Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
 Identifier name must not be similar to any keyword defined in the language.
 Identifier names are case sensitive for example my name, and MyName is not the same.
 Examples of valid identifiers : a123, _n, n_9, etc.
 Examples of invalid identifiers: 1a, n%4, n 9, etc.

Declaring Variable and Assigning Values


Python does not bound us to declare variable before using in the application. It allows us to
create variable at required time.

We don't need to declare explicitly variable in Python. When we assign any value to the variable
that variable is declared automatically.

The equal (=) operator is used to assign value to a variable.

Eg:

Output:

1. >>>
2. 10
3. ravi
4. 20000.67
5. >>>

Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement which is also
known as multiple assignment.

We can apply multiple assignments in two ways either by assigning a single value to multiple
variables or assigning multiple values to multiple variables. Lets see given examples.

1. Assigning single value to multiple variables

1. x=y=z=50
2. print iple
3. print y
4. print z
Output:

1. >>>
2. 50
3. 50
4. 50
5. >>>

2.Assigning multiple values to multiple variables:

Eg:

1. a,b,c=5,10,15
2. print a
3. print b
4. print c

Output:

1. >>>
2. 5
3. 10
4. 15
5. >>>

The values will be assigned in the order in which variables appears.

Basic Fundamentals:

This section contains the basic fundamentals of Python like :

i)Tokens and their types.

ii) Comments

a)Tokens:

 Tokens can be defined as a punctuator mark, reserved words and each individual word in a
statement.
 Token is the smallest unit inside the given program.

There are following tokens in Python:

 Keywords.
 Identifiers.
 Literals.
 Operators.
Tuples:

 Tuple is another form of collection where different type of data can be stored.
 It is similar to list where data is separated by commas. Only the difference is that list uses square
bracket and tuple uses parenthesis.
 Tuples are enclosed in parenthesis and cannot be changed.

Eg:

1. >>> tuple=('rahul',100,60.4,'deepak')
2. >>> tuple1=('sanjay',10)
3. >>> tuple
4. ('rahul', 100, 60.4, 'deepak')
5. >>> tuple[2:]
6. (60.4, 'deepak')
7. >>> tuple1[0]
8. 'sanjay'
9. >>> tuple+tuple1
10. ('rahul', 100, 60.4, 'deepak', 'sanjay', 10)
11. >>>

Dictionary:

 Dictionary is a collection which works on a key-value pair.


 It works like an associated array where no two keys can be same.
 Dictionaries are enclosed by curly braces ({}) and values can be retrieved by square
bracket([]).

Eg:

1. >>> dictionary={'name':'charlie','id':100,'dept':'it'}
2. >>> dictionary
3. {'dept': 'it', 'name': 'charlie', 'id': 100}
4. >>> dictionary.keys()
5. ['dept', 'name', 'id']
6. >>> dictionary.values()
7. ['it', 'charlie', 100]
8. >>>

Python Data Types

Variables can hold values of different data types. Python is a dynamically typed language hence
we need not define the type of the variable while declaring it. The interpreter implicitly binds the
value with its type.
Python enables us to check the type of the variable used in the program. Python provides us the
type() function which returns the type of the variable passed.

Consider the following example to define the values of different data types and checking its type.

1. A=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a));
5. print(type(b));
6. print(type(c));

Output:

<type 'int'>
<type 'str'>
<type 'float'>

Standard data types


A variable can hold different types of values. For example, a person?s name must be stored as a
string whereas its id must be stored as an integer.

Python provides various standard data types that define the storage method on each of them. The
data types defined in Python are given below.

1. Numbers
2. String
3. List
4. Tuple
5. Dictionary

In this section of the tutorial, we will give a brief introduction of the above data types. We will
discuss each one of them in detail later in this tutorial.

Numbers

Number stores numeric values. Python creates Number objects when a number is assigned to a
variable. For example;

1. a = 3 , b = 5 #a and b are number objects

Python supports 4 types of numeric data.

1. int (signed integers like 10, 2, 29, etc.)


2. long (long integers used for a higher range of values like 908090800L, -0x1929292L, etc.)
3. float (float is used to store floating point numbers like 1.9, 9.902, 15.2, etc.)
4. complex (complex numbers like 2.14j, 2.0 + 2.3j, etc.)

Python allows us to use a lower-case L to be used with long integers. However, we must always
use an upper-case L to avoid confusion.

A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and
imaginary parts respectively).

String

The string can be defined as the sequence of characters represented in the quotation marks. In
python, we can use single, double, or triple quotes to define a string.

String handling in python is a straightforward task since there are various inbuilt functions and
operators provided.

In the case of string handling, the operator + is used to concatenate two strings as the operation
"hello"+" python" returns "hello python".

The operator * is known as repetition operator as the operation "Python " *2 returns "Python
Python ".

The following example illustrates the string handling in python.

1. str1 = 'hello javatpoint' #string str1


2. str2 = ' how are you' #string str2
3. print (str1[0:2]) #printing first two character using slice operator
4. print (str1[4]) #printing 4th character of the string
5. print (str1*2) #printing the string twice
6. print (str1 + str2) #printing the concatenation of str1 and str2

Output:

he
o
hello javatpointhello javatpoint
hello javatpoint how are you

List
Lists are similar to arrays in C. However; the list can contain data of different types. The items stored in
the list are separated with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+) and
repetition operator (*) works with the list in the same way as they were working with the strings.

Consider the following example.

1. l = [1, "hi", "python", 2]


2. print (l[3:]);
3. print (l[0:2]);
4. print (l);
5. print (l + l);
6. print (l * 3);

Output:

[2]
[1, 'hi']
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]

Tuple

A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and enclosed
in parentheses ().

A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.

Let's see a simple example of the tuple.

1. t = ("hi", "python", 2)
2. print (t[1:]);
3. print (t[0:1]);
4. print (t);
5. print (t + t);
6. print (t * 3);
7. print (type(t))
8. t[2] = "hi";

Output:

('python', 2)
('hi',)
('hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2, 'hi', 'python', 2)
<type 'tuple'>
Traceback (most recent call last):
File "main.py", line 8, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

Dictionary

Dictionary is an ordered set of a key-value pair of items. It is like an associative array or a hash
table where each key stores a specific value. Key can hold any primitive data type whereas value
is an arbitrary Python object.

The items in the dictionary are separated with the comma and enclosed in the curly braces {}.

Consider the following example.

1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'};


2. print("1st name is "+d[1]);
3. print("2nd name is "+ d[4]);
4. print (d);
5. print (d.keys());
6. print (d.values());

Output:

1st name is Jimmy


2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
[1, 2, 3, 4]
['Jimmy', 'Alex', 'john', 'mike']

Python Keywords

Python Keywords are special reserved words which convey a special meaning to the
compiler/interpreter. Each keyword have a special meaning and a specific operation. These
keywords can't be used as variable. Following is the List of Python Keywords.

Fals Non
True and as
e e

clas contin
asset def break
s ue

final excep
else elif del
ly t
impor
global for if from
t

raise try or return pass

lamb
nonlocal in not is
da

Python Operators

The operator can be defined as a symbol which is responsible for a


particular operation between two operands. Operators are the pillars of a
program on which the logic is built in a particular programming language.
Python provides a variety of operators described as follows.

 Arithmetic operators
 Comparison operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

Arithmetic operators
Arithmetic operators are used to perform arithmetic operations between
two operands. It includes +(addition), - (subtraction), *(multiplication),
/(divide), %(reminder), //(floor division), and exponent (**).

Consider the following table for a detailed explanation of arithmetic


operators.

Operator Description

It is used to add two operands. For example, if a = 20, b = 10


+ (Addition)
=> a+b = 30
It is used to subtract the second operand from the first
operand. If the first operand is less than the second operand,
- (Subtraction)
the value result negative. For example, if a = 20, b = 10 => a ?
b = 10

It returns the quotient after dividing the first operand by the


/ (divide)
second operand. For example, if a = 20, b = 10 => a/b = 2

* It is used to multiply one operand with the other. For


(Multiplication) example, if a = 20, b = 10 => a * b = 200

It returns the reminder after dividing the first operand by the


% (reminder)
second operand. For example, if a = 20, b = 10 => a%b = 0

It is an exponent operator represented as it calculates the


** (Exponent)
first operand power to second operand.

// (Floor It gives the floor value of the quotient produced by dividing


division) the two operands.

Comparison operator
Comparison operators are used to comparing the value of the two
operands and returns boolean true or false accordingly. The comparison
operators are described in the following table.

Operator Description

If the value of two operands is equal, then the condition becomes


==
true.

If the value of two operands is not equal then the condition


!=
becomes true.

If the first operand is less than or equal to the second operand, then
<=
the condition becomes true.

If the first operand is greater than or equal to the second operand,


>=
then the condition becomes true.
If the value of two operands is not equal, then the condition
<>
becomes true.

If the first operand is greater than the second operand, then the
>
condition becomes true.

If the first operand is less than the second operand, then the
<
condition becomes true.

Python assignment operators


The assignment operators are used to assign the value of the right
expression to the left operand. The assignment operators are described in
the following table.

Operator Description

= It assigns the the value of the right expression to the left operand.

It increases the value of the left operand by the value of the right
operand and assign the modified value back to left operand. For
+=
example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and
therefore, a = 30.

It decreases the value of the left operand by the value of the right
operand and assign the modified value back to left operand. For
-=
example, if a = 20, b = 10 => a- = b will be equal to a = a- b and
therefore, a = 10.

It multiplies the value of the left operand by the value of the right
operand and assign the modified value back to left operand. For
*=
example, if a = 10, b = 20 => a* = b will be equal to a = a* b and
therefore, a = 200.

It divides the value of the left operand by the value of the right
operand and assign the reminder back to left operand. For example,
%=
if a = 20, b = 10 => a % = b will be equal to a = a % b and therefore, a
= 0.

**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will
assign 4**2 = 16 to a.

A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will


//=
assign 4//3 = 1 to a.

Bitwise operator
The bitwise operators perform bit by bit operation on the values of the
two operands.

For example,

1. if a = 7;
2. b = 6;
3. then, binary (a) = 0111
4. binary (b) = 0011
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000

Operator Description

& (binary If both the bits at the same place in two operands are 1, then 1 is
and) copied to the result. Otherwise, 0 is copied.

The resulting bit will be 0 if both the bits are zero otherwise the
| (binary or)
resulting bit will be 1.

^ (binary The resulting bit will be 1 if both the bits are different otherwise
xor) the resulting bit will be 0.

It calculates the negation of each bit of the operand, i.e., if the


~ (negation)
bit is 0, the resulting bit will be 1 and vice versa.

<< (left The left operand value is moved left by the number of bits
shift) present in the right operand.

>> (right The left operand is moved right by the number of bits present in
shift) the right operand.

Logical Operators
The logical operators are used primarily in the expression evaluation to
make a decision. Python supports the following logical operators.

Operator Description

If both the expression are true, then the condition will be true. If a
and and b are the two expressions, a → true, b → true => a and b →
true.

If one of the expressions is true, then the condition will be true. If a


or
and b are the two expressions, a → true, b → false => a or b → true.

not If an expression a is true then not (a) will be false and vice versa.

Membership Operators
Python membership operators are used to check the membership of value
inside a data structure. If the value is present in the data structure, then
the resulting value is true otherwise it returns false.

Operator Description

It is evaluated to be true if the first operand is found in the second


in
operand (list, tuple, or dictionary).

It is evaluated to be true if the first operand is not found in the


not in
second operand (list, tuple, or dictionary).

Identity Operators
Operator Description
It is evaluated to be true if the reference present at both sides point
is
to the same object.

It is evaluated to be true if the reference present at both side do not


is not
point to the same object.

Operator Precedence
The precedence of the operators is important to find out since it enables
us to know which operator should be evaluated first. The precedence
table of the operators in python is given below.

Operator Description

The exponent operator is given priority over all the others used
**
in the expression.

~+- The negation, unary plus and minus.

The multiplication, divide, modules, reminder, and floor


* / % //
division.

+- Binary plus and minus

>> << Left shift and right shift

& Binary and.

^| Binary xor and or

Comparison operators (less then, less then equal to, greater


<= < > >=
then, greater then equal to).

<> == != Equality operators.

= %= /= //= -=
+= Assignment operators
*= **=

is is not Identity operators


in not in Membership operators

not or and Logical operators

Python Comments

Comments in Python can be used to explain any program code. It can also
be used to hide the code as well.

Comments are the most helpful stuff of any program. It enables us to


understand the way, a program works. In python, any statement written
along with # symbol is known as a comment. The interpreter does not
interpret the comment.

Comment is not a part of the program, but it enhances the interactivity of


the program and makes the program readable.

Python supports two types of comments:

1) Single Line Comment:

In case user wants to specify a single line comment, then comment must
start with ?#?

Eg:

1. # This is single line comment.


2. print "Hello Python"

Output:

Hello Python

2) Multi Line Comment:

Multi lined comment can be given inside triple quotes.

eg:

1. ''''' This
2. Is
3. Multipline comment'''

eg:
1. #single line comment
2. print "Hello Python"
3. '''''This is
4. multiline comment'''

Output:

Hello Python

Python If-else statements

Decision making is the most important aspect of almost all the


programming languages. As the name implies, decision making allows us
to run a particular block of code for a particular decision. Here, the
decisions are made on the validity of the particular conditions. Condition
checking is the backbone of decision making.

In python, decision making is performed by the following statements.

Statement Description

The if statement is used to test a specific condition. If the


If Statement
condition is true, a block of code (if-block) will be executed.

The if-else statement is similar to if statement except the fact


If - else that, it also provides the block of the code for the false case of
Statement the condition to be checked. If the condition provided in the if
statement is false, then the else statement will be executed.

Nested if Nested if statements enable us to use if ? else statement inside


Statement an outer if statement.

Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't
allow the use of parentheses for the block level code. In Python,
indentation is used to declare a block. If two statements are at the same
indentation level, then they are the part of the same block.

Generally, four spaces are given to indent the statements which are a
typical amount of indentation in python.

Indentation is the most used part of the python language since it declares
the block of code. All the statements of one block are intended at the
same level indentation. We will see how the actual indentation takes
place in decision making and other stuff in python.

The if statement
The if statement is used to test a particular condition and if the condition
is true, it executes a block of code known as if-block. The condition of if
statement can be any valid logical expression which can be either
evaluated to true or false.

The syntax of the if-statement is given below.

1. if expression:
2. statement

Example 1
1. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even")

Output:

enter the number?10


Number is even

Example 2 : Program to print the largest of the three numbers.

1. a = int(input("Enter a? "));
2. b = int(input("Enter b? "));
3. c = int(input("Enter c? "));
4. if a>b and a>c:
5. print("a is largest");
6. if b>a and b>c:
7. print("b is largest");
8. if c>a and c>b:
9. print("c is largest");

Output:

Enter a? 100
Enter b? 120
Enter c? 130
c is largest

The if-else statement


The if-else statement provides an else block combined with the if
statement which is executed in the false case of the condition.

If the condition is true, then the if-block is executed. Otherwise, the else-
block is executed.
The syntax of the if-else statement is given below.

1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)

Example 1 : Program to check whether a person is eligible to vote or


not.

1. age = int (input("Enter your age? "))


2. if age>=18:
3. print("You are eligible to vote !!");
4. else:
5. print("Sorry! you have to wait !!");

Output:

Enter your age? 90


You are eligible to vote !!

Example 2: Program to check whether a number is even or not.

1. num = int(input("enter the number?"))


2. if num%2 == 0:
3. print("Number is even...")
4. else:
5. print("Number is odd...")

Output:

enter the number?10


Number is even

The elif statement


The elif statement enables us to check multiple conditions and execute the
specific block of statements depending upon the true condition among
them. We can have any number of elif statements in our program
depending upon our need. However, using elif is optional.

The elif statement works like an if-else-if ladder statement in C. It must


be succeeded by an if statement.

The syntax of the elif statement is given below.

1. if expression 1:
2. # block of statements
3.
4. elif expression 2:
5. # block of statements
6.
7. elif expression 3:
8. # block of statements
9.
10. else:
11. # block of statements
Example 1

1. number = int(input("Enter the number?"))


2. if number==10:
3. print("number is equals to 10")
4. elif number==50:
5. print("number is equal to 50");
6. elif number==100:
7. print("number is equal to 100");
8. else:
9. print("number is not equal to 10, 50 or 100");

Output:

Enter the number?15


number is not equal to 10, 50 or 100

Example 2

1. marks = int(input("Enter the marks? "))


2. f marks > 85 and marks <= 100:
3. print("Congrats ! you scored grade A ...")
4. lif marks > 60 and marks <= 85:
5. print("You scored grade B + ...")
6. lif marks > 40 and marks <= 60:
7. print("You scored grade B ...")
8. lif (marks > 30 and marks <= 40):
9. print("You scored grade C ...")
10. lse:
11. print("Sorry you are fail ?")

Python Loops

The flow of the programs written in any programming language is


sequential by default. Sometimes we may need to alter the flow of the
program. The execution of a specific code may need to be repeated
several numbers of times.

For this purpose, The programming languages provide various types of


loops which are capable of repeating some specific code several numbers
of times. Consider the following diagram to understand the working of a
loop statement.
Why we use loops in python?
The looping simplifies the complex problems into the easy ones. It
enables us to alter the flow of the program so that instead of writing the
same code again and again, we can repeat the same code for a finite
number of times. For example, if we need to print the first 10 natural
numbers then, instead of using the print statement 10 times, we can print
inside a loop which runs up to 10 iterations.

Advantages of loops
There are the following advantages of loops in Python.

1. It provides code re-usability.


2. Using loops, we do not need to write the same code again and
again.
3. Using loops, we can traverse over the elements of data structures
(array or linked lists).
There are the following loop statements in Python.

Loop
Description
Statement
The for loop is used in the case where we need to execute
some part of the code until the given condition is satisfied.
for loop
The for loop is also called as a per-tested loop. It is better to
use for loop if the number of iteration is known in advance.
The while loop is to be used in the scenario where we don't
know the number of iterations in advance. The block of
while loop statements is executed in the while loop until the condition
specified in the while loop is satisfied. It is also called a pre-
tested loop.
The do-while loop continues until a given condition
do-while satisfies. It is also called post tested loop. It is used when it
loop is necessary to execute the loop at least once (mostly menu
driven programs).

Python for loop

The for loop in Python is used to iterate the statements or a part of the
program several times. It is frequently used to traverse the data structures
like list, tuple, or dictionary.

The syntax of for loop in python is given below.

1. for iterating_var in sequence:


2. statement(s)
Example
1. i=1
2. n=int(input("Enter the number up to which you want to print the natur
al numbers?"))
3. for i in range(0,10):
4. print(i,end = ' ')

Output:

0 1 2 3 4 5 6 7 8 9
Python for loop example : printing the table
of the given number
1. i=1;
2. num = int(input("Enter a number:"));
3. for i in range(1,11):
4. print("%d X %d = %d"%(num,i,num*i));

Output:

Enter a number:10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100

Nested for loop in python


Python allows us to nest any number of for loops inside a for loop. The
inner loop is executed n number of times for every iteration of the outer
loop. The syntax of the nested for loop in python is given below.

1. for iterating_var1 in sequence:


2. for iterating_var2 in sequence:
3. #block of statements
4. #Other statements

Example 1
1. n = int(input("Enter the number of rows you want to print?"))
2. i,j=0,0
3. for i in range(0,n):
4. print()
5. for j in range(0,i+1):
6. print("*",end="")

Output:
Enter the number of rows you want to print?5
*
**
***
****
*****

Using else statement with for loop


Unlike other languages like C, C++, or Java, python allows us to use the
else statement with the for loop which can be executed only when all the
iterations are exhausted. Here, we must notice that if the loop contains
any of the break statement then the else statement will not be executed.

Example 1
1. for i in range(0,5):
2. print(i)
3. else:print("for loop completely exhausted, since there is no break."
);

In the above example, for loop is executed completely since there is no


break statement in the loop. The control comes out of the loop and hence
the else block is executed.

Output:

0
1
2
3
4

for loop completely exhausted, since there is no break.

Example 2
1. for i in range(0,5):
2. print(i)
3. break;
4. else:print("for loop is exhausted");
5. print("The loop is broken due to break statement...came out of loo
p")

In the above example, the loop is broken due to break statement therefore
the else statement will not be executed. The statement present immediate
next to else block will be executed.

Output:

The loop is broken due to break statement...came out of loop

Python while loop

The while loop is also known as a pre-tested loop. In general, a while


loop allows a part of the code to be executed as long as the given
condition is true.

It can be viewed as a repeating if statement. The while loop is mostly


used in the case where the number of iterations is not known in advance.

The syntax is given below.

1. while expression:
2. statements

Here, the statements can be a single statement or the group of statements.


The expression should be any valid python expression resulting into true
or false. The true is any non-zero value.
Example 1
1. i=1;
2. while i<=10:
3. print(i);
4. i=i+1;

Output:

1
2
3
4
5
6
7
8
9
10

Example 2
1. i=1
2. number=0
3. b=9
4. number = int(input("Enter the number?"))
5. while i<=10:
6. print("%d X %d = %d \n"%(number,i,number*i));
7. i = i+1;

Output:

Enter the number?10

10 X 1 = 10

10 X 2 = 20

10 X 3 = 30

10 X 4 = 40

10 X 5 = 50

10 X 6 = 60

10 X 7 = 70

10 X 8 = 80

10 X 9 = 90

10 X 10 = 100

Infinite while loop


If the condition given in the while loop never becomes false then the
while loop will never terminate and result into the infinite while loop.

Any non-zero value in the while loop indicates an always-true condition


whereas 0 indicates the always-false condition. This type of approach is
useful if we want our program to run continuously in the loop without any
disturbance.

Example 1
1. while (1):
2. print("Hi! we are inside the infinite while loop");

Output:

Hi! we are inside the infinite while loop


(infinite times)

Example 2
1. var = 1
2. while var != 2:
3. i = int(input("Enter the number?"))
4. print ("Entered value is %d"%(i))

Output:

Enter the number?102


Entered value is 102
Enter the number?102
Entered value is 102
Enter the number?103
Entered value is 103
Enter the number?103
(infinite loop)

Using else with Python while loop


Python enables us to use the while loop with the while loop also. The else
block is executed when the condition given in the while statement
becomes false. Like for loop, if the while loop is broken using break
statement, then the else block will not be executed and the statement
present after else block will be executed.

Consider the following example.

1. i=1;
2. while i<=5:
3. print(i)
4. i=i+1;
5. else:print("The while loop exhausted");

Output:

1
2
3
4
5
The while loop exhausted

Example 2
1. i=1;
2. while i<=5:
3. print(i)
4. i=i+1;
5. if(i==3):
6. break;
7. else:print("The while loop exhausted");

Output:

1
2

Python break statement

The break is a keyword in python which is used to bring the program


control out of the loop. The break statement breaks the loops one by one,
i.e., in the case of nested loops, it breaks the inner loop first and then
proceeds to outer loops. In other words, we can say that break is used to
abort the current execution of the program and the control goes to the
next line after the loop.

The break is commonly used in the cases where we need to break the loop
for a given condition.

The syntax of the break is given below.

1. #loop statements
2. break;

Example 1
1. list =[1,2,3,4]
2. count = 1;
3. for i in list:
4. if i == 4:
5. print("item matched")
6. count = count + 1;
7. break
8. print("found at",count,"location");

Output:

item matched
found at 2 location

Example 2
1. str = "python"
2. for i in str:
3. if i == 'o':
4. break
5. print(i);

Output:

p
y
t
h

Example 3: break statement with while loop


1. i = 0;
2. while 1:
3. print(i," ",end=""),
4. i=i+1;
5. if i == 10:
6. break;
7. print("came out of while loop");

Output:

0 1 2 3 4 5 6 7 8 9 came out of while loop

Example 3
1. n=2
2. while 1:
3. i=1;
4. while i<=10:
5. print("%d X %d = %d\n"%(n,i,n*i));
6. i = i+1;
7. choice = int(input("Do you want to continue printing the table, press
0 for no?"))
8. if choice == 0:
9. break;
10. n=n+1

Output:

2 X 1 = 2

2 X 2 = 4

2 X 3 = 6

2 X 4 = 8

2 X 5 = 10

2 X 6 = 12

2 X 7 = 14

2 X 8 = 16

2 X 9 = 18

2 X 10 = 20

Do you want to continue printing the table, press 0 for


no?1

3 X 1 = 3

3 X 2 = 6

3 X 3 = 9

3 X 4 = 12

3 X 5 = 15

3 X 6 = 18

3 X 7 = 21

3 X 8 = 24

3 X 9 = 27
3 X 10 = 30

Do you want to continue printing the table, press 0 for


no?0

Python continue Statement

The continue statement in python is used to bring the program control to


the beginning of the loop. The continue statement skips the remaining
lines of code inside the loop and start with the next iteration. It is mainly
used for a particular condition inside the loop so that we can skip some
specific code for a particular condition.

The syntax of Python continue statement is given below.

1. #loop statements
2. continue;
3. #the code to be skipped

Example 1
1. i = 0;
2. while i!=10:
3. print("%d"%i);
4. continue;
5. i=i+1;

Output:

infinite loop

Example 2
1. i=1; #initializing a local variable
2. #starting a loop from 1 to 10
3. for i in range(1,11):
4. if i==5:
5. continue;
6. print("%d"%i);

Output:

1
2
3
4
6
7
8
9
10

Pass Statement
The pass statement is a null operation since nothing happens when it is
executed. It is used in the cases where a statement is syntactically needed
but we don?t want to use any executable statement at its place.

For example, it can be used while overriding a parent class method in the
subclass but don't want to give its specific implementation in the subclass.

Pass is also used where the code will be written somewhere but not yet
written in the program file.

The syntax of the pass statement is given below.

Example
1. list = [1,2,3,4,5]
2. flag = 0
3. for i in list:
4. print("Current element:",i,end=" ");
5. if i==3:
6. pass;
7. print("\nWe are inside pass block\n");
8. flag = 1;
9. if flag==1:
10. print("\nCame out of pass\n");
11. flag=0;

Output:

Current element: 1 Current element: 2 Current element: 3


We are inside pass block

Came out of pass

Current element: 4 Current element: 5

You might also like