Python programming concepts for the Internet of things applications development. This PPT contains details about classes, list , tuples, dictionaries, packages like HTTPLib,SMTPLib, etc
The slides defines IoT and show the differnce between M2M and IoT vision. It then describes the different layers that depicts the functional architecture of IoT, standard organizations and bodies and other IoT technology alliances, low power IoT protocols, IoT Platform components, and finally gives a short description to one of IoT low power application protocols (MQTT).
The slides defines IoT and show the differnce between M2M and IoT vision. It then describes the different layers that depicts the functional architecture of IoT, standard organizations and bodies and other IoT technology alliances, low power IoT protocols, IoT Platform components, and finally gives a short description to one of IoT low power application protocols (MQTT).
The Internet of things describes physical objects that are embedded with sensors, processing ability, software, and other technologies that connect and exchange data with other devices and systems over the Internet or other communications networks.
Internet of Things means every household or handy device which is used to make our world easy and better and connected with IP which transmit some data.
This slide covers IOT description, OWASP Top 10 2014 & its recommendations.
The Internet of things describes physical objects that are embedded with sensors, processing ability, software, and other technologies that connect and exchange data with other devices and systems over the Internet or other communications networks.
Internet of Things means every household or handy device which is used to make our world easy and better and connected with IP which transmit some data.
This slide covers IOT description, OWASP Top 10 2014 & its recommendations.
ZENUS INFOTECH is best Python Training institute in Roorkee and an ISO 9001:2008 Certified Engineer’s Training Company in Roorkee & provides training to the B.E./B.TECH/DIPLOMA/MCA/BCA and related field students in 35+ cutting-edge technologies like AutoCAD, Solid-Works, CATIA, REVIT, Pro-E, UG-NX .NET, JAVA, PHP, GST Tally and Wireless & Telecommunication and many more.
Python Mastery: A Comprehensive Guide to Setting Up Your Development EnvironmentPython Devloper
**Module 1: Python Environment Setup Essentials**
Python, with its versatility and ease of use, has become a powerhouse in various domains, from web development to data science. Before diving into the fascinating world of Python programming, it's crucial to set up the right environment. This module serves as a comprehensive guide to ensure a seamless and efficient Python environment setup.
**1.1 Understanding Python Environments**
Python offers multiple environments to cater to diverse development needs. The choice between Python 2 and Python 3, as well as the decision between Anaconda and the standard Python distribution, depends on project requirements. This section provides a nuanced understanding of these options, enabling developers to make informed decisions.
**1.2 Installing Python**
The first step in setting up a Python environment is installing the interpreter. This module guides users through the installation process, whether on Windows, macOS, or Linux. It covers best practices, troubleshooting common installation issues, and ensuring a clean, stable Python installation.
**1.3 Virtual Environments**
Virtual environments are indispensable for managing dependencies and isolating project environments. This section explores the creation, activation, and deactivation of virtual environments using tools like `venv` or `virtualenv`. It emphasizes the importance of encapsulating project dependencies to avoid conflicts and ensure reproducibility.
**1.4 Package Management with pip**
The Python Package Index (PyPI) is a treasure trove of libraries and tools. Understanding how to use the `pip` package manager is crucial for installing, upgrading, and managing project dependencies. This section delves into pip commands, requirement files, and strategies for version management to maintain a stable and consistent development environment.
**1.5 Integrated Development Environments (IDEs)**
Choosing the right IDE can significantly enhance productivity. This module explores popular Python IDEs like PyCharm, VSCode, and Jupyter Notebooks. It covers installation, basic configuration, and features that cater to different development styles, whether it's web development, data science, or general-purpose coding.
**1.6 Version Control Integration**
Version control is a developer's best friend. This section demonstrates how to integrate Python projects with version control systems like Git. From initializing a repository to committing changes and collaborating with a team, developers learn essential version control practices to streamline their workflow.
**1.7 Configuration and Customization**
Tailoring the Python environment to individual preferences is an often-overlooked aspect of setup. This part of the module covers customizing the Python shell, configuring environment variables, and optimizing settings in IDEs. A personalized environment can significantly enhance the development experience.
**1.8 Troubleshooting and Common Pitfalls**
No s
Kosmik is the best institute for Python training in Hyderabad Kukatpally/KPHB. kosmik provides lab facilities with complete real-time training with live sessions
call now: +91-8712186898, +91-8179496603, +91-6309565721
Today, Python is one of the most popular programming languages. Although it is a general-purpose language, it is used in various areas of applications such as Machine Learning, Artificial Intelligence, web development, IoT, and more.
Slides from Phil Pennington\'s talk on Using Parallel Computing with Visual Studio 2010 and .NET 4.0, originally presented at the North Houston .NET Users Group (facebook.com/nhdnug).
This PPT is very much useful for practitioners who are all making products and services to society. Mangers think innovatively and come up with innovative ideas. It is a 5 stage processing also called a design thinking process. The stages are empathize, define, ideate, prototype and test.
Understanding Inductive Bias in Machine LearningSUTEJAS
This presentation explores the concept of inductive bias in machine learning. It explains how algorithms come with built-in assumptions and preferences that guide the learning process. You'll learn about the different types of inductive bias and how they can impact the performance and generalizability of machine learning models.
The presentation also covers the positive and negative aspects of inductive bias, along with strategies for mitigating potential drawbacks. We'll explore examples of how bias manifests in algorithms like neural networks and decision trees.
By understanding inductive bias, you can gain valuable insights into how machine learning models work and make informed decisions when building and deploying them.
6th International Conference on Machine Learning & Applications (CMLA 2024)ClaraZara1
6th International Conference on Machine Learning & Applications (CMLA 2024) will provide an excellent international forum for sharing knowledge and results in theory, methodology and applications of on Machine Learning & Applications.
Using recycled concrete aggregates (RCA) for pavements is crucial to achieving sustainability. Implementing RCA for new pavement can minimize carbon footprint, conserve natural resources, reduce harmful emissions, and lower life cycle costs. Compared to natural aggregate (NA), RCA pavement has fewer comprehensive studies and sustainability assessments.
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdffxintegritypublishin
Advancements in technology unveil a myriad of electrical and electronic breakthroughs geared towards efficiently harnessing limited resources to meet human energy demands. The optimization of hybrid solar PV panels and pumped hydro energy supply systems plays a pivotal role in utilizing natural resources effectively. This initiative not only benefits humanity but also fosters environmental sustainability. The study investigated the design optimization of these hybrid systems, focusing on understanding solar radiation patterns, identifying geographical influences on solar radiation, formulating a mathematical model for system optimization, and determining the optimal configuration of PV panels and pumped hydro storage. Through a comparative analysis approach and eight weeks of data collection, the study addressed key research questions related to solar radiation patterns and optimal system design. The findings highlighted regions with heightened solar radiation levels, showcasing substantial potential for power generation and emphasizing the system's efficiency. Optimizing system design significantly boosted power generation, promoted renewable energy utilization, and enhanced energy storage capacity. The study underscored the benefits of optimizing hybrid solar PV panels and pumped hydro energy supply systems for sustainable energy usage. Optimizing the design of solar PV panels and pumped hydro energy supply systems as examined across diverse climatic conditions in a developing country, not only enhances power generation but also improves the integration of renewable energy sources and boosts energy storage capacities, particularly beneficial for less economically prosperous regions. Additionally, the study provides valuable insights for advancing energy research in economically viable areas. Recommendations included conducting site-specific assessments, utilizing advanced modeling tools, implementing regular maintenance protocols, and enhancing communication among system components.
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesChristina Lin
Traditionally, dealing with real-time data pipelines has involved significant overhead, even for straightforward tasks like data transformation or masking. However, in this talk, we’ll venture into the dynamic realm of WebAssembly (WASM) and discover how it can revolutionize the creation of stateless streaming pipelines within a Kafka (Redpanda) broker. These pipelines are adept at managing low-latency, high-data-volume scenarios.
We have compiled the most important slides from each speaker's presentation. This year’s compilation, available for free, captures the key insights and contributions shared during the DfMAy 2024 conference.
HEAP SORT ILLUSTRATED WITH HEAPIFY, BUILD HEAP FOR DYNAMIC ARRAYS.
Heap sort is a comparison-based sorting technique based on Binary Heap data structure. It is similar to the selection sort where we first find the minimum element and place the minimum element at the beginning. Repeat the same process for the remaining elements.
Forklift Classes Overview by Intella PartsIntella Parts
Discover the different forklift classes and their specific applications. Learn how to choose the right forklift for your needs to ensure safety, efficiency, and compliance in your operations.
For more technical information, visit our website https://intellaparts.com
Online aptitude test management system project report.pdfKamal Acharya
The purpose of on-line aptitude test system is to take online test in an efficient manner and no time wasting for checking the paper. The main objective of on-line aptitude test system is to efficiently evaluate the candidate thoroughly through a fully automated system that not only saves lot of time but also gives fast results. For students they give papers according to their convenience and time and there is no need of using extra thing like paper, pen etc. This can be used in educational institutions as well as in corporate world. Can be used anywhere any time as it is a web based application (user Location doesn’t matter). No restriction that examiner has to be present when the candidate takes the test.
Every time when lecturers/professors need to conduct examinations they have to sit down think about the questions and then create a whole new set of questions for each and every exam. In some cases the professor may want to give an open book online exam that is the student can take the exam any time anywhere, but the student might have to answer the questions in a limited time period. The professor may want to change the sequence of questions for every student. The problem that a student has is whenever a date for the exam is declared the student has to take it and there is no way he can take it at some other time. This project will create an interface for the examiner to create and store questions in a repository. It will also create an interface for the student to take examinations at his convenience and the questions and/or exams may be timed. Thereby creating an application which can be used by examiners and examinee’s simultaneously.
Examination System is very useful for Teachers/Professors. As in the teaching profession, you are responsible for writing question papers. In the conventional method, you write the question paper on paper, keep question papers separate from answers and all this information you have to keep in a locker to avoid unauthorized access. Using the Examination System you can create a question paper and everything will be written to a single exam file in encrypted format. You can set the General and Administrator password to avoid unauthorized access to your question paper. Every time you start the examination, the program shuffles all the questions and selects them randomly from the database, which reduces the chances of memorizing the questions.
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...ssuser7dcef0
Power plants release a large amount of water vapor into the
atmosphere through the stack. The flue gas can be a potential
source for obtaining much needed cooling water for a power
plant. If a power plant could recover and reuse a portion of this
moisture, it could reduce its total cooling water intake
requirement. One of the most practical way to recover water
from flue gas is to use a condensing heat exchanger. The power
plant could also recover latent heat due to condensation as well
as sensible heat due to lowering the flue gas exit temperature.
Additionally, harmful acids released from the stack can be
reduced in a condensing heat exchanger by acid condensation. reduced in a condensing heat exchanger by acid condensation.
Condensation of vapors in flue gas is a complicated
phenomenon since heat and mass transfer of water vapor and
various acids simultaneously occur in the presence of noncondensable
gases such as nitrogen and oxygen. Design of a
condenser depends on the knowledge and understanding of the
heat and mass transfer processes. A computer program for
numerical simulations of water (H2O) and sulfuric acid (H2SO4)
condensation in a flue gas condensing heat exchanger was
developed using MATLAB. Governing equations based on
mass and energy balances for the system were derived to
predict variables such as flue gas exit temperature, cooling
water outlet temperature, mole fraction and condensation rates
of water and sulfuric acid vapors. The equations were solved
using an iterative solution technique with calculations of heat
and mass transfer coefficients and physical properties.
2. Contents
• Language Features of Python
• Data Types
• Data Structures
• Control of Flow
• Functions
• Modules
• Packaging
• File Handling
• Date/Time Operations
• Classes
• Exception Handling
• Python Packages – HTTPLib,URLLib,SMTPLib
1/7/2021 Python for IoT 2
3. Python Conquers the Universe
• Most widely used high level programming language across the world
1/7/2021 Python for IoT 3
4. Introduction
• Python is a general-purpose interpreted,
interactive, object-oriented and high-level
programming language
• It was created by Guido van Rossum during 1985-
1990
• Like Perl, Python source code is also available
under the GNU General Public License (GPL)
• Extension of python program is .py
• Applications:
– Develop simple text processing to www applications,
even games.
1/7/2021 Python for IoT 4
7. Features
• Easy to learn
• Easy to read
• Easy to maintain
• Broad standard library
• Interactive
• Portable (Many hardware platforms)
• Extendable
• Databases
• GUI programming
• Scalable
1/7/2021 Python for IoT 7
8. Modes of Programming
• Interactive Mode Programming
– Invoking the interpreter without passing a script
file as a parameter
• Script Mode Programming
– Invoking the interpreter with a script parameter
begins execution of the script and continues until
the script is finished
1/7/2021 Python for IoT 8
10. Programming Rules
• Quotation
– accepts single (') and double (") quotes to denote string literals
– Example:
• word = 'word‘
• sentence = "This is a sentence."
• Comments
– A hash sign (#) that is not inside a string literal begins a
comment
– Example:
• # First comment
• Multiple Statements on a Single Line
– semicolon ( ; ) allows multiple statements on the single line
1/7/2021 Python for IoT 10
11. Lines and Indentation
• Python provides no braces to indicate blocks
of code for class and function definitions or
flow control
• Example:
1/7/2021 Python for IoT 11
13. Python Identifiers
• Identifier is a name used to identify a variable,
function, class, module or other object
• Case sensitive programming language
• Naming conventions:
– Class names start with an uppercase letter
– All other identifiers start with a lowercase letter
– Starting an identifier with a single leading
underscore indicates that the identifier is private
1/7/2021 Python for IoT 13
16. Variables
• Variables are nothing but reserved memory
locations to store values
• Assigning Values to Variables
– Variables do not need explicit declaration to
reserve memory space
– The declaration happens automatically when you
assign a value to a variable
– The equal sign (=) is used to assign values to
variables.
1/7/2021 Python for IoT 16
17. Multiple Assignment
• Python allows you to assign a single value to
several variables simultaneously
– a = b = c = 1
– a, b, c = 1, 2, "john"
1/7/2021 Python for IoT 17
18. Input Methods
• Two Methods:
– raw_input function:
Syntax:
varname=raw_input(“Prompt”);
– input function:
Syntax:
varname=input(“Prompt”);
– Example:
a=int(raw_input('Enter number 1'))
b=int(raw_input('Enter number 2'))
c=a+b
print "sum=",c
1/7/2021 Python for IoT 18
19. Output statements
• print function:
Syntax:
print(“Message”) // used in python 3.4
print “Message” // used in python 2.7
• Example:
print ("Hello World“)
a=10
print ("The Value of a=",a)
b=20.5
print ("The Value of b = %d" %b)
print ("The Value of b = %f" %b)
print ("The Value of b = %g" %b)
print ("The Value of b = %3.2f" %b)
1/7/2021 Python for IoT 19
22. Contents
• Language Features of Python
• Data Types
• Data Structures
• Control of Flow
• Functions
• Modules
• Packaging
• File Handling
• Date/Time Operations
• Classes
• Exception Handling
• Python Packages – HTTPLib,URLLib,SMTPLib
1/7/2021 Python for IoT 22
23. Standard Data Types
• Numbers
• String
• List
• Tuple
• Dictionary
1/7/2021 Python for IoT 23
24. Numbers
• Number data types store numeric values
• Python supports four different numerical
types −
– int (signed integers)
– long (long integers, they can also be represented
in octal and hexadecimal)
– float (floating point real values)
– complex (complex numbers)
1/7/2021 Python for IoT 24
25. Strings
• Contiguous set of characters represented in
the quotation marks
• Subsets of strings can be taken using the slice
operator ([ ] and [:] )
• Indexing and Slicing ([ ] and [:] )
• The plus (+) sign is the string concatenation
operator and the asterisk (*) is the repetition
operator
1/7/2021 Python for IoT 25
27. Lists
• Compound data type
• A list contains items separated by commas
and enclosed within square brackets
• Lists are similar to arrays in C.
• Difference - a list can be of different data type
• Accessed using the slice operator ([ ] and [:])
with indexes
• (+) sign is the list concatenation operator, (*) is
the repetition operator
1/7/2021 Python for IoT 27
29. Tuples
• A tuple is another sequence data type that is
similar to the list
• A tuple consists of a number of values
separated by commas
• Unlike lists, however, tuples are enclosed
within parentheses
• Tuples can be thought of as read-only lists
1/7/2021 Python for IoT 29
33. Dictionary
• Hash table type
• Work like associative arrays or hashes - consist
of key-value pairs.
• Key - any Python type, but are usually
numbers or strings
• Enclosed by curly braces ({ }) and values can
be assigned and accessed using square braces
([])
1/7/2021 Python for IoT 33
42. Membership Operators
• Python’s membership operators test for
membership in a sequence, such as strings,
lists, or tuples
1/7/2021 Python for IoT 42
51. If Statement
• Syntax of If Statement
– if (test_expression):
Statement 1
..........
Statement n
Statement x
• Example:
x = 10
if(x>0):
x= x+1
Print(x)
1/7/2021 Python for IoT 51
52. If – Else Statement
• Syntax of If-else Statement
– if (test_expression):
Statement Block 1
else:
Statement Block 2
Statement x
• Example:
age = 19
if(age>=18):
print(“You are Eligible to vote”)
else:
print(“Not Eligible”)
1/7/2021 Python for IoT 52
53. Nested if Statement
• To perform more complex checks if statement can be nested.
• If statements can be nested resulting in multi-way selection.
• Example:
avg = 50
If (avg<=100 and avg>90):
print(“Grade S”)
If (avg<=90 and avg>80):
print(“Grade A”)
If (avg<=80 and avg>70):
print(“Grade B”)
If (avg<=70 and avg>60):
print(“Grade C”)
If (avg<=60 and avg>50):
print(“Grade D”)
If (avg<=50):
print(“Grade E”)
Else:
print(“Grade RA”)
1/7/2021 Python for IoT 53
54. If-elif-else Statement
• Python does not have switch statement. You can use an if...elif...else
statement to do the same thing.
• Elif is an short for else if.
• Syntax of If-elif-else Statement
– if (test_expression 1):
Statement Block 1
elif (test_expression 2):
Statement Block 2
.........................
elif (test_expression n):
Statement Block n
Else:
Statement Block x
Statement y
1/7/2021 Python for IoT 54
55. Loops
• A loop statement allows us to execute a
statement or group of statements multiple
times
• Examples:
– While
– for
– nested loops
1/7/2021 Python for IoT 55
57. Using else Statement with Loops
• Supports else statement associated with a
loop.
• Example:
1/7/2021 Python for IoT 57
58. for Loop
• Syntax:
for iterating_var in sequence:
statements(s)
• Example:
1/7/2021 Python for IoT 58
Output:
59. The range() function
• Syntax for range () function
– range(start, stop, step)
• Example 1:
– For i in range(10):
print(i, end=“,”)
– Output: 0,1,2,3,4,5,6,7,8,9,
• Example 2:
– For i in range(1,5):
print(i, end=“,”)
– Output: 1,2,3,4,
• Example 3:
– For i in range(1,10,2):
print(i, end=“,”)
– Output: 1,3,5,7,9,
1/7/2021 Python for IoT 59
64. Functions
• A function is a block of organized and reusable code
• Modularity
• Types:
– Built-in functions
– User defined functions
• Rules:
– first statement of a function can be an optional statement -
the documentation string of the function or docstring.
– statement return [expression] exits a function, optionally
passing back an expression to the caller. A return
statement with no arguments is the same as return None
1/7/2021 Python for IoT 64
66. Calling a Function
• All parameters (arguments) in the Python
language are passed by reference.
• It means if you change what a parameter
refers to within a function, the change also
reflects back in the calling function.
1/7/2021 Python for IoT 66
67. Function Arguments
• Call a function by using the following types of
formal arguments:
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
1/7/2021 Python for IoT 67
68. Required arguments
• Required arguments are the arguments
passed to a function in correct positional
order
1/7/2021 Python for IoT 68
69. Keyword arguments
• The caller identifies the arguments by the
parameter name
• Python interpreter is able to use the keywords
provided to match the values with parameters
1/7/2021 Python for IoT 69
70. Default arguments
• A default argument is an argument that
assumes a default value if a value is not
provided in the function call for that argument
1/7/2021 Python for IoT 70
71. Variable-length arguments
• Call a function with variable number of arguments.
• Example:
def customer_details(cust_name,*var_tuple):
print(“This function prints Customer Names:”)
print(“Customer name:”,cust_name)
for var in var_tuple:
print(var)
return
customer_details (“John”,”Jim”,”Harry”,” Kerber”)
This function prints Customer Names
Customer name:John
Jim
Harry
Kerber
customer_details (“Mary”)
This function prints Customer Names
Customer name: Mary
1/7/2021 Python for IoT 71
72. Global vs. Local variables
• Variables that are defined inside a function
body have a local scope
• Variables defined outside have a global scope.
1/7/2021 Python for IoT 72
75. Python Modules
• Used to logically organize code
• Grouping related code into a module
• Module is a file consisting of Python code
• It can define functions, classes and variables
1/7/2021 Python for IoT 75
76. Example
Save this in sample1.py
import math;
def fact(n):
f=1;
for i in range(1, n+1):
f=f*i;
return f;
def power(a,b):
p=math.pow(a, b)
return p;
1/7/2021 Python for IoT 76
77. The import Statement
• You can use any Python source file as a
module by executing an import statement in
some other Python source file.
• import module1[, module2[,... moduleN]
1/7/2021 Python for IoT 77
79. The from...import Statement
• Python's from statement lets you import specific
attributes from a module into the current
namespace
• Syntax:
from modname import name1[, name2[, ...
nameN]]
Example:
from sample1 import power;
f=power(5,3);
print "Power is =", f;
1/7/2021 Python for IoT 79
80. The from...import * Statement:
• It is also possible to import all names from a
module into the current namespace by using
the following import statement −
from modname import *
1/7/2021 Python for IoT 80
81. Locating Modules
• When you import a module, the Python
interpreter searches for the module in the
following sequences −
– The current directory
– If the module isn't found, Python then searches
each directory in the shell variable PYTHONPATH
– If all else fails, Python checks the default path.
– On UNIX, this default path is normally
/usr/local/lib/python/.
1/7/2021 Python for IoT 81
82. Packages
• Package is a hierarchical file structure that consists of
modules and subpackages.
• Packages allow better organization of modules related
to a single application environment.
• Each package in python is a directory which must have
a special file called _init_.py
• This file may not even have a single line of code.
• It is simply added to indicate that this directory is not
an ordinary directory and contains a python package.
1/7/2021 Python for IoT 82
84. Files I/O
• Opening and Closing Files
– Syntax:
– file object = open(file_name [, access_mode][, buffering])
– access_mode - read, write, append, read and write(r+ or w+), read-binary(rb),
write-binary(wb), etc.
– If the buffering value is set to 0, no buffering takes place.
– If the buffering value is 1, line buffering is performed while accessing a file.
– If the buffering value is an integer greater than 1, then buffering is performed
with the indicated buffer size
– Example:
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
1/7/2021 Python for IoT 84
85. The close() Method
• close() method of a file object flushes any
unwritten information an
• Syntax
– fileObject.close();
1/7/2021 Python for IoT 85
86. Reading and Writing Files
• write() method writes any string to an open
file
• Example:
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.nYeah its
great!!n");
fo.close()
1/7/2021 Python for IoT 86
87. The read() Method
• The read()
• Syntax
– fileObject.read([count]);
Example:
– fo = open("foo.txt", "r+")
– str = fo.read(10);
– print "Read String is : ", str
– fo.close()
1/7/2021 Python for IoT 87
89. Renaming and Deleting Files
• Python os module provides methods that help
you perform file-processing operations, such
as renaming and deleting files.
1/7/2021 Python for IoT 89
92. Date & Time
• Python's time and calendar modules help track dates
and times
• time module provides functions for working with times
and for converting between representations
• Function time.time() returns the current system time in
ticks since 12:00am, January 1, 1970
1/7/2021 Python for IoT 92
96. Getting calendar for a month
• The calendar module gives a wide range of methods to
manipulate with yearly and monthly calendars
1/7/2021 Python for IoT 96
97. Time -clock() Method
• clock() returns the current processor time
as a floating point number expressed in
seconds
• Example:
import time;
print (time.clock())
time.sleep(20.5)
print (time.clock())
1/7/2021 Python for IoT 97
98. Classes
• Python is an OOP Language.
• Python provides all the standard features of
OOP
1/7/2021 Python for IoT 98
99. OOP Concepts:
• Class
• Object
• Class variable
• Data member
• Method
• Instance variable
• Inheritance
• Instantiation
• Function overloading
• Operator overloading
1/7/2021 Python for IoT 99
100. Class and Instance/Object
• Class is simply a representation of type of
object and user-defined prototype for an
object that is composed of three things:
– Name
– Attributes
– Operations/Methods
• Object is an instance of the data structure
defined by a class.
1/7/2021 Python for IoT 100
105. Class Inheritance
• It is the process of forming a new class from
an existing class or base class.
• Instead of starting from scratch, you can
create a class by deriving it from a preexisting
class
• The child class inherits the attributes of its
parent class
• Syntax:
1/7/2021 Python for IoT 105
107. Function Overloading and Operator
Overloading
• Function overloading is a form of
polymorphism that allows a function to have
different meaning, depending on its context.
• Operator overloading is form of polymorphism
that allows assignment of more than one
function to a particular operator.
1/7/2021 Python for IoT 107
108. Overriding Methods
• Function overriding allows a child class to provide a specific
implementation of a function that is already provided by the base
class.
• It has the same name, parameters and return type as the function
in the base class.
• Override parent class methods.
• Reason – To give special or different functionality in subclass
1/7/2021 Python for IoT 108
110. Exceptions Handling
• Errors detected during execution are
called exceptions
• The try block lets you test a block of code for
errors.
• The except block lets you handle the error.
• The finally block lets you execute code,
regardless of the result of the try- and except
blocks.
1/7/2021 Python for IoT 110
113. Exceptions- Example2
while True:
try:
x = int(raw_input("Please enter a number:
"))
break
except ValueError:
print "That was not valid number. Try
again..."
print "Number is correct!"
1/7/2021 Python for IoT 113
114. Python Packages – HTTPLib,URLLib,SMPTLib
• HTTPLib2 and URLLib2 are python libraries
used in network/internet programming.
• HTTPLib2 is an HTTP client library
• URLLib2 is a library for fetching URLs.
1/7/2021 Python for IoT 114
118. SMTPLib
• Simple Mail Transfer Protocol (SMTP) is a
protocol which handles sending email and
routing e-mail between mail server.
• Python smtplib module provides an SMTP
client session object that can be used to send
email.
• ‘message’ contains the email message to be
sent.
1/7/2021 Python for IoT 118
122. Sample Code 1
def myfunc(a):
a = a + 2
a = a * 2
return a
print myfunc(2)
1/7/2021 Python for IoT 122
a) 8
b) 16
c) Indentation Error
d) Runtime Error
Ans: ?
123. Sample Code 2
What is the output of the expression : 3*1**3
1/7/2021 Python for IoT 123
a) 27
b) 9
c) 3
d) 1
Ans: ?
124. Sample Code 3
i = 0
while i < 3:
print i
i += 1
else:
print 0
1/7/2021 Python for IoT 124
a) 0 1 2 3 0
b) 0 1 2 0
c) 0 1 2
d) Error
Ans: ?
125. Sample Code 4
1/7/2021 Python for IoT 125
a) 12
b) 24
c) 48
d) Error
Ans: ?
r = lambda q: q * 2
s = lambda q: q * 3
x = 2
x = r(x)
x = s(x)
x = r(x)
print x
126. Sample Code 5
a = 4.5
b = 2
c = a/b
d = a//b
a = d
print (a,b,c,d)
1/7/2021 Python for IoT 126
a) 4.5 2 2.25 2.0
b) 4.5 2 2.0 2.25
c) 2.0 2 2.25 2.0
d) 2 2 2.25 2.0
Ans: ?
127. Sample Code 6
list = [1,2,3,4,5,6,7,8]
print (list[1:5])
print (list[-2])
1/7/2021 Python for IoT 127
a) 1,2,3,4,5 7
b) 2,3,4,5,6 7
c) 2,3,4,5 7
d) 2,3,4,5 6
e) 1,2,3,4,5 6
f) 2,3,4,5,6 6
Ans: ?
128. Sample Code 7
class A(object):
val = 1
class B(A):
pass
class C(A):
pass
print A.val, B.val, C.val
B.val = 2
print A.val, B.val, C.val
A.val = 3
print A.val, B.val, C.val
1/7/2021 Python for IoT 128
a) 1 1 1
1 2 1
3 3 3
b) 1 1 1
1 2 1
3 2 3
c) 1 1 1
2 2 2
3 2 3
d) 1 1 1
2 2 2
3 3 3
Ans: ?
129. Sample Code 8
nameList = ['Harsh', 'Pratik', 'Bob', 'Dhruv']
print nameList[1][-1]
1/7/2021 Python for IoT 129
a) Dhruv
b) Bob
c) v
d) Pratik
e) k
f) b
Ans: ?
130. Sample Code 9
data = 50
try:
data = data/10
except ZeroDivisionError:
print('Cannot divide by 0 ', end = '')
finally:
print('GeeksforGeeks ', end = '')
else:
print('Division successful ', end = '')
1/7/2021 Python for IoT 130
a) Runtime error
b) Cannot divide by 0 GeeksforGeeks
c) GeeksforGeeks Division successful
d) GeeksforGeeks
Ans: ?
131. Sample Code 10
• data = 50
• try:
• data = data/0
• except ZeroDivisionError:
• print('Cannot divide by 0 ', end = '')
• else:
• print('Division successful ', end = '')
•
• try:
• data = data/5
• except:
• print('Inside except block ', end = '')
• else:
• print('GFG', end = '')
1/7/2021 Python for IoT 131
a) Cannot divide by 0 GFG
b) Cannot divide by 0
c) Cannot divide by 0 Inside except block GFG
d) Cannot divide by 0 Inside except block
Ans: ?