100% found this document useful (1 vote)
139 views140 pages

Unit III Iiot

Python is a high-level, interpreted, interactive and object-oriented programming language. It can be used for a wide range of applications including web development, scientific computing, desktop GUIs, and business applications. Some key features of Python include being easy to code, free and open-source, portable, having a large standard library, and supporting object-oriented, procedural, and functional programming. Python is an interpreted language, meaning code does not need to be compiled but is instead executed line by line.

Uploaded by

Rama Rao Mannam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
139 views140 pages

Unit III Iiot

Python is a high-level, interpreted, interactive and object-oriented programming language. It can be used for a wide range of applications including web development, scientific computing, desktop GUIs, and business applications. Some key features of Python include being easy to code, free and open-source, portable, having a large standard library, and supporting object-oriented, procedural, and functional programming. Python is an interpreted language, meaning code does not need to be compiled but is instead executed line by line.

Uploaded by

Rama Rao Mannam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 140

UNIT-3

Introduction to
Python
What is Computer Program?

 A computer program is a sequence of instructions


written using a Computer Programming Language to
perform a specified task by the computer.
Computer program
• A computer program is also called a computer software, which can range from
two lines to millions of lines of instructions.

• Computer program instructions are also called program source code


and computer programming is also called program coding.

• computer scientists have developed several computer-programming languages


to provide instructions to the computer (i.e., to write computer programs) few
of them are −
 Java C C++ Python
 PHP Perl Ruby
Applications of computer programming languages
Python Web and Internet Development, Scientific and Numeric applications, Desktop GUIs, Business
applications. It is widely used in AI and Machine Learning space.

Java Mostly used for developing Android apps, web apps, and Big data.

R Data Science projects, Statistical computing, Machine learning

Javascript JavaScript usage include web/mobile app development, game development, and desktop app
development.

C++ C++ is widely used in Game Development, Advance Computations, and Graphics Compilers

C# Widely used in Enterprise Cross-Applications Development, Web Applications

PHP Web Development, eCommerce Applications

SQL Used in Any Database


What is PYTHON?

• Python is a high-level, interpreted, interactive and


object-oriented, scripting language.

Python is a high-level
 It is a language that enables a programmer to
write programs that are more or less independent of a particular
type of computer. Such languages are considered as closer to
human languages and further from machine languages.

Python is Interpreted
 Python is processed at runtime by the interpreter. We do not need to
compile our program before executing it. This is similar to PERL and
PHP.
Python is Interactive
 You can actually sit at a Python prompt and
interact with the interpreter directly to write your
programs.

Python is Object-Oriented
 Python is an object-oriented language .It allows
us to develop applications using an Object-
Oriented approach. In Python, we can easily
create and use classes and objects.
Python is scripting language:
 A scripting language is used to write scripts. These contain a series of commands that are
interpreted one by one at runtime unlike programming languages that are compiled first
before running
Programming languages based applications are run by compiler
Programming languages based applications are required explicit compilation
Programming languages based applications can’t run directly without
compilation.
Ex: C,C++,JAVA .NET
These languages are run by compiler

Scripting language based applications are run by interpreter.


Scripting language based applications are not required explicit compilation
Ex: shellscript, python , perl, Ruby, PowerShell
These languages are run by interpreter.
 Python is a dynamic programming language which supports several different
programming paradigms:
Procedural programming(C)
Object oriented programming(C++,java)
Functional programming(LISP, Erlang…..)
Scripting languages(shell script, PERL, Ruby, Powershell)
Modular programming(Modula-3)

 Python= powerful programming language + powerful scripting language


2. History of Python, Python is Derived from?,:
Python was developed by Guido van Rossum, a Dutch computer programmer in December
1989 at the National Research Institute for Mathematics and Computer Science (NRIMCS)in the
Netherlands.

Python is said to have succeeded is ABC Programming Language, which had the interfacing
with the Amoeba Operating System.

Python is derived from many other languages, including ABC, Modula-3, C, C++,Algol-68,
SmallTalk, and Unix shell and other scripting languages
 Here interesting fact is- Python is named after the BBC TV comedy show Monty

Python’s Flying Circus.

 It is not named after the Python snake.


Features of Python Programming

1. Easy to code and Easy to read

2. Free and Open-Source


3. High- Level
4. Portable

5. Interpreted
6. Object-Oriented
7. Embeddable

8. Large Standard Library


9. GUI Programming
10.Dynamically Typed
1. Easy:
a. Easy to code:

– Python is very easy to code. Compared to other popular languages like Java
and C++ . Anyone can learn python syntax in just a few hours.
b. Easy to read:

– Being a high-level language, Python code is quite like English. Looking at it, you
can tell what the code is supposed to do.

2. Free and Open-Source

 Firstly, Python is freely available. You can download it from the following link
https://www.python.org/downloads/.

 Secondly, it is open-source. This means that its source code is available to the
public. You can download it, change it, use it, and distribute it. This is called
FLOSS(Free/Libre and Open Source Software).
3. High- Level

 It is a high-level language. This means that as programmers,


we don’t need to remember the system architecture. Nor do
we need to manage the memory. This makes it more
programmer-friendly.

4. Portable
 We can take one code and run it on any machine, there is no
need to write different code for different machines. This
makes Python a portable language. However, you must avoid
any system-dependent features in this case.
5. Interpreted:
 If you’re any familiar with languages like C++ or Java, you must first
compile it, and then run it. But in Python, there is no need to
compile it. Internally, its source code is converted into an
immediate form called byte code.

 So, all you need to do is to run your Python code without worrying
about linking to libraries, and a few other things.

 By interpreted, we mean the source code is executed line by line,


and not all at once. Because of this, it is easier to debug your code.
6. Object-Oriented:
 Python allows us to develop applications using an Object-Oriented approach.

 Object-oriented programming (OOP) is nothing but that which allows the writing of programs
with the help of certain classes and real-time objects.

 Python supports object-oriented programming concepts like


 Class
 Object
 Method
 Inheritance
 Polymorphism
 Data Abstraction
 Encapsulation

 It also supports multiple inheritance, unlike Java.


7. Embeddable
 We can put our Python code in a source code in a different language like C++.

 We can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
 CPython is a python integrated with C/C++ language.
 Similarly JPython is a purely integrated language.

8. Large Standard Library


 Python downloads with a large library that you can use so you don’t have to
write your own code for every single thing.

 There are libraries for regular expressions, documentation-generation, unit-


testing, web browsers, threading, databases, CGI, email, image manipulation,
and a lot of other functionality.
9.GUI Programming
You can use Tk or Tkinter to create basic GUIs.

10. Dynamically Typed


Python is dynamically-typed. This means that the
type for a value is decided at runtime, not in
advance. This is why we don’t need to specify the
type of data while declaring it.
Python Applications
1) Web Applications

2) Desktop GUI Applications

3) Scientific and Numeric

4) Business Applications

5) Console Based Application

6) Audio or Video based Applications

7) 3D CAD Applications

8) Enterprise Applications

9) Image applications
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 etc.

 It also provides Frameworks such as Django, Pyramid, Flask etc to design and
develop 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, numpy, Pandas, IPython etc.
 SciPy is group of packages of engineering, science and mathematics.

5) Business Applications
 Python is used to build Business 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.
Advantages of Python
1. Freeware: Python is open source language. It doesn't require any activation key or
subscription to work on it. It is free to use software and all the tool available on
python are absolutely free.

2. Less Coding: The syntax written in python is very simple and use common English
language which makes it more user-friendly.

3. Efficient: Python relies on indentation, using white space, to define scope; such as
the scope of loops, functions, and classes. Other Programming Languages use curly-
brackets for this purpose.

4. Portability: Python can run any operating system. Also, we use the Python Code
written on one system onto another system without making any changes to the code.
Existing Programming Vs Python Programming:
C, c++ ,java , python program to find addition of two numbers

--------c program-------- --------c++ program--------


#include<stdio.h>  #include <iostream>
int main() using namespace std;
{ int main()
   int a, b, sum;  {

   printf("\nEnter two no: "); int firstNumber, secondNumber, sumOfTwoNumbers;

   scanf("%d %d", &a, &b);  cout << "Enter two integers: ";
cin >> firstNumber >> secondNumber;
   sum = a + b; 
sumOfTwoNumbers = firstNumber + secondNumber;
   printf("Sum : %d", sum); 
cout << firstNumber << " + " << secondNumber << " = " << sumOfTwoNumbers;
   return(0);
return 0;
}
}

--------java program--------
--------python program--------
public class AddTwoNumbers {
num1 = 1.5; num2 = 6.3
public static void main(String[] args) {
sum = num1 + num2
int num1 = 5, num2 = 15, sum;
print('The sum of two numbers”, sum))
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
1. Data Types in Python
Data Structures in Python
• What is a Data Structure? 
• Organizing, managing and storing data is
important as it enables easier access and
efficient modifications.

• Data Structures allows to organize data in such


a way that enables to store collections of data,
relate them and perform operations on them
accordingly. 
Types of Data Structures in Python

• Python has implicit support for Data Structures


which enable you to store and access data. These
structures are called List, Dictionary, Tuple and Set.

• Python allows its users to create their own Data


Structures enabling them to have full control over
their functionality.

• The most prominent Data Structures are Stack,


Queue, Tree, Linked List and so on which are also
available in other programming languages.
Built-in Data Structures

1) Lists:
• Lists are used to store data of different data types in a
sequential manner.

• There are addresses assigned to every element of the


list, which is called as Index. The index value starts
from 0 and goes on until the last element called
the positive index.

• There is also negative indexing which starts from -1


enabling you to access elements from the last to first.
Creating a list

• To create a list, use the square brackets and add elements


into it accordingly. If you do not pass any elements inside
the square brackets, get an empty list as the output.

my_list = [] #create empty list


print(my_list)
my_list = [1, 2, 3, 'example', 3.132] #creating list with data
print(my_list)

Output:
[]
[1, 2, 3, ‘example’, 3.132]
Adding Elements

• Adding the elements in the list can be achieved


using the append(), extend() and insert() functions.

• The append() function adds all the elements passed


to it as a single element.

• The extend() function adds the elements one-by-


one into the list.

• The insert() function adds the element passed to


the index value and increase the size of the list too.
Example:

my_list = [1, 2, 3]
print(my_list)
my_list.append([555, 12]) #add as a single element
print(my_list)
my_list.extend([234, 'more_example']) #add as different elements
print(my_list)
my_list.insert(1, 'insert_example') #add element i
print(my_list)

Output:

[1, 2, 3]
[1, 2, 3, [555, 12]]
[1, 2, 3, [555, 12], 234, ‘more_example’]
[1, ‘insert_example’, 2, 3, [555, 12], 234, ‘more_example’]
Deleting Elements

• To delete elements, use the del keyword


which is built-in into Python but this does not
return anything back to us.

• If you want the element back, you use the


pop() function which takes the index value.

• To remove an element by its value, you use


the remove() function.
Example:

my_list = [1, 2, 3, 'example', 3.132, 10, 30]


del my_list[5] #delete element at index 5
print(my_list)
my_list.remove('example') #remove element with value
print(my_list)
a = my_list.pop(1) #pop element from list
print('Popped Element: ', a, ' List remaining: ', my_list)
my_list.clear() #empty the list
print(my_list)

Output:

[1, 2, 3, ‘example’, 3.132, 30]


[1, 2, 3, 3.132, 30]
Popped Element: 2 List remaining: [1, 3, 3.132, 30]
[]
Accessing Elements

• Accessing elements is the same as


accessing Strings in Python. Pass the index values
and hence can obtain the values as needed.
my_list = [1, 2, 3, 'example', 3.132, 10, 30]
for element in my_list: #access elements one by one
    print(element)
print(my_list) #access all elements
print(my_list[3]) #access index 3 element
print(my_list[0:2]) #access elements from 0 to 1 and exclude 2
print(my_list[::-1]) #access elements in reverse

Output:

1
2
3
example
3.132
10
30
[1, 2, 3, ‘example’, 3.132, 10, 30]
example
[1, 2]
[30, 10, 3.132, ‘example’, 3, 2, 1]
Other Functions

• The len() function returns to us the length of the list.

• The index() function finds the index value of value


passed where it has been encountered the first time.

• The count() function finds the count of the value


passed to it.

• The sorted() and sort() functions do the same thing,


that is to sort the values of the list. The sorted() has a
return type whereas the sort() modifies the original
list.
my_list = [1, 2, 3, 10, 30, 10]
print(len(my_list)) #find length of list
print(my_list.index(10)) #find index of element that occurs first
print(my_list.count(10)) #find count of the element
print(sorted(my_list)) #print sorted list but not change original
my_list.sort(reverse=True) #sort original list
print(my_list)

Output:
6
3
2
[1, 2, 3, 10, 10, 30]
[30, 10, 10, 3, 2, 1]
Dictionary

• Dictionaries are used to store key-value pairs.

• Example: Phone directory where hundreds and thousands of names and


their corresponding numbers have been added.

― Now the constant values here are Name and the Phone Numbers which are
called as the keys.

― And the various names and phone numbers are the values that have been fed to
the keys.

― If you access the values of the keys, you will obtain all the names and phone
numbers.

― So that is what a key-value pair is. And in Python, this structure is stored using
Dictionaries. 
Creating a Dictionary

• Dictionaries can be created using the flower braces or using


the dict() function. You need to add the key-value pairs
whenever you work with dictionaries.

my_dict = {} #empty dictionary


print(my_dict)
my_dict = {1: 'Python', 2: 'Java‘} #dictionary with elements
print(my_dict)

Output:
{}
{1: ‘Python’, 2: ‘Java’}
Changing and Adding key, value pairs

• To change the values of the dictionary, you need to do that using the
keys. So, you firstly access the key and then change the value
accordingly. To add values, you simply just add another key-value pair as
shown below.

my_dict = {'First': 'Python', 'Second': 'Java'}


print(my_dict)
my_dict['Second'] = 'C++' #changing element
print(my_dict)
my_dict['Third'] = ‘Ruby’ #adding key-value pair
print(my_dict)

Output:
{‘First’: ‘Python’, ‘Second’: ‘Java’}
{‘First’: ‘Python’, ‘Second’: ‘C++’}
{‘First’: ‘Python’, ‘Second’: ‘C++’, ‘Third’: ‘Ruby’}
Deleting key, value pairs
• To delete the values, you use the pop() function which returns the value that has been deleted.
• To retrieve the key-value pair, you use the popitem() function which returns a tuple of the key and
value.
• To clear the entire dictionary, you use the clear() function.

my_dict = {'First': 'Python', 'Second': 'Java', 'Third': 'Ruby'}


a = my_dict.pop('Third') #pop element
print('Value:', a)
print('Dictionary:', my_dict)
b = my_dict.popitem() #pop the key-value pair
print('Key, value pair:', b)
print('Dictionary', my_dict)
my_dict.clear() #empty dictionary
print('n', my_dict)

Output:
Value: Ruby
Dictionary: {‘First’: ‘Python’, ‘Second’: ‘Java’}
Key, value pair: (‘Second’, ‘Java’)
Dictionary {‘First’: ‘Python’}
{}
Accessing Elements

• Access elements using the keys only. Use either


the get() function or just pass the key values and
you will be retrieving the values.

my_dict = {'First': 'Python', 'Second': 'Java'}


print(my_dict['First']) #access elements using keys
print(my_dict.get('Second'))

Output:
Python
Java
Other Functions

• We have different functions which return to us the keys or the


values of the key-value pair accordingly to the keys(), values(),
items() functions accordingly.

my_dict = {'First': 'Python', 'Second': 'Java', 'Third': 'Ruby'}


print(my_dict.keys()) #get keys
print(my_dict.values()) #get values
print(my_dict.items()) #get key-value pairs
print(my_dict.get('First'))

Output:
dict_keys([‘First’, ‘Second’, ‘Third’])
dict_values([‘Python’, ‘Java’, ‘Ruby’])
dict_items([(‘First’, ‘Python’), (‘Second’, ‘Java’), (‘Third’, ‘Ruby’)])
Python
Tuple

• Tuple are the same as lists are with the exception that the data
once entered into the tuple cannot be changed no matter what.

• The only exception is when the data inside the tuple is mutable,
only then the tuple data can be changed.

Creating a Tuple:

You create a tuple using parenthesis or using the tuple() function.

my_tuple = (1, 2, 3) #create tuple


print(my_tuple)

Output:
(1, 2, 3)
Accessing Elements

• Accessing elements is the same as it is for accessing values in lists.

my_tuple2 = (1, 2, 3, ‘Bharath') #access elements


for x in my_tuple2:
    print(x)
print(my_tuple2)
print(my_tuple2[0])
print(my_tuple2[:])
print(my_tuple2[3][4])

Output:
1
2
3
Bharath
(1, 2, 3, ‘Bharath’)
1
(1, 2, 3, ‘Bharath’)
a
Appending Elements

• To append the values, you use the ‘+’ operator


which will take another tuple to be appended to
it.

my_tuple = (1, 2, 3)
my_tuple = my_tuple + (4, 5, 6) #add elements
print(my_tuple)

• Output:
(1, 2, 3, 4, 5, 6)
Other Functions

• These functions are the same as they are for lists.

my_tuple = (1, 2, 3, ['hindi', 'python'])


my_tuple[3][0] = 'english'
print(my_tuple)
print(my_tuple.count(2))
print(my_tuple.index(['english', 'python']))

• Output:
(1, 2, 3, [‘english’, ‘python’])
1
3
Sets

• Sets are a collection of unordered elements


that are unique.

• Meaning that even if the data is repeated more


than one time, it would be entered into the set
only once.

• It resembles the sets that have learnt in


arithmetic. The operations also are the same as
is with the arithmetic sets.
Creating a set

• Sets are created using the flower braces but


instead of adding key-value pairs, you just pass
values to it.

my_set = {1, 2, 3, 4, 5, 5, 5} #create set


print(my_set)

• Output:
{1, 2, 3, 4, 5}
Adding elements

• To add elements, you use the add() function


and pass the value to it.

my_set = {1, 2, 3}
my_set.add(4) #add element to set
print(my_set)

• Output:
{1, 2, 3, 4}
Operations in sets

my_set = {1, 2, 3, 4}
my_set_2 = {3, 4, 5, 6}
print(my_set.union(my_set_2), '----------', my_set |
my_set_2)
print(my_set.intersection(my_set_2), '----------', my_set &
my_set_2)
print(my_set.difference(my_set_2), '----------', my_set -
my_set_2)
print(my_set.symmetric_difference(my_set_2), '----------',
my_set ^ my_set_2)
my_set.clear()
print(my_set)
• Output:
{1, 2, 3, 4, 5, 6} ———- {1, 2, 3, 4, 5, 6}
{3, 4} ———- {3, 4}
{1, 2} ———- {1, 2}
{1, 2, 5, 6} ———- {1, 2, 5, 6}
set()

• The union() function combines the data present in both sets.

• The intersection() function finds the data present in both sets only.

• The difference() function deletes the data present in both and


outputs data present only in the set passed.

• The symmetric_difference() does the same as the difference()


function but outputs the data which is remaining in both sets.
User-Defined Data Structures

1) Arrays:

• Arrays and lists are the same structure with one


difference.

• Lists allow heterogeneous data element storage


whereas  Arrays  allow only homogenous elements
to be stored within them.
Stack

• Stacks are linear Data Structures which are


based on the principle of Last-In-First-Out
(LIFO) where data which is entered last will be
the first to get accessed.

• It is built using the array structure and has


operations namely, pushing (adding) elements,
popping (deleting) elements and accessing
elements only from one point in the stack called
as the TOP.
• This TOP is the pointer to the current position of
the stack.

• Stacks are prominently used in applications such


as Recursive Programming, reversing words,
undo mechanisms in word editors and so forth.
Queue

• A Queue is also a linear data structure which is


based on the principle of First-In-First-Out
(FIFO) where the data entered first will be
accessed first.

• It is built using the array structure and has


operations which can be performed from both
ends of the Queue, that is, head-tail or front-
back.
• Operations such as adding and deleting elements are called
En-Queue and De-Queue and accessing the elements can
be performed.

• Queues are used as Network Buffers for traffic congestion


management, used in Operating Systems for Job
Scheduling and many more.
Tree

• Trees are non-linear Data Structures which have root and


nodes.

• The root is the node from where the data originates and
the nodes are the other data points that are available to
us.

• The node that precedes is the parent and the node after is
called the child.

• There are levels a tree has to show the depth of


information. The last nodes are called the leaves.
• Trees create a hierarchy which can be used in a lot of
real-world applications such as the HTML pages use
trees to distinguish which tag comes under which block.

• It is also efficient in searching purposes and much more.


Linked List

• Linked List are linear Data Structures which are not


stored consequently but are linked with each other using
pointers.

• The node of a linked list is composed of data and a


pointer called next.

• These structures are most widely used in image viewing


applications, music player applications and so forth.
Graph

• Graphs are used to store data collection of points called vertices


(nodes) and edges (edges).

• Graphs can be called as the most accurate representation of a real-


world map.

• They are used to find the various cost-to-distance between the


various data points called as the nodes and hence find the least path.

• Many applications such as Google Maps, Uber, and many more use
Graphs to find the least distance and increase profits in the best
ways.
HashMaps

• HashMaps are the same as what dictionaries are in


Python.

• They can be used to implement applications such as


phonebooks, populate data according to the lists and
much more.
Control of Flow in Python
• In Python programming, flow control is the order
in which statements or blocks of code are
executed at runtime based on a condition.

• Control Flow Statements:


The flow control statements are divided
into three categories.
– Conditional statements
– Iterative statements.
– Transfer statements
Conditional statements

• In Python, condition statements act depending on


whether a given condition is true or false. You can
execute different blocks of codes depending on the
outcome of a condition. Condition statements always
evaluate to either True or False.

• There are four types of conditional statements.


– if statement
– if-else
– if-elif-else
– nested if-else
1) If statement in Python

• In control statements, The if statement is the simplest


form. It takes a condition and evaluates to either True
or False.

• If the condition is True, then the True block of code will be


executed, and if the condition is False, then the block of
code is skipped, and The controller moves to the next line.

• Syntax of the if statement:
if condition:
statement 1
statement 2
statement n
Example:
number = 6
if number > 5:
print(number * number) # Calculate square
print('Next lines of code')

Output
36
Next lines of code
2) If – else statement

• The if-else statement checks the condition and


executes the if block of code when the condition is
True, and if the condition is False, it will execute
the else block of code.

Syntax of the if-else statement:

if condition:
statement 1
else:
statement 2
Flow chart of if-else statement
Example:
password = input('Enter password ')
if password == “Mrecw@123":
print("Correct password")
else:
print("Incorrect Password")

Output 1:
Enter password Mrecw@123
Correct password
Output 2:
Enter password Mrecw@12
Incorrect Password
3) if-elif-else statement

• In Python, the if-elif-else condition statement has an elif blocks


to chain multiple conditions one after another. This is useful
when you need to check multiple conditions.

• Syntax of the if-elif-else statement:

if condition-1:
statement 1
elif condition-2:
stetement 2
elif condition-3:
stetement 3
...
else: statement
Example:

def user_check(choice):
if choice == 1: Output:
print("Admin") Admin
elif choice == 2: Editor
print("Editor") Guest
elif choice == 3: Wrong entry
print("Guest")
else: print("Wrong entry")
user_check(1)
user_check(2)
user_check(3)
user_check(4)
4) Nested if-else statement

• In Python, the nested if-else statement is an if


statement inside another if-else statement. It is
allowed in Python to put any number
of if statements in another if statement.

• Indentation is the only way to differentiate the


level of nesting. The nested if-else is useful
when we want to make a series of decisions.
Syntax of the nested-if-else:

if conditon_outer:
if condition_inner:
statement of inner if
else:
statement of inner else:
statement of outer if
else:
Outer else
statement outside if block
Example: Find a greater number between two
numbers

num1 = int(input('Enter first number '))


num2 = int(input('Enter second number '))
if num1 >= num2:
if num1 == num2:
print(num1, 'and', num2, 'are equal')
else:
print(num1, 'is greater than', num2)
else:
print(num1, 'is smaller than', num2)
Output 1:
Enter first number 56
Enter second number 15
56 is greater than 15

Output 2:
Enter first number 29
Enter second number 78
29 is smaller than 78
Single statement suites

• Whenever we write a block of code with multiple


if statements, indentation plays an important
role. But sometimes, there is a situation where
the block contains only a single line statement.

Example: Example:
x=1
number = 56 while x <= 5:
if number > 0: print(x,end=" ");
print("positive") x = x+1
else:
print("negative") Output
12345
Iterative statements

• In Python, iterative statements allow us to


execute a block of code repeatedly as long as
the condition is True. We also call it a loop
statements.

• Python provides us the following two loop


statement to perform some actions repeatedly.
1) For loop
2) while loop
1) for loop

• Using for loop, we can iterate any sequence or iterate variable.


The sequence can be string, list, dictionary, set, or tuple.

• Flow Chart of for loop:


Syntax of for loop:
for element in sequence:
body of for loop
Output:
1
2
Example: To display first ten 3
numbers using for loop 4
5
6
for i in range(1, 11): 7
print(i) 8
9
10
2) While loop

• In Python, The while loop statement


repeatedly executes a code block while a
particular condition is true.

• In a while-loop, every time the condition is


checked at the beginning of the loop, and if it
is true, then the loop’s body gets executed.
When the condition became False, the
controller comes out of the block.
Flow chart of While loop
Syntax of while-loop
while condition :
body of while loop

Example to calculate the sum of first ten numbers

num = 10
sum = 0
i=1
while i <= num:
sum = sum + I
i=i+1
print("Sum of first 10 number is:", sum)

Output
Sum of first 10 number is: 55
Transfer statements

• In Python, transfer statements are used to


alter the program’s way of execution in a
certain manner. For this purpose, we use
three types of transfer statements.

• break statement
• continue statement
• pass statements
1) Break Statement

• The break statement is used inside the loop to


exit out of the loop. It is useful when we want
to terminate the loop as soon as the
condition is fulfilled instead of doing the
remaining iterations.

• It reduces execution time. Whenever the


controller encountered a break statement, it
comes out of that loop immediately.
Example of using a break statement:
for num in range(10):
if num > 5:
print("stop processing.")
break
Output:
print(num) 0
1
2
3
4
5
stop processing.
2) Continue statement

• The continue statement is used to skip the


current iteration and continue with the next
iteration.

Example of a continue statement:
for num in range(3, 8):
Output:
if num == 5: 3
continue 4
6
else:
7
print(num)
3) Pass statement

• The pass is the keyword In Python, which won’t do


anything. Sometimes there is a situation in programming
where we need to define a syntactically empty block. We
can define that block with the pass keyword.

• A pass statement is a Python null statement. When the


interpreter finds a pass statement in the program, it
returns no operation. Nothing happens when
the pass statement is executed.

• It is useful in a situation where we are implementing new


methods or also in exception handling. It plays a role like
a placeholder.
Example:
months = ['January', 'June', 'March', 'April']
for mon in months:
pass
print(months)

Output:
['January', 'June', 'March', 'April']
Python Functions

• Python Functions is a block of related statements


designed to perform a computational, logical, or
evaluative task.

• The idea is to put some commonly or repeatedly done


tasks together and make a function so that instead of
writing the same code again and again for different
inputs, we can do the function calls to reuse code
contained in it over and over again. 

• Functions can be both built-in or user-defined. It helps


the program to be concise, non-repetitive, and organized.
Creating a Function

• We can create a Python function using


the def keyword.

Example: Python Creating Function:

# A simple Python function


def fun():
print("Welcome to MRECW")
Calling a  Function

• After creating a function we can call it by using the name


of the function followed by parenthesis containing
parameters of that particular function.

Example: Python Calling Function:

# A simple Python function


 def fun():
  print("Welcome to GFG")
         
# Driver code to call a function
fun()
Arguments of a Function

• Arguments are the values passed inside the parenthesis of the function.
• A function can have any number of arguments separated by a comma.

Example: Python Function with arguments


In this example, we will create a simple function to check whether the number
passed as an argument to the function is even or odd.

# A simple Python function to check


# whether x is even or odd
 def evenOdd(x):
    if (x % 2 == 0):
Output
        print("even") even
    else: odd
        print("odd")
 
# Driver code to call the function
evenOdd(2)
evenOdd(3)
Types of Arguments

Python supports various types of arguments that can be passed at the time of
the function call.

1) Default arguments:

A default argument is a parameter that assumes a default value, if a value


is not provided in the function call for that argument. The following
example illustrates Default arguments. 

# Python program to demonstrate default arguments


 def myFun(x, y=50):
    print("x: ", x)
Output:
    print("y: ", y) ('x: ', 10)
  ('y: ', 50)
# Driver code (We call myFun() with only argument)
myFun(10)
2) Keyword arguments

The idea is to allow the caller to specify the argument


name with values so that caller does not need to
remember the order of parameters.

#Python program to demonstrate Keyword Arguments


def student(firstname, lastname): Output:
(‘RATAN', ‘TATA')
    print(firstname, lastname)
(‘TATA', ‘RATAN')
 
# Keyword arguments
student(firstname=‘RATAN', lastname=‘TATA')
student(lastname=‘TATA', firstname=‘RATAN')
3) Variable-length arguments

In Python, we can pass a variable number of arguments to a function


using special symbols. There are two special symbols:
*args (Non-Keyword Arguments)
**kwargs (Keyword Arguments)

Example 1: Variable length non-keywords argument

# Python program to illustrate


# *args for variable number of arguments Output:
   Hello
def myFun(*argv):
Welcome
to
    for arg in argv:
MRECW
        print(arg)
  
myFun('Hello', 'Welcome', 'to', ‘MRECW‘)
Example 2: Variable length keyword arguments
# Python program to illustrate
# *kwargs for variable number of keyword
arguments
  
def myFun(**kwargs):
Output
    for key, value in kwargs.items():
first == INDIA
        print("%s == %s" % (key, value)) mid ==is
last == GREAT
  
# Driver code
myFun(first=‘INDIA', mid=‘is', last=‘GREAT')
MODULES

• A Python module is a file containing Python


definitions and statements.

• A module can define functions, classes, and variables.

• A module can also include runnable code. Grouping


related code into a module makes the code easier to
understand and use.

• It also makes the code logically organized.


• Example: create a simple module

# A simple module
 
def add(x, y):
    return (x+y)
 
def subtract(x, y):
    return (x-y)
Import Module in Python –  Import statement

• We can import the functions, classes defined


in a module to another module using
the import statement in some other Python
source file. 

Syntax:
import module
• When the interpreter encounters an import statement, it imports
the module if the module is present in the search path.

• A search path is a list of directories that the interpreter searches for


importing a module.

• For example, to import the module calc.py, we need to put the


following command at the top of the script.

# importing  module calc.py


import calc
 
print(calc.add(10, 2))

Output:
12
Python Packages

• A Python module may contain several classes, functions,


variables, etc.

• A Python package can contains several module. In simpler


terms a package is folder that contains various modules as files.

Creating Package:
• Let’s create a package named mypckg that will contain two
modules mod1 and mod2. To create this module follow the
below steps – 
– Create a folder named mypckg.
– Inside this folder create an empty Python file i.e. __init__.py
– Then create two modules mod1 and mod2 in this folder.
Mod1.py

def gfg():
    print("Welcome to MRECW")

Mod2.py 
def sum(a, b):
    return a+b

Import Module from package

from mypckg import mod1


from mypckg import mod2
 
mod1.gfg()
res = mod2.sum(1, 2)
print(res)

Output:
Welcome to MRECW
3
File Handling in Python

• Python too supports file handling and allows users to handle files
i.e., to read and write files, along with many other file handling
options, to operate on files. 

• Python treats file differently as text or binary and this is


important.

• Each line of code includes a sequence of characters and they form


text file. Each line of a file is terminated with a special character,
called the EOL or End of Line characters like comma {,} or
newline character.

• It ends the current line and tells the interpreter a new one has
begun.
Opening of a File
• Before performing any operation on the file like read or write, first we have
to open that file. For this, we should use Python’s inbuilt function open().

• But at the time of opening, we have to specify the mode, which represents
the purpose of the opening file.

• f = open(filename, mode)

• Where the following mode is supported:


• r: open an existing file for a read operation.
• w: open an existing file for a write operation. If the file already contains
some data then it will be overridden.
• a:  open an existing file for append operation. It won’t override existing
data.
•  r+:  To read and write data into the file. The previous data in the file will
not be deleted.
• w+: To write and read data. It will override existing data.
• a+: To append and read data from the file. It won’t override existing data.
Example:
1) Working of open() function
2) # a file named “mrecw", will be opened with the
reading mode.
file = open(‘mrecw.txt', 'r')
# This will print every line one by one in the file
for each in file:
    print (each)

2) Working of read() mode


# Python code to illustrate read() mode
file = open("file.txt", "r")
print (file.read())
3)
# Python code to illustrate read() mode character
wise
file = open("file.txt", "r")
print (file.read(5))

4) Creating a file using write() mode


# Python code to create a file
file = open(‘mrecw.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
5) Working of append() mode
# Python code to illustrate append() mode
file = open('geek.txt','a')
file.write("This will add this line")
file.close()
Python Exception Handling

• Error in Python can be of two types i.e. Syntax


errors and Exceptions.

• Errors are the problems in a program due to


which the program will stop the execution.

• Exceptions are raised when some internal


events occur which changes the normal flow
of the program. 
Difference between Syntax Error and Exceptions
Syntax Error: As the name suggests this error is caused by the wrong
syntax in the code. It leads to the termination of the program. 
Example: 
# initialize the amount variable
amount = 10000
 
# check that You are eligible to
#  purchase Dsa Self Paced or not
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")

Output:
Exceptions: Exceptions are raised when the program is syntactically
correct, but the code resulted in an error. This error does not stop the
execution of the program, however, it changes the normal flow of the
program.
Example:
# initialize the amount variable
marks = 10000
 
# perform division with 0
a = marks / 0
print(a)

Output:
Try and Except Statement – Catching Exceptions
Try and except statements are used to catch and handle exceptions in Python.
Statements that can raise exceptions are kept inside the try clause and the
statements that handle the exception are written inside except clause.
Example: Let us try to access the array element whose index is out of bound and handle
the corresponding exception.
# Python program to handle simple runtime error
 a = [1, 2, 3]

try:
    print ("Second element = %d" %(a[1]))
     # Throws error since there are only 3 elements in array
    print ("Fourth element = %d" %(a[3]))
 
except:
    print ("An error occurred")

Output:
Second element = 2
An error occurred
Python Packages
Python Packages of Interest for IoT are

1) JSON
2) XML
3) HTTPLib
4) URLLib
5) SMTPLib
1) JSON:
• JavaScript Object Notation (JSON) is an easy to read and write data-
interchange format.

• JSON is used as an alternative to XML and is easy for machines to


parse and generate.

• JSON is built on two structures: a collection of name–value pairs (e.g.,


a Python dictionary) and ordered lists of values (e.g., a Python list).

2) XML :
• XML (Extensible Markup Language) is a data format for structured
document interchange.

• The Python minidom library provides a minimal implementation of the


Document Object Model interface and has an API similar to that in
other languages.
3) HTTPLib & URLLib :
• HTTPLib2 (Hyper Text Transfer Protocol) and
URLLib2 (Uniform Resource Locator) are Python
libraries used in network/internet programming.

4) SMTPLib:
• Simple Mail Transfer Protocol (SMTP) is a protocol
which handles sending email and routing email
between mail servers.

• The Python SMTPLib module provides an SMTP


client session object that can be used to send email.

You might also like