Unit 1 Python Programming Basics
Unit 1 Python Programming Basics
Python provides basic and advanced concepts of Python. Python is a simple, general purpose,
high level, and object-oriented programming language.
Python is an interpreted scripting language also. Guido Van Rossum is known as the founder
of Python programming.
What is Python
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 make it an ideal language for
scripting and rapid application development.
Python is not intended to work in a particular area, such as web programming. That is why it
is known as multipurpose programming language 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.
o Python programming language is being updated regularly with new features and
supports. There are lots of update in Python versions, started from 1994 to current
release.
o A list of Python versions with its released date is given below.
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 is 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 Python programming tutorial.
Python Features
Python provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming, procedural programming
approaches and provides dynamic memory allocation. We have listed below a few essential
features.
2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello world
program you simply type print("Hello World"). It will take only one line to execute, while
Java or C takes multiple lines.
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a time.
The advantage of being interpreted language, it makes debugging easy and portable.
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. It enables programmers to develop the
software for several competing platforms by writing a program only once.
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. It converts the program into byte code, and any platform
can use that byte code.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line
by line like C,C++ Java. It makes easy to debug the code.
11. Embeddable
The code of the other programming language can use in the Python source code. We can use
Python source code in another programming language as well. It can embed other language
into our code.
Python Applications
Python is known for its general-purpose nature that makes it applicable in almost every domain
of software development. Python makes its presence in every emerging field. It is the fastest-
growing programming language and can develop any application.
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. One of Python web-framework named Django is used. Python provides many
useful frameworks, and these are given below:
The GUI stands for the Graphical User Interface, which provides a smooth interaction to any
application. Python provides a Tk GUI library to develop a user interface. Some popular GUI
libraries are given below.
o Tkinter or Tk
o wxWidgetM
o Kivy (used for writing multitouch applications )
o PyQt or Pyside
3) Console-based Application
Console-based applications run from the command-line or shell. These applications are
computer program which are used commands to execute. This kind of application was more
popular in the old generation of computers. Python can develop this kind of application very
effectively. It is famous for having REPL, which means the Read-Eval-Print Loop that makes
it the most suitable language for the command-line applications.
Python provides many free library or module which helps to build the command-line apps. The
necessary IO libraries are used to read and write. It helps to parse argument and create console
help text out-of-the-box. There are also advance libraries that can develop independent console
apps.
4) Software Development
Python is useful for the software development process. It works as a support language and can
be used to build control and management, testing, etc.
This is the era of Artificial intelligence where the machine can perform the task the same as
the human. Python language is the most suitable language for Artificial intelligence or machine
learning. It consists of many scientific and mathematical libraries, which makes easy to solve
complex calculations.
o SciPy
o Scikit-learn
o NumPy
o Pandas
o Matplotlib
6) Business Applications
Business Applications differ from standard applications. E-commerce and ERP are an example
of a business application. This kind of application requires extensively, scalability and
readability, and Python provides all these features.
Oddo is an example of the all-in-one Python-based application which offers a range of business
applications. Python provides a Tryton platform which is used to develop the business
application.
7) Audio or Video-based Applications
Python is flexible to perform multiple tasks and can be used to create multimedia applications.
Some multimedia applications which are made by using Python are TimPlayer, cplay, etc.
The few multimedia libraries are given below.
o Gstreamer
o Pyglet
o QT Phonon
8) 3D CAD Applications
The CAD (Computer-aided design) is used to design engineering related architecture. It is used
to develop the 3D representation of a part of a system. Python can create a 3D CAD application
by using the following functionalities.
o Fandango (Popular )
o CAMVOX
o HeeksCNC
o AnyCAD
o RCAM
9) Enterprise Applications
Python can be used to create applications that can be used within an Enterprise or an
Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.
Python contains many libraries that are used to work with the image. The image can be
manipulated according to our requirements. Some libraries of image processing are given
below.
o OpenCV
o Pillow
o SimpleITK
In this topic, we have described all types of applications where Python plays an essential role
in the development of these applications. In the next tutorial, we will learn more concepts about
Python.
How to Install Python (Environment Set-up)
In order to become Python developer, the first step is to learn how to install or update Python
on a local machine or computer.
Installation on Windows
Double-click the executable file, which is downloaded; Select Customize installation and
proceed. Click on the Add Path check box, it will set the Python path automatically.
We can also click on the customize installation to choose desired location and features. Other
important thing is install launcher for the all user must be checked.
In this Section, we will discuss the basic syntax of Python, we will run a simple program to
print Hello World on the console.
Python provides us the feature to execute the Python statement one by one at the interactive
prompt. It is preferable in the case where we are concerned about the output of each line of
our Python program.
To open the interactive mode, open the terminal (or command prompt) and type python
(python3 in case if you have Python2 and Python3 both installed on your system).
It will open the following prompt where we can execute the Python statement and check their
impact on the console.
To open the interactive mode, open the terminal (or command prompt) and type python
(python3 in case if you have Python2 and Python3 both installed on your system).
It will open the following prompt where we can execute the Python statement and check their
impact on the console.
Here, we get the message "Hello World !" printed on the console.
The interpreter prompt is best to run the single-line statements of the code. However, we cannot
write the code every-time on the terminal. It is not suitable to write multiple lines of code.
Using the script mode, we can write multiple lines code into a file which can be executed later.
For this purpose, we need to open an editor like notepad, create a file named and save it
with .py extension, which stands for "Python". Now, we will implement the above example
using the script mode.
Python Variables
Variable is a name that is used to refer to memory location. Python variable is also known as
an identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a infer language and
smart enough to get variable type.
Variable names can be a group of both the letters and digits, but they have to begin with a letter
or an underscore.
It is recommended to use lowercase letters for the 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.
We don't need to declare explicitly variable in Python. When we assign any value to the
variable, that variable is declared automatically.
Object References
It is necessary to understand how the Python interpreter works when we declare a variable. The
process of treating variables is somewhat different from many other programming languages.
Python is the highly object-oriented programming language; that's why every data item belongs
to a specific type of class. Consider the following example.
print("ABC")
output
ABC
The Python object creates an integer object and displays it to the console. In the above print
statement, we have created a string object. Let's check the type of it using the Python built-
in type() function.
type("ABC")
Output:
<class 'str'>
In Python, variables are a symbolic name that is a reference or pointer to an object. The
variables are used to denote objects by that name.
a = 50
In the above image, the variable a refers to an integer object.
a = 50
b=a
The variable b refers to the same object that a points to because Python does not create another
object.
Let's assign the new value to b. Now both variables will refer to the different objects.
a = 50
b =100
Python manages memory efficiently if we assign the same variable to two different values.
Object Identity
In Python, every created object identifies uniquely in Python. Python provides the guaranteed
that no two objects will have the same identifier. The built-in id() function, is used to identify
the object identifier. Consider the following example.
1. a = 50
2. b = a
3. print(id(a))
4. print(id(b))
5. # Reassigned variable a
6. a = 500
7. print(id(a))
Output:
3065075101520
3065075101520
3065117318480
We assigned the b = a, a and b both point to the same object. When we checked by
the id() function it returned the same number. We reassign a to 500; then it referred to the new
object identifier.
Variable Names
We have already discussed how to declare the valid variable. Variable names can be any length
can have uppercase, lowercase (A to Z, a to z), the digit (0-9), and underscore character(_).
Consider the following example of valid variables names.
1. name = "Rajiv"
2. age = 20
3. marks = 80.50
4. print(name)
5. print(age)
6. print(marks)
Output:
Rajiv
20
80.5
o Camel Case - In the camel case, each word or abbreviation in the middle of begins with
a capital letter. There is no intervention of whitespace. For example - nameOfStudent,
valueOfVaraible, etc.
o Pascal Case - It is the same as the Camel Case, but here the first word is also capital.
For example - NameOfStudent, etc.
o Snake Case - In the snake case, Words are separated by the underscore. For example -
name_of_student, etc.
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is also
known as multiple assignments.
We can apply multiple assignments in two ways, either by assigning a single value to multiple
variables or assigning multiple values to multiple variables. Consider the following example.
1. Assigning single value to multiple variables
Eg:
1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)
Output:
50
50
50
Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
5
10
15
Local Variable
Local variables are the variables that declared inside the function and have scope within the
function. Let's understand the following example.
Example -
1. # Declaring a function
2. def add():
3. # Defining local variables. They has scope only within a function
4. a = 20
5. b = 30
6. c=a+b
7. print("The sum is:", c)
8. # Calling a function
9. add()
Output:
Global variables can be used throughout the program, and its scope is in the entire program.
We can use global variables inside or outside the function.
A variable declared outside the function is the global variable by default. Python provides
the global keyword to use global variable inside the function. If we don't use
the global keyword, the function treats it as a local variable. Let's understand the following
example.
Example –
1. # Declare a variable and initialize it
2. x = 101
3. # Global variable in function
4. def mainFunction():
5. # printing a global variable
6. global x
7. print(x)
8. # modifying a global variable
9. x = 'Welcome To Python'
10. print(x)
11. mainFunction()
12. print(x)
Output:
101
Welcome To Python
Welcome To Python
Python Data Types
Variables can hold values, and every value has a data-type. Python is a dynamically typed
language; hence we do not need to define the type of the variable while declaring it. The
interpreter implicitly binds the value with its type.
a=5
The variable a holds integer value five and we did not define its type. Python interpreter will
automatically interpret variables a as an integer 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))
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. Sequence Type
3. Boolean
4. Set
5. Dictionary
Numbers
Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type. Python provides the type() function to know the data-type of the variable.
Similarly, the isinstance() function is used to check an object belongs to a particular class.
Python creates Number objects when a number is assigned to a variable. For example;
1. a = 5
2. print("The type of a", type(a))
3. b = 40.5
4. print("The type of b", type(b))
5. c = 1+3j
6. print("The type of c", type(c))
7. print(" c is a complex number", isinstance(1+3j,complex))
Output:
Sequence Type
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 Python provides built-in functions and operators to
perform operations in the string. In the case of string handling, the operator + is used to
concatenate two strings as the operation "hello"+" python" returns "hello python". mutable(can
modify after creation) . String is immutable(can’t modify after creation)
The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python
Python'.
Example – 1
str = "string using double quotes"
print(str)
s = '''''A multiline
string'''
print(s)
Output:
List
Python 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. List is mutable (can modify after creation)
Output:
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 (). Tuple is immutable (can’t modify after creation).
A tuple is a read-only data structure as we can't modify the size and value of the items of
a tuple.
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
Dictionary
Dictionary is an unordered 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. Dictionary is mutable (can modify after creation)
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces
{}.
Output:
Boolean
Boolean type provides two built-in values, True and False. These values are used to determine
the given statement true or false. It denotes by the class bool. True can be represented by any
non-zero value or 'T' whereas false can be represented by the 0 or 'F'. Consider the following
example.
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after
creation), and has unique elements. In set, the order of the elements is undefined; it may return
the changed sequence of the element. The set is created by using a built-in function set(), or a
sequence of elements is passed in the curly braces and separated by the comma. It can contain
various types of values. Consider the following example.
Output:
Python Keywords
Python Keywords are special reserved words that convey a special meaning to the
compiler/interpreter. Each keyword has a special meaning and a specific operation. These
keywords can't be used as a variable. Following is the List of Python Keywords.
1. True - It represents the Boolean true, if the given condition is true, then it returns
"True". Non-zero values are treated as true.
2. False - It represents the Boolean false; if the given condition is false, then it returns
"False". Zero value is treated as false
3. None - It denotes the null value or void. An empty list or Zero can't be treated as None.
4. and - It is a logical operator. It is used to check the multiple conditions. It returns true
if both conditions are true.
5. or - It is a logical operator in Python. It returns true if one of the conditions is true.
6. not - It is a logical operator and inverts the truth value.
7. def - This keyword is used to declare the function in Python.
8. class - It is used to represents the class in Python. The class is the blueprint of the
objects. It is the collection of the variable and methods.
9. continue - It is used to stop the execution of the current iteration.
10. break - It is used to terminate the loop execution and control transfer to the end of
the loop.
11. If - It is used to represent the conditional statement. The execution of a particular block
is decided by if statement.
12. else - The else statement is used with the if statement. When if statement returns false,
then else block is executed.
13. elif - This Keyword is used to check the multiple conditions. It is short for else-if. If the
previous condition is false, then check until the true condition is found.
14. del - It is used to delete the reference of the object.
15. try, except - The try-except is used to handle the exceptions. The exceptions are run-
time errors.
16. raise - The raise keyword is used to through the exception forcefully.
17. finally - The finally keyword is used to create a block of code that will always be
executed no matter the else block raises an error or not.
18. for, while - Both keywords are used for iteration. The for keyword is used to iterate
over the sequences (list, tuple, dictionary, string). A while loop is executed until the
condition returns false.
19. import - The import keyword is used to import modules in the current Python script.
The module contains a runnable Python code.
20. from - This keyword is used to import the specific function or attributes in the current
Python script.
21. as - It is used to create a name alias. It provides the user-define name while importing
a module.
22. pass - The pass keyword is used to execute nothing or create a placeholder for future
code. If we declare an empty class or function, it will through an error, so we use the
pass keyword to declare an empty class or function.
Example:
class my_class:
pass
def my_func():
pass
23. return - The return keyword is used to return the result value or none to called
function.
24. is - This keyword is used to check if the two-variable refers to the same object. It returns
the true if they refer to the same object otherwise false. Consider the following
example.
Example
x=5
y=5
a = []
b = []
print(x is y)
print(a is b)
25. global - The global keyword is used to create a global variable inside the function. Any
function can access the global.
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 specific
programming language. Python provides a variety of operators, which are described as follows.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o 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 (**) operators.
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b =
30
- (Subtraction) It is used to subtract the second operand from the first operand. If the first
operand is less than the second operand, the value results negative. For
example, if a = 20, b = 10 => a - b = 10
/ (divide) It returns the quotient after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a = 20,
(Multiplication) b = 10 => a * b = 200
% (reminder) It returns the reminder after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a%b = 0
// (Floor It gives the floor value of the quotient produced by dividing the two
division) 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 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.
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 increases the value of the left operand by the value of the right operand and
assigns 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
assigns 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
assigns the modified value back to then the 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
assigns the reminder back to the 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 Operators
The bitwise operators perform bit by bit operation on the values of the two operands. Consider
the following example.
For example,
1. if a = 7
2. b=6
3. then, binary (a) = 0111
4. binary (b) = 0110
5. hence, a & b = 0011
6. a | b = 0111
7. a ^ b = 0100
8. ~ a = 1000
Operator Description
& (binary If both the bits at the same place in two operands are 1, then 1 is copied to
and) the result. Otherwise, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting
bit will be 1.
^ (binary xor) The resulting bit will be 1 if both the bits are different; otherwise, the
resulting bit will be 0.
~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is 0, the
resulting bit will be 1 and vice versa.
<< (left shift) The left operand value is moved left by the number of bits present in the right
operand.
>> (right The left operand is moved right by the number of bits present in the right
shift) 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
and If both the expression are true, then the condition will be true. If a and b are the
two expressions, a → true, b → true => a and b → true.
or If one of the expressions is true, then the condition will be true. If a 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 Python data
structure. If the value is present in the data structure, then the resulting value is true otherwise
it returns false.
Operator Description
in It is evaluated to be true if the first operand is found in the second operand (list,
tuple, or dictionary).
not in It is evaluated to be true if the first operand is not found in the second operand (list,
tuple, or dictionary).
Identity Operators
The identity operators are used to decide whether an element certain class or type.
Operator Description
is It is evaluated to be true if the reference present at both sides point to the same
object.
is not It is evaluated to be true if the reference present at both sides do not point to the
same object.
Operator Precedence
The precedence of the operators is essential 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.
<= < > >= Comparison operators (less than, less than equal to, greater than, greater then
equal to).
Python Comments
Python Comment is an essential tool for the programmers. Comments are generally used to
explain the code. We can easily understand the code if it has a proper explanation. A good
programmer must use the comments because in the future anyone wants to modify the code as
well as implement the new module; then, it can be done easily.
In the other programming language such as C++, It provides the // for single-lined comment
and /*.... */ for multiple-lined comment, but Python provides the single-lined Python comment.
To apply the comment in the code we use the hash(#) at the beginning of the statement or code.
The above code is very readable even the absolute beginners can under that what is happening
in each line of the code. This is the advantage of using comments in code.
We can also use the triple quotes ('''''') for multiline comment. The triple quotes are also used
to string formatting. Consider the following example.
def intro():
"""
This function prints Hello Joseph
"""
print("Hi Joseph")
intro()
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.
Statement Description
If Statement The if statement is used to test a specific condition. If the condition is true, a block
of code (if-block) will be executed.
If - else The if-else statement is similar to if statement except the fact that, it also provides
Statement the block of the code for the false case of the condition to be checked. If the
condition provided in the if statement is false, then the else statement will be
executed.
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:
Output:
Enter a? 100
Enter b? 120
Enter c? 130
c is largest
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)
Output:
Output:
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.
1. if expression 1:
2. # block of statements
3. elif expression 2:
4. # block of statements
5. elif expression 3:
6. # block of statements
7. else:
8. # 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:
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.
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.
Loop Description
Statement
for loop The for loop is used in the case where we need to execute some part of the code
until the given condition is satisfied. 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.
while loop The while loop is to be used in the scenario where we don't know the number
of iterations in advance. The block of 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.
do-while loop The do-while loop continues until a given condition satisfies. It is also called
post tested loop. It is used when it is necessary to execute the loop at least once
(mostly menu driven programs).
1. str = "Python"
2. for i in str:
3. print(i)
Output:
P
y
t
h
o
n
1. list = [1,2,3,4,5,6,7,8,9,10]
2. n = 5
3. for i in list:
4. c = n*i
5. print(c)
Output:
5
10
15
20
25
30
35
40
45
50
1. list = [10,30,23,43,65,12]
2. sum = 0
3. for i in list:
4. sum = sum+i
5. print("The sum is:",sum)
Output:
Syntax:
1. for i in range(10):
2. print(i,end = ' ')
Output:
0123456789
Output:
Output:
We can also use the range() function with sequence of numbers. The len() function is
combined with range() function which iterate through a sequence using indexing. Consider the
following example.
1. list = ['Peter','Joseph','Ricky','Devansh']
2. for i in range(len(list)):
3. print("Hello",list[i])
Output:
Hello Peter
Hello Joseph
Hello Ricky
Hello Devansh
Syntax
Output:
1
22
333
4444
55555
Example 1
1. for i in range(0,5):
2. print(i)
3. else:
4. print("for loop completely exhausted, since there is no break.")
Output:
0
1
2
3
4
for loop completely exhausted, since there is no break.
The 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:
5. print("for loop is exhausted");
6. print("The loop is broken due to break statement...came out of the loop")
In the above example, the loop is broken due to the 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 the break statement...came out of the loop.
It can be viewed as a repeating if statement. When we don't know the number of iterations then
the while loop is most effective to use.
1. while expression:
2. statements
Here, the statements can be a single statement or a group of statements. The expression should
be any valid Python expression resulting in true or false. The true is any non-zero value and
false is 0.
Loop Control Statements
We can change the normal sequence of while loop's execution using the loop control statement.
When the while loop's execution is completed, all automatic objects defined in that scope are
demolished. Python offers the following control statement to use within the while loop.
1. Continue Statement - When the continue statement is encountered, the control transfer to
the beginning of the loop. Let's understand the following example.
Example:
Output:
Current Letter : p
Current Letter : y
Current Letter : h
Current Letter : o
Current Letter : n
Break Statement - When the break statement is encountered, it brings control out of the
loop.
Example:
Output:
Current Letter : p
Current Letter : y
Pass Statement - The pass statement is used to declare the empty loop. It is also used to
define empty class, function, and control statement. Let's understand the following example.
Example -
1. # An empty loop
2. str1 = 'python'
3. i = 0
4. while i < len(str1):
5. i += 1
6. pass
7. print('Value of i :', i)
Output:
Value of i : 10
Example-1: Program to print 1 to 10 using while loop
1. i=1
2. #The while loop will iterate until condition becomes false.
3. while(i<=10):
4. print(i)
5. i=i+1
Output:
1
2
3
4
5
6
7
8
9
10
Example -2: Program to print table of given numbers.
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:
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
Any non-zero value in the while loop indicates an always-true condition, whereas zero
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:
Output:
Output:
The break is commonly used in the cases where we need to break the loop for a given condition.
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
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:
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:
2X1=2
2X2=4
2X3=6
2X4=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
3X1=3
3X2=6
3X3=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
Syntax
1. #loop statements
2. continue
3. #the code to be skipped
Flow Diagram
Example 1
i=0
while(i < 10):
i = i+1
if(i == 5):
continue
print(i)
Output:
1
2
3
4
6
7
8
9
10
Observe the output of above code, the value 5 is skipped because we have provided the if
condition using with continue statement in while loop. When it matched with the given
condition then control transferred to the beginning of the while loop and it skipped the value 5
from the code.
Example 2
1. str = "python"
2. for i in str:
3. if(i == 'T'):
4. continue
5. print(i)
Output:
p
y
t
h
o
n
Python Pass
In Python, the pass keyword is used to execute nothing; it means, when we don't want to
execute code, the pass can be used to execute empty. It is the same as the name refers to. It just
makes the control to pass by without executing any code. If we want to bypass any code pass
statement can be used.
It is beneficial when a statement is required syntactically, but we want we don't want to execute
or execute it later. The difference between the comments and pass is that, comments are entirely
ignored by the Python interpreter, where the pass statement is not ignored.
Suppose we have a loop, and we do not want to execute right this moment, but we will execute
in the future. Here we can use the pass.
Example - 2:
for i in [1,2,3,4,5]:
if(i==4):
pass
print("This is pass block",i)
print(i)
Output:
1. 1
2. 2
3. 3
4. This is pass block 4
5. 4
6. 5
1. # Empty Function
2. def function_name(args):
3. pass
4. #Empty Class
5. class Python:
6. pass