This document provides an introduction to the Python programming language. It covers Python's background, syntax, types, operators, control flow, functions, classes, tools, and IDEs. Key points include that Python is a multi-purpose, object-oriented language that is interpreted, strongly and dynamically typed. It focuses on readability and has a huge library of modules. Popular Python IDEs include Emacs, Vim, Komodo, PyCharm, and Eclipse.
Variables & Data Types In Python | EdurekaEdureka!
YouTube Link: https://youtu.be/6yrsX752CWk
(** Python Certification Training: https://www.edureka.co/python **)
This Edureka PPT on 'Variables and Data Types in Python' will help you establish a foothold on Python by helping you learn basic concepts like variables and data types. Below are the topics covered in this PPT:
Introduction To Python
Applications Of Python
Variable Declaration
Variable Data Types
Type Conversion
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
This presentation provides the information on python including the topics Python features, applications, variables and operators in python, control statements, numbers, strings, print formatting, list and list comprehension, dictionaries, tuples, files, sets, boolean, mehtods and functions, lambda expressions and a sample project using Python.
Variables & Data Types In Python | EdurekaEdureka!
YouTube Link: https://youtu.be/6yrsX752CWk
(** Python Certification Training: https://www.edureka.co/python **)
This Edureka PPT on 'Variables and Data Types in Python' will help you establish a foothold on Python by helping you learn basic concepts like variables and data types. Below are the topics covered in this PPT:
Introduction To Python
Applications Of Python
Variable Declaration
Variable Data Types
Type Conversion
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
This presentation provides the information on python including the topics Python features, applications, variables and operators in python, control statements, numbers, strings, print formatting, list and list comprehension, dictionaries, tuples, files, sets, boolean, mehtods and functions, lambda expressions and a sample project using Python.
This is the basic introduction of the pandas library, you can use it for teaching this library for machine learning introduction. This slide will be able to help to understand the basics of pandas to the students with no coding background.
( ** Python Certification Training: https://www.edureka.co/python ** )
This Edureka PPT on Tkinter tutorial covers all the basic aspects of creating and making use of your own simple Graphical User Interface (GUI) using Python. It establishes all of the concepts needed to get started with building your own user interfaces while coding in Python.
In this PPT you will learn how to use looping in python.
For more presentation in any subject please contact us on
raginijain0208@gmail.com.
You get a new presentation every Sunday at 10 AM.
Learn more about Python by clicking on given below link
Python Introduction- https://www.slideshare.net/RaginiJain21/final-presentation-on-python
Basic concept of Python -https://www.slideshare.net/RaginiJain21/python-second-ppt
Python Datatypes - https://www.slideshare.net/RaginiJain21/data-types-in-python-248466302
Python Library & Module - https://www.slideshare.net/RaginiJain21/python-libraries-and-modules
Basic Python Programs- https://www.slideshare.net/RaginiJain21/basic-python-programs
Python Media Libarary - https://www.slideshare.net/RaginiJain21/python-media-library
This Edureka Python Programming tutorial will help you learn python and understand the various basics of Python programming with examples in detail. Below are the topics covered in this tutorial:
1. Python Installation
2. Python Variables
3. Data types in Python
4. Operators in Python
5. Conditional Statements
6. Loops in Python
7. Functions in Python
8. Classes and Objects
Creating Your First Predictive Model In PythonRobert Dempsey
If you’ve been reading books and blog posts on machine learning and predictive analytics and are still left wondering how to create a predictive model and apply it to your own data, this presentation will give you the steps you need to take to do just that.
This is the basic introduction of the pandas library, you can use it for teaching this library for machine learning introduction. This slide will be able to help to understand the basics of pandas to the students with no coding background.
( ** Python Certification Training: https://www.edureka.co/python ** )
This Edureka PPT on Tkinter tutorial covers all the basic aspects of creating and making use of your own simple Graphical User Interface (GUI) using Python. It establishes all of the concepts needed to get started with building your own user interfaces while coding in Python.
In this PPT you will learn how to use looping in python.
For more presentation in any subject please contact us on
raginijain0208@gmail.com.
You get a new presentation every Sunday at 10 AM.
Learn more about Python by clicking on given below link
Python Introduction- https://www.slideshare.net/RaginiJain21/final-presentation-on-python
Basic concept of Python -https://www.slideshare.net/RaginiJain21/python-second-ppt
Python Datatypes - https://www.slideshare.net/RaginiJain21/data-types-in-python-248466302
Python Library & Module - https://www.slideshare.net/RaginiJain21/python-libraries-and-modules
Basic Python Programs- https://www.slideshare.net/RaginiJain21/basic-python-programs
Python Media Libarary - https://www.slideshare.net/RaginiJain21/python-media-library
This Edureka Python Programming tutorial will help you learn python and understand the various basics of Python programming with examples in detail. Below are the topics covered in this tutorial:
1. Python Installation
2. Python Variables
3. Data types in Python
4. Operators in Python
5. Conditional Statements
6. Loops in Python
7. Functions in Python
8. Classes and Objects
Creating Your First Predictive Model In PythonRobert Dempsey
If you’ve been reading books and blog posts on machine learning and predictive analytics and are still left wondering how to create a predictive model and apply it to your own data, this presentation will give you the steps you need to take to do just that.
Introduction to the Python programming language (version 2.x)
Ambient intelligence: technology and design
http://bit.ly/polito-ami
Politecnico di Torino, 2015
Python has been one of the premier, flexible, and powerful open-source language that is easy to learn, easy to use, and has powerful libraries for data manipulation and analysis. It’s easy to learn simple syntax is very accessible to new programmers and is similar to Matlab, C/C++, Java, or Visual Basic. Python is general purpose and comparatively easy to learn with an increased adoption for analytical and quantitative computing. For over a decade, Python has been used in scientific computing and highly quantitative domains such as finance, oil and gas, physics, and signal processing.
Open source general-purpose. Multiplatform programming language
Object Oriented, Procedural, Functional
Easy to interface with C/ObjC/Java/Fortran
Easy to interface with C++ (via SWIG)
Great interactive environment
Python 'philosophy' emphasis readability, clarity and simplicity
The Interactive Interpreter
it is very easy to learn and understand.
This presentation about Python Interview Questions will help you crack your next Python interview with ease. The video includes interview questions on Numbers, lists, tuples, arrays, functions, regular expressions, strings, and files. We also look into concepts such as multithreading, deep copy, and shallow copy, pickling and unpickling. This video also covers Python libraries such as matplotlib, pandas, numpy,scikit and the programming paradigms followed by Python. It also covers Python library interview questions, libraries such as matplotlib, pandas, numpy and scikit. This video is ideal for both beginners as well as experienced professionals who are appearing for Python programming job interviews. Learn what are the most important Python interview questions and answers and know what will set you apart in the interview process.
Simplilearn’s Python Training Course is an all-inclusive program that will introduce you to the Python development language and expose you to the essentials of object-oriented programming, web development with Django and game development. Python has surpassed Java as the top language used to introduce U.S. students to programming and computer science. This course will give you hands-on development experience and prepare you for a career as a professional Python programmer.
What is this course about?
The All-in-One Python course enables you to become a professional Python programmer. Any aspiring programmer can learn Python from the basics and go on to master web development & game development in Python. Gain hands on experience creating a flappy bird game clone & website functionalities in Python.
What are the course objectives?
By the end of this online Python training course, you will be able to:
1. Internalize the concepts & constructs of Python
2. Learn to create your own Python programs
3. Master Python Django & advanced web development in Python
4. Master PyGame & game development in Python
5. Create a flappy bird game clone
The Python training course is recommended for:
1. Any aspiring programmer can take up this bundle to master Python
2. Any aspiring web developer or game developer can take up this bundle to meet their training needs
Learn more at https://www.simplilearn.com/mobile-and-software-development/python-development-training
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language.
Make use of the PPT to have a better understanding of Python.
In this presentation I have presented about the iPython, how to install iPython, how to start with iPython. How to plot graph, how to animate/design it, the different type of graphs. What all functions you can take help of with iPython
I am Bianca H. I am a C++ Homework Expert at cpphomeworkhelp.com. I hold a Masters in Programming from, the University of Nottingham, UK. I have been helping students with their homework for the past 7 years. I solve homework related to C++. Visit cpphomeworkhelp.com or email info@cpphomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with C++ Homework.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
The field of Information retrieval (IR) is currently undergoing a transformative shift, at least partly due to the emerging applications of generative AI to information access. In this talk, we will deliberate on the sociotechnical implications of generative AI for information access. We will argue that there is both a critical necessity and an exciting opportunity for the IR community to re-center our research agendas on societal needs while dismantling the artificial separation between the work on fairness, accountability, transparency, and ethics in IR and the rest of IR research. Instead of adopting a reactionary strategy of trying to mitigate potential social harms from emerging technologies, the community should aim to proactively set the research agenda for the kinds of systems we should build inspired by diverse explicitly stated sociotechnical imaginaries. The sociotechnical imaginaries that underpin the design and development of information access technologies needs to be explicitly articulated, and we need to develop theories of change in context of these diverse perspectives. Our guiding future imaginaries must be informed by other academic fields, such as democratic theory and critical theory, and should be co-developed with social science scholars, legal scholars, civil rights and social justice activists, and artists, among others.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
I have heard many times that architecture is not important for the front-end. Also, many times I have seen how developers implement features on the front-end just following the standard rules for a framework and think that this is enough to successfully launch the project, and then the project fails. How to prevent this and what approach to choose? I have launched dozens of complex projects and during the talk we will analyze which approaches have worked for me and which have not.
8. Comments
Comments
• Start comments with # – the rest of line is
ignored.
• Can include a documentation string as the first
line of
any new function or class that you define.
• The development environment, debugger, and
other tools
use it: its good style to include one.
def my_function(x, y):
"""This is the docstring. This
8
9. Indentation
• Most languages don’t care about indentation
• Most humans do
• We tend to group similar things together
9
12. Assignment
• Binding a variable in Python means setting a
name to hold
a reference to some object.
• Assignment creates references, not copies
• Python determines the type of the reference
automatically based on the data object assigned
to it.
• You create a name the first time it appears on
the left side
of an assignment expression:
x = 3 12
13. Naming Rules
• Names are case sensitive and cannot start with
a number.
They can contain letters, numbers, and
underscores.
name Name _name _
• There are some reserved words:
and, assert, break, class, continue, def, del,
elif, else, except, exec, finally, for, from,
global, if, import, in, is, not, or,
pass, print, raise, return, try, while 13
14. Importing Modules
• Use classes & functions defined in another file.
• A Python module is a file with the same name (plus the .py
extension)
• Like Java import, C++ include.
import somefile
from somefile import *
from somefile import className
What’s the difference?
What gets imported from the file and what name refers to it
after it has been imported.
14
15. more import...
import somefile
• Everything in somefile.py gets imported.
• To refer to something in the file, append the text “somefile.” to the front of its name:
somefile.className.method(“abc”)
somefile.myFunction(34)
from somefile import *
• Everything in somefile.py gets imported
• To refer to anything in the module, just use its name. Everything in the module is now in the current
namespace.
• Caveat! Using this import command can easily overwrite the definition of an existing function or
variable!
className.method(“abc”)
myFunction(34)
15
16. Where does Python look for module files?
• The list of directories in which Python will look for the files to be imported: sys.path
(Variable named ‘path’ stored inside the ‘sys’ module.)
• To add a directory of your own to this list, append it to this list.
sys.path.append(‘/my/new/path’)
• default directory
/usr/local/lib/python2.7/dist-packages
16
17. Operators & Expressions
Python Operators:
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Python Expressions:
• Expressions in programming are like formulas in maths
• both use values to compute a result.
17
18. Arithematic Operators
c = a + b
c = a - b
c = a * b
c = a / b
c = a % b
a = 2
b = 3
c = a**b
print "Line 6 - Value of c is ", c
a = 10
b = 5
c = a//b
print "Line 7 - Value of c is ", c
18
19. Comparision operator
if ( a == b ):
print "Line 1 - a is equal to b"
else:
print "Line 1 - a is not equal to b"
if ( a != b ):
print "Line 2 - a is not equal to b"
else:
print "Line 2 - a is equal to b"
if ( a <> b ):
print "Line 3 - a is not equal to b"
else:
print "Line 3 - a is equal to b"
if ( a < b ):
print "Line 4 - a is less than b"
else:
print "Line 4 - a is not less than b"
19
20. Assignment Operators
a = 21
b = 10
c = 0
c = a + b
c += a
c *= a
c /= a
c %= a
c **= a
c //= a
20
22. Strings
Strings are sequences of characters
Indexed exactly like lists
name = 'somename'
print name[5]
name = 'myname'
for c in name:
print c
print 'in','dia'
print 'in
dia'
' == " but one a time
SyntaxError: EOL while scanning string literal 22
23. Strings
String are compared by charecter:
print 'a'<"b"
print 'cde'<"xy"
print 'cde'<"cda"
print '10'<'9'
Strings are immutable:
name = 'tushar'
name[1] = 'i'
TypeError: 'str' object does not support item assignment
Formatting:
emp_id = 100
percentage_business = 8
print 'employee id:' + str(emp_id) + ' produced ' + str(percentage_business) + '% business'
print 'employee id:%s produced %d%% business' %(str(emp_id),percentage_business)
percentage_yield = 12.3
print 'yield: %6.2f' % percentage_yield
23
24. Concantenate
var1 = 'kill bill!'
print "Updated String :- ", var1[:6] + 'all'
name = 'tushar' + ' ' + 'ranjan'
name+ = 'panda'
print name
Supported escape charecters:
a Bell or alert
b Backspace
cx Control-x
C-x Control-x
e Escape
f Formfeed
M-C-x Meta-Control-x
n Newline
r Carriage return
s Space
t Tab
v Vertical tab
24
26. More strings...
Raw Strings:
print 'D:filename'
print r'D:filename
O/P
D:filename
D:filename
Unicode String
# -*- coding: UTF-8 -*-
print u"àçñ"
title = u"Klüft skräms inför på fédéral électoral große"
import unicodedata
Print unicodedata.normalize('NFKD', title).encode('ascii','ignore')
'Kluft skrams infor pa federal electoral groe'
26
27. Python Typing
_Dynamic Typing_
Python determines the data types of variable bindings in a program automatically.
_Strong Typing_
But Python_s not casual about types, it enforces the types of objects.
Note: You can_t just append an integer to a string.
You must first convert the integer to a string itself.
x = "the answer is "
y = 23
print x + y (oops mistake...)
27
33. List
Operations:
concantenate
(['a', 'b', 'c'] + [4, 5, 6])
repeat
(['hello'] * 3)
Searching List:
using member of
(5 in [1, 2, 5])
range
for x in [1, 2, 3]: print x,
Notes:
you can put all kinds of objects in lists, including other lists, and multiple references to a single object. 33
34. List
The List sequence can be any kind of sequence object or iterable, including tuples and generators.
If you pass in another list, the list function makes a copy.
creates a new list every time you execute the [] expression.
A = []; B = []
No more, no less. And Python never creates a new list if you assign a list to a variable.
A = B = [] # both names will point to the same list
A = []
B = A # both names will point to the same list
34
35. List Comprehensions
python supports computed lists called list comprehensions.
L = [expression for variable in sequence]
A powerful feature of the Python language.
• Generate a new list by applying a function to every member of an original list.
• Python programmers use list comprehensions extensively.
The syntax of a list comprehension is somewhat tricky.
• Syntax suggests that of a for-loop, an in operation, or an if statement
• all three of these keywords (_for_, _in_, and _if_) are also used in the syntax of forms of list
comprehensions.
35
36. List Comprehensions ...
Ex:
list1 = [3, 6, 2, 7]
print [element*2 for element in list1]
[6, 12, 4, 14]
• The expressions in list comprehension can be anything.
• all kinds of objects in lists, including other lists, and multiple references to a single object.
• If different types of elements are present , expression must operate correctly on all the types.
• If the elements of list are other containers, then the name can consist of a container of names
that match the type and shape of the list members.
list1 = [(a, 1), (b, 2), (c, 7)]
print [ n * 3 for (x, n) in list1]
[3, 6, 21]
36
37. Iterators
List has support for iterator protocol.
i = iter(L)
item = i.next()
Locate first element index:
try:
index = L.index(value)
except ValueError
print "No match"
Locate all element index:
while 1:
i = L.index(value, i+1)
print "match at", i
print L.count()
37
38. Tuple
A tuple is like an immutable list.
It is slightly faster and smaller than a list.
t = ()
t = ("iit")
t = ("iit","nit")
print t
t[1] = "trp"
TypeError: 'tuple' object does not support item assignment
38
39. Tuple
list to tuple:
a1 = ["python","java"]
a2 = tuple(a1)
print type(a1)
print type(a2)
unpacking values:
t = ('lakshmi','mittal')
first_name,family_name = t
print first_name,family_name
Tuple Slicing:
t = ('Lakshmi','Niwas','Mittal')
print t[0::2]
('Lakshmi', 'Mittal')
39
40. Dictionary
operate as key-value pairs.
dict = {}
dict['Name'] = 'Raj'
dict['Age'] = 7
dict['Class'] = 'First'
• Dictionaries are used for non-integer index containers.
• Any immutable type can be used as index.
removing an item:
del dict['Class']
getting keys/values/items:
print dict.keys()
print dict.values()
print dict.items()
print dict.has_key('name')
40
41. Sets
A set is gathering of definite & distinct objects.
The objects are called elements of the set.
Creating Set:
x = set("A Python Tutorial")
print x
No element duplication in set
Immutable sets
cities = set((("Python","Perl"), ("Delhi", "Mumbai", "Pune")))
print cities
Add:
colours = {"red","green"}
colours.add("yellow") 41
42. Sets
Clear:
cities = {"chennai", "hyderabad", "bangalore"}
cities.clear()
Copy:
cities = {"chennai", "hyderabad", "bangalore"}
cities2 = cities.copy()
cities.clear()
print cities2
copy() is NOT EQUAL TO assignment.
cities = set((["Python","Perl"], ["Delhi", "Mumbai", "Pune"]))
print cities
TypeError: unhashable type: 'list'
Reason: assignment fails as two pointers points to a blank(previously full) location. 42
44. Simple Loop
count = 10
while (count < 20):
print 'Counter value:', count
count = count + 1
for loop can iterate list , The list can be heterogenous .
A for loop can also iterate over a "generator", which is a small piece of code instead of an actual list.
the range function can be used with loops.
Ex:
n = int(input('how many iterations ??'))
for i in range(0,n):
print "iteration",n
44
45. infinite loop:
=========================
While True:
// do something
infinite loop with break:
=========================
While True:
condition match:
hit the break condition, move out
else keep moving
ex:
with open("logfile",'rb') as f:
while True:
line=f.readline()
if not line:
break
print line
45
46. Exceptions
string1 = "I like Python"
print string1[54]
IndexError: string index out of range
An exception in general is an event,
• which occurs during the execution of a program
• that disrupts the normal flow of the program's instructions.
why exceptions are important ??
1. handle errors
2. prevent program flow disruption.
3. nothing matches, use else.
46
47. Exceptions
In Python: Exception is a object that represents an error.
x = 5
y =0
try:
z = x/y
except ZeroDivisionError:
print "divide by zero"
47
48. Class & Objects
OOP Terminology:
Class, Objects, Methods
• Class variable
• Data member
• Function overloading
• Instance
• Instance variable
• Inheritance
• Instantiation
• Operator overloading
48
49. Class & Objects
Class: A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data
members (class variables and instance variables) and methods, accessed via dot notation.
Class variable: A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods.
Class variables are not used as frequently as instance variables are.
Data member: A class variable or instance variable that holds data associated with a class and its objects.
Function overloading: The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects or
arguments involved.
Instance variable: A variable that is defined inside a method and belongs only to the current instance of a class.
Inheritance: The transfer of the characteristics of a class to other classes that are derived from it.
Instance: An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle.
Instantiation: The creation of an instance of a class.
Method : A special kind of function that is defined in a class definition.
Object: A unique instance of a data structure that's defined by its class. An object comprises both data members (class variables and instance
variables) and methods.
Operator overloading: The assignment of more than one function to a particular operator.
49
50. Class & Objects
Objects
Everything in Python is an object that has:
- an identity (id)
- a value (mutable or immutable) , Objects whose value can change are said to be mutable.
Ex:
a = 7
print id(a)
632887
Mutable: id remains same. Dictionary, List
Immutable: id changes. String, Integer, Tuple
50
51. Class & ObjectsMore on mutable:
b = ["hello"]
print id(b)
139908350192024
b.append("world")
print id(b)
139908350192024
a = "super"
print id(a)
140304291482864
a = "super man"
print id(a)
140304290186416
51
55. Class build-in attributes
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
print Employee.__doc__
print Employee.__name__
print Employee.__module__
print Employee.__bases__
print Employee.__dict__ 55
56. Defn:
__doc__: Class documentation string or none, if undefined.
__name__: Class name.
__module__: Module name in which the class is defined. This attribute is "__main__" in interactive
mode.
__bases__: A possibly empty tuple containing the base classes, in the order of their occurrence in the
base class list.
__dict__: Dictionary containing the class's namespace.
Answer:
Common base class for all employees
Employee
__main__
()
{'__module__': '__main__', 'displayCount': <function displayCount at 0x7facd5bbd668>, 'empCount': 0,
'displayEmployee': <function displayEmployee at 0x7facd5bbd6e0>, '__doc__': 'Common base class for
all employees', '__init__': <function __init__ at 0x7facd5bbd5f0>}
56
57. Files
What You Need In Order To Read
Information From A File
1. Open the file and associate the file with a file variable.
2. A command to read the information.
3. A command to close the file.
57
58. Files
opening file:
<file variable> = open(<file name>, "r")
Example:
inputFile = open("data.txt", "r")
What open does ??
A. Links the file variable with the physical file (references to the file variable are references to the
physical file).
B. Positions the file pointer at the start of the file.
Dynamic file naming:
filename = input("Enter name of input file: ")
inputFile = open(filename, "r")
58
59. Files
reading file:
Example:
for line in inputFile:
print(line) # Echo file contents back onscreen
Notes:
- Typically reading is done within the body of a loop
- Each execution of the loop will read a line from the
- put file into a string
59
60. Files
Closing File:
• Format:
<name of file variable>.close()
• Example:
inputFile.close()
Caution:
Always explicitly close the files.
Reason:
- if the program encounters a runtime error and crashes before it reaches the end, the file remain ‘locked’
in an inaccessible state because it’s still open.
60
61. Files
What You Need In Order To Write
Information From A File
1. Open the file and associate the file with a file variable.
2. A command to read the information.
3. A command to close the file.
61
62. writing to file:
iFile = input("file to be read")
oFile = input("fileto be written ")
inputFile = open(iFile, "r")
outputFile = open(oFile, "w")
...
...
for line in inputFile:
if (line[0] == "A"):
grade = 4
elif (line[0] == "B"):
grade = 3
elif (line[0] == "F"):
grade = 0
else:
print "Invalid Grade"
outputFile.write (grade)
...
...
inputFile.close ()
outputFile.close ()
print ("Completed reading ", iFile)
print ("Completed writing ", oFile)
62
67. Regular Expression
Why need it ??
Data files generated by a third party.
No control over the format.
Files badly need pre-processing
Its used to perform pattern match/search/replace over the data.
Ex:
s = 'This is the main road'
print s.replace('road', '0')
This is the main 0
s = 'This is a broad road'
s.replace('road', 'ROAD.')
This is a bROAD. ROAD.
s[:-4] + s[-4:].replace('ROAD', 'RD.')
'100 NORTH BROAD RD.'
67
68. Regular Expression
import re
data = "Python is great. I like python"
m = re.search(r'[pP]ython',data)
print m.group()
Python
import re
data = "I like python"
m = re.search(r’python’,data)
m.group()
m.start()
m.span()
python
7
(7,13)
68
69. Regular Expression
import re
data = "Python is great. I like python"
m = re.search(r'[pP]ython',data)
print m.group()
'Python'
['Python', 'python']
import re
data = "Python is great. I like python"
l = re.findall(r'[pP]ython',data)
print l
['Python', 'python']
re.search() returns only the first match, re.findall() return all matches.
69
70. Database
Data in a Python application can be stored and referenced in multiple ways.
- files
- flat file database
- XML, json
- Relational Database (SQL)
- Non Relational Database (NOSQL)
70
71. Database
Sqlite:
steps:
• import sqlite3 module.
• create a Connection object which will represent databse.
• provide a database name.
• if exists, file is loaded and database is opened.
• create/access a table
• execute command using cursor
• retrieve data from database
71
72. Database
Common Errors:
SQLITE_ERROR 1 /* SQL error or missing database */
SQLITE_BUSY 5 /* The database file is locked */
SQLITE_PERM 3 /* Access permission denied */
SQLITE_READONLY 8 /* Attempt to write a readonly database */
SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
72
74. Database
mysql:
sudo apt-get install python-MySQLdb
steps:
• import MySQLdb module
• Open a connection to the MySQL server
• Send command and receive data
• Close connection
Example:
import MySQLdb
db = MySQLdb.connect(<SERVER>,<DATABASE_NAME>,<USERNAME>,<PASSWORD>)
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print "Database version : %s " % data
db.close()
74
75. Python & Web
WWW
• craze for user generated content.
• frameworks & tools available: a click away.
• dynamic frameworks --->>> We too support MVC.
The Low-Level View :
user & server
request:
user enters a web site ->
browser connects to server->
response:
server looks for requested file ->
sends file back to browser ->
Dynamic Sites:
host dynamic pages.
- display posts,
- show news board,
- show your email,
- configure software.
HTTP servers are written C++, python bridges required to interact with them.
fork.c
75
76. CGI & FCGI
Common Gateway Interface
- the oldest & supported everywhere web server.
- 1 request = 1 python interpreter
- simple 3 lines of code
supported cgi servers:
apache httpd
lighttpd
FastCGI
no interpreter.
module/library talk with independent background processes(mostly cpp).
FCGI is used to deploy WSGI applications.
76
77. FCGI
Setting up FastCGI
Each web server requires a specific module - mod_fastcgi or mod_fcgid
Apache has both.
lighttpd ships its own FastCGI module.
nginx also supports FastCGI.
Once you have installed and configured the module, you can test it with the following WSGI-application:
===================
# -*- coding: UTF-8 -*-
from flup.server.fcgi import WSGIServer
from <YOURAPPLICATION> import app
if __name__ == '__main__':
WSGIServer(app).run()
===================
77
78. Why CGI not used ??
CGI Example:
import cgitb
cgitb.enable()
print "Content-Type: text/plain;charset=utf-8"
print "Hello World!"
cgitb:
display error instead of crashing.
risk:
risk os exposing confidential data
better try/catch stuff.
78
79. WSGI
Standard Interface defined in pep-0333.
proposed standard interface between web servers and Python web applications or frameworks.
remove framework dependancy like Java Servelet API.
Applications can run on multiple servers.
Middleware can be reused easily.
A Simple Complete Response
HTTP/1.x 200 OK
Server: SimpleHTTP/0.6 Python/2.4.1
Content-Type: text/html
<html><body>Hello World!</body></html>
def application(environ, start_response):
start_response('200 OK',[('Content-type','text/html')])
return ['<html><body>Hello World!</body></html>']
What makes this a WSGI application ??
It is a callable taking ONLY two parameters.
It calls start_response() with status code and list of headers.
It should only be called once.
The response it returns is an iterable (in this case a list with just one string). 79
80. SimpleHTTPServer
import SimpleHTTPServer
import SocketServer
import signal
import sys
def receive_signal(signum, stack):
print 'Stopping Server !!!', signum
sys.exit(0)
signal.signal(signal.SIGINT, receive_signal)
PORT = 8001
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
Server = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
Server.serve_forever()
80
81. Sockets Server
#############SERVER
import portfile
portno = portfile.portnumber
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.settimeout(100)
s.setblocking(0)
#s.settimeout(0.5)
s.bind((socket.gethostname(),portno))
s.listen(5)
while True:
c, addr = s.accept()
print 'Got connection from', addr
# print 'Peername ', c.getpeername()
timestamp1 = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
c.send(timestamp1)
data = c.recv(100)
if data == "stopnow":
print "stopnow received : Server Stopped"
s.close()
sys.exit(0)
else:
print "%s received." %data
s.close()
81
82. Sockets Client
#############CLIENT
import socket
import portfile
portno = portfile.portnumber
send_text = portfile.client_text
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((socket.gethostname(),portno))
while True:
data = s.recv(100)
print "nrecv:",data
s.send(send_text)
s.close()
82