This document provides an overview of the Python programming language. It discusses Python's history and design, data types like integers, floats, strings, lists, tuples and dictionaries. It also covers core concepts like variables, expressions, control flow with if/else statements and loops. The document demonstrates how to take user input, read and write files, and describes moving Python code to files to make it reusable.
Getting started in Python presentation by Laban KGDSCKYAMBOGO
Python Overview and getting started in Python Language. It includes on how to install, run it and carrying out some simple python codes in different environments(IDLEs)
Getting started in Python presentation by Laban KGDSCKYAMBOGO
Python Overview and getting started in Python Language. It includes on how to install, run it and carrying out some simple python codes in different environments(IDLEs)
Python is an interpreted, object-oriented programming language similar to PERL, that has gained popularity because of its clear syntax and readability.
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.
Python is an interpreted, object-oriented programming language similar to PERL, that has gained popularity because of its clear syntax and readability.
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.
mooc_presentataion_mayankmanral on the subject puthongarvitbisht27
Python prr ppt hai so plzz nsjsiskbdbdjdjdkdjdndndndndmmdmdndndndndndndndnndndndnndndndmememdmsjakksmwbshskammanahaialemneeuislmeheuiekememejkeksmwjejekekmemenejekmemrme
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Python is an interpreted, object-oriented programming language similar to PERL, that has gained popularity because of its clear syntax and readability.
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.
Python is an interpreted, object-oriented programming language similar to PERL, that has gained popularity because of its clear syntax and readability.
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.
mooc_presentataion_mayankmanral on the subject puthongarvitbisht27
Python prr ppt hai so plzz nsjsiskbdbdjdjdkdjdndndndndmmdmdndndndndndndndnndndndnndndndmememdmsjakksmwbshskammanahaialemneeuislmeheuiekememejkeksmwjejekekmemenejekmemrme
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
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.
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.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
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
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
ppt_pspp.pdf
1. 19cab04 - problem
solving and Python
Programming
By
Dr. M. Moorthy, HoD / MCA
Muthayammal Engineering College
MCA - I Semester Regulation 2019
2. Presentation Overview
• History of Python
• Running Python and Output
• Data Types
• Input and File I/O
• Control Flow
• Functions
• Working with MySQL d/b
3. Brief History of Python
• Invented in the Netherlands, early 90s by
Guido van Rossum
• Named after Monty Python
• Open sourced from the beginning
• Considered a scripting language, but is much more
• Scalable, object oriented and functional from the beginning
• Used by Google from the beginning
• Increasingly popular
4. Hello World
>>> 'hello world!'
'hello world!'
•Open a terminal window and type “python”
•If on Windows open a Python IDE like IDLE
•At the prompt type ‘hello world!’
5. Python Overview
• Programs are composed of modules
• Modules contain statements
• Statements contain expressions
• Expressions create and process objects
6. The Python Interpreter
•Python is an interpreted
language
•The interpreter provides an
interactive environment to
play with the language
•Results of expressions are
printed on the screen
>>> 3 + 7
10
>>> 3 < 15
True
>>> 'print me'
'print me'
>>> print 'print me'
print me
>>>
7. Enough to Understand the Code
• Indentation matters to code meaning
– Block structure indicated by indentation
• First assignment to a variable creates it
– Variable types don’t need to be declared.
– Python figures out the variable types on its own.
• Assignment is = and comparison is ==
• For numbers + - * / % are as expected
– Special use of + for string concatenation and % for string formatting
(as in C’s printf)
• Logical operators are words (and, or, not) not symbols
• The basic printing command is print
8. Whitespace
Whitespace is meaningful in Python: especially indentation and placement
of newlines
•Use a newline to end a line of code
Use when must go to next line prematurely
•No braces {} to mark blocks of code, use consistent indentation instead
• First line with less indentation is outside of the block
• First line with more indentation starts a nested block
•Colons start of a new block in many constructs, e.g. function definitions,
then clauses
9. Naming Rules
• Names are case sensitive and cannot start with a
number. They can contain letters, numbers, and
underscores.
bob Bob _bob _2_bob_ bob_2 BoB
• There are some reserved words:
and, assert, break, class, continue,
def, del, elif, else, except, exec,
finally, for, from, global, if,
import, in, is, lambda, not, or,
pass, print, raise, return, try,
while
10. Naming conventions
The Python community has these recommend-ed
naming conventions
•joined_lower for functions, methods and, attributes
•joined_lower or ALL_CAPS for constants
•StudlyCaps for classes
•camelCase only to conform to pre-existing
conventions
•Attributes: interface, _internal, __private
11. The print Statement
>>> print 'hello'
hello
>>> print 'hello', 'there'
hello there
•Elements separated by
commas print with a space
between them
•A comma at the end of the
statement (print ‘hello’,) will
not print a newline character
13. Variables
• Are not declared, just assigned
• The variable is created the first time you assign it
a value
• Are references to objects
• Type information is with the object, not the
reference
• Everything in Python is an object
14. Everything is an object
• Everything means
everything, including
functions and classes
• Data type is a property
of the object and not of
the variable
>>> x = 7
>>> x
7
>>> x = 'hello'
>>> x
'hello'
>>>
15. Numbers: Integers
• Integer – the equivalent of
a C long
• Long Integer – an
unbounded integer value.
>>> 132224
132224
>>> 132323 ** 2
17509376329L
>>>
16. Numbers: Floating Point
• int(x) converts x to an
integer
• float(x) converts x to a
floating point
• The interpreter shows
a lot of digits
>>> 1.23232
1.2323200000000001
>>> print 1.23232
1.23232
>>> 1.3E7
13000000.0
>>> int(2.0)
2
>>> float(2)
2.0
17. Numbers: Complex
• Built into Python
• Same operations are
supported as integer and
float
>>> x = 3 + 2j
>>> y = -1j
>>> x + y
(3+1j)
>>> x * y
(2-3j)
19. String Literals
• Strings are immutable
• There is no char type like
in C++ or Java
• + is overloaded to do
concatenation
>>> x = 'hello'
>>> x = x + ' there'
>>> x
'hello there'
20. String Literals: Many Kinds
• Can use single or double quotes, and three double
quotes for a multi-line string
>>> 'I am a string'
'I am a string'
>>> "So am I!"
'So am I!'
>>> s = """And me too!
though I am much longer
than the others :)"""
'And me too!nthough I am much longernthan the others :)‘
>>> print s
And me too!
though I am much longer
than the others :)‘
21. Substrings and Methods
>>> s = '012345'
>>> s[3]
'3'
>>> s[1:4]
'123'
>>> s[2:]
'2345'
>>> s[:4]
'0123'
>>> s[-2]
'4'
• len(String) – returns the
number of characters in the
String
• str(Object) – returns a
String representation of the
Object
>>> len(x)
6
>>> str(10.3)
'10.3'
22. String Formatting
• Similar to C’s printf
• <formatted string> % <elements to insert>
• Can usually just use %s for everything, it will
convert the object to its String representation.
>>> "One, %d, three" % 2
'One, 2, three'
>>> "%d, two, %s" % (1,3)
'1, two, 3'
>>> "%s two %s" % (1, 'three')
'1 two three'
>>>
23. Lists
• Ordered collection of data
• Data can be of different
types
• Lists are mutable
• Issues with shared
references and mutability
• Same subset operations as
Strings
>>> x = [1,'hello', (3 + 2j)]
>>> x
[1, 'hello', (3+2j)]
>>> x[2]
(3+2j)
>>> x[0:2]
[1, 'hello']
24. Lists: Modifying Content
• x[i] = a reassigns the
ith element to the
value a
• Since x and y point to
the same list object,
both are changed
• The method append
also modifies the list
>>> x = [1,2,3]
>>> y = x
>>> x[1] = 15
>>> x
[1, 15, 3]
>>> y
[1, 15, 3]
>>> x.append(12)
>>> y
[1, 15, 3, 12]
25. Lists: Modifying Contents
• The method
append modifies
the list and returns
None
• List addition (+)
returns a new list
>>> x = [1,2,3]
>>> y = x
>>> z = x.append(12)
>>> z == None
True
>>> y
[1, 2, 3, 12]
>>> x = x + [9,10]
>>> x
[1, 2, 3, 12, 9, 10]
>>> y
[1, 2, 3, 12]
>>>
26. Operations on Lists Only
Lists have many methods, including index, count, remove,
reverse, sort
>>> li = [‘a’, ‘b’, ‘c’, ‘b’]
>>> li.index(‘b’) # index of 1st occurrence
3
>>> li.count(‘b’) # number of occurrences
2
>>> li.remove(‘b’) # remove 1st occurrence
>>> li
[‘a’, ‘c’, ‘b’]
27. Operations on Lists Only (Contd..)
>>> li = [5, 2, 6, 8]
>>> li.reverse() # reverse the list *in place*
>>> li
[8, 6, 2, 5]
>>> li.sort() # sort the list *in place*
>>> li
[2, 5, 6, 8]
>>> li.sort(some_function)
# sort in place using user-defined comparison
28. Tuples
• Tuples are immutable
versions of lists
• One strange point is the
format to make a tuple with
one element:
‘,’ is needed to differentiate
from the mathematical
expression (2)
>>> x = (1,2,3)
>>> x[1:]
(2, 3)
>>> y = (2,)
>>> y
(2,)
>>>
29. Summary: Tuples vs. Lists
• Lists slower but more powerful than tuples
– Lists can be modified, and they have lots of
handy operations and mehtods
– Tuples are immutable and have fewer features
• To convert between tuples and lists use the list()
and tuple() functions:
li = list(tu)
tu = tuple(li)
30. Dictionaries
• A set of key-value pairs
• Dictionaries are mutable
>>> d = {1 : 'hello', 'two' : 42, 'blah' : [1,2,3]}
>>> d
{1: 'hello', 'two': 42, 'blah': [1, 2, 3]}
>>> d['blah']
[1, 2, 3]
31. Dictionaries: Add/Modify
>>> d
{1: 'hello', 'two': 42, 'blah': [1, 2, 3]}
>>> d['two'] = 99
>>> d
{1: 'hello', 'two': 99, 'blah': [1, 2, 3]}
>>> d[7] = 'new entry'
>>> d
{1: 'hello', 7: 'new entry', 'two': 99, 'blah': [1, 2, 3]}
• Entries can be changed by assigning to that entry
• Assigning to a key that does not exist adds an entry
32. Dictionaries: Deleting Elements
• The del method deletes an element from a dictionary
>>> d
{1: 'hello', 2: 'there', 10: 'world'}
>>> del(d[2])
>>> d
{1: 'hello', 10: 'world'}
33. Copying Dictionaries and Lists
• The built-in list
function will
copy a list
• The dictionary
has a method
called copy
>>> l1 = [1]
>>> l2 = list(l1)
>>> l1[0] = 22
>>> l1
[22]
>>> l2
[1]
>>> d = {1 : 10}
>>> d2 = d.copy()
>>> d[1] = 22
>>> d
{1: 22}
>>> d2
{1: 10}
34. Data Type Summary
• Lists, Tuples, and Dictionaries can store any type
(including other lists, tuples, and dictionaries!)
• Only lists and dictionaries are mutable
• All variables are references
35. Data Type Summary
• Integers: 2323, 3234L
• Floating Point: 32.3, 3.1E2
• Complex: 3 + 2j, 1j
• Lists: l = [ 1,2,3]
• Tuples: t = (1,2,3)
• Dictionaries: d = {‘hello’ : ‘there’, 2 : 15}
36. Input
• The raw_input(string) method returns a line of
user input as a string
• The parameter is used as a prompt
• The string can be converted by using the
conversion methods int(string), float(string), etc.
37. Input: Example
print "What's your name?"
name = raw_input("> ")
print "What year were you born?"
birthyear = int(raw_input("> "))
print "Hi %s! You are %d years old!" % (name, 2011 - birthyear)
~: python input.py
What's your name?
> Michael
What year were you born?
>1980
Hi Michael! You are 31 years old!
38. Files: Input
inflobj = open(‘data’,
‘r’)
Open the file ‘data’
for input
S = inflobj.read() Read whole file into
one String
S = inflobj.read(N) Reads N bytes
(N >= 1)
L = inflobj.readlines() Returns a list of line
strings
39. Files: Output
outflobj = open(‘data’, ‘w’) Open the file ‘data’
for writing
outflobj.write(S) Writes the string S to
file
outflobj.writelines(L) Writes each of the
strings in list L to file
outflobj.close() Closes the file
40. Booleans
• 0 and None are false
• Everything else is true
• True and False are aliases for 1 and 0 respectively
41. Boolean Expressions
• Compound boolean expressions
short circuit
• and and or return one of the
elements in the expression
• Note that when None is returned
the interpreter does not print
anything
>>> True and False
False
>>> False or True
True
>>> 7 and 14
14
>>> None and 2
>>> None or 2
2
42. Moving to Files
• The interpreter is a good place to try out some code,
but what you type is not reusable
• Python code files can be read into the interpreter
using the import statement
43. Moving to Files
• In order to be able to find a module called myscripts.py,
the interpreter scans the list sys.path of directory names.
• The module must be in one of those directories.
>>> import sys
>>> sys.path
['C:Python26Libidlelib', 'C:WINDOWSsystem32python26.zip',
'C:Python26DLLs', 'C:Python26lib', 'C:Python26libplat-win',
'C:Python26liblib-tk', 'C:Python26', 'C:Python26libsite-packages']
>>> import myscripts
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
import myscripts.py
ImportError: No module named myscripts.py
44. No Braces
• Python uses indentation instead of braces to determine
the scope of expressions
• All lines must be indented the same amount to be part
of the scope (or indented more if part of an inner
scope)
• This forces the programmer to use proper indentation
since the indenting is part of the program!
45. If Statements
import math
x = 30
if x <= 15 :
y = x + 15
elif x <= 30 :
y = x + 30
else :
y = x
print ‘y = ‘,
print math.sin(y)
In file ifstatement.py
>>> import ifstatement
y = 0.999911860107
>>>
In interpreter
46. While Loops
x = 1
while x < 10 :
print x
x = x + 1
>>> import whileloop
1
2
3
4
5
6
7
8
9
>>>
In whileloop.py
In interpreter
47. Loop Control Statements
break Jumps out of the closest
enclosing loop
continue Jumps to the top of the closest
enclosing loop
pass Does nothing, empty statement
placeholder
48. The Loop Else Clause
• The optional else clause runs only if the loop exits
normally (not by break)
x = 1
while x < 3 :
print x
x = x + 1
else:
print 'hello'
~: python whileelse.py
1
2
hello
Run from the command line
In whileelse.py
49. The Loop Else Clause
x = 1
while x < 5 :
print x
x = x + 1
break
else :
print 'i got here'
~: python whileelse2.py
1
whileelse2.py
50. For Loops
• Similar to perl for loops, iterating through a list of values
~: python forloop1.py
1
7
13
2
for x in [1,7,13,2] :
print x
forloop1.py
~: python forloop2.py
0
1
2
3
4
for x in range(5) :
print x
forloop2.py
range(N) generates a list of numbers [0,1, …, n-1]
51. For Loops
• For loops also may have the optional else clause
for x in range(5):
print x
break
else :
print 'i got here'
~: python elseforloop.py
1
elseforloop.py
52. Function Basics
def max(x,y) :
if x < y :
return x
else :
return y
>>> import functionbasics
>>> max(3,5)
5
>>> max('hello', 'there')
'there'
>>> max(3, 'hello')
'hello'
functionbasics.py
53. Functions are first class objects
• Can be assigned to a variable
• Can be passed as a parameter
• Can be returned from a function
• Functions are treated like any other variable in
Python, the def statement simply assigns a
function to a variable
54. Function names are like any variable
• Functions are objects
• The same reference
rules hold for them as
for other objects
>>> x = 10
>>> x
10
>>> def x () :
... print 'hello'
>>> x
<function x at 0x619f0>
>>> x()
hello
>>> x = 'blah'
>>> x
'blah'
55. Functions as Parameters
def foo(f, a) :
return f(a)
def bar(x) :
return x * x
>>> from funcasparam import *
>>> foo(bar, 3)
9
Note that the function foo takes two
parameters and applies the first as a
function with the second as its
parameter
funcasparam.py
56. Higher-Order Functions
map(func,seq) – for all i, applies func(seq[i]) and returns the
corresponding sequence of the calculated results.
def double(x):
return 2*x
>>> from highorder import *
>>> lst = range(10)
>>> lst
[0,1,2,3,4,5,6,7,8,9]
>>> map(double,lst)
[0,2,4,6,8,10,12,14,16,18]
highorder.py
57. Higher-Order Functions
filter(boolfunc,seq) – returns a sequence containing all those items
in seq for which boolfunc is True.
def even(x):
return ((x%2 == 0)
>>> from highorder import *
>>> lst = range(10)
>>> lst
[0,1,2,3,4,5,6,7,8,9]
>>> filter(even,lst)
[0,2,4,6,8]
highorder.py
58. Higher-Order Functions
reduce(func,seq) – applies func to the items of seq, from left to
right, two-at-time, to reduce the seq to a single value.
def plus(x,y):
return (x + y)
>>> from highorder import *
>>> lst = [‘h’,’e’,’l’,’l’,’o’]
>>> reduce(plus,lst)
‘hello’
highorder.py
59. Functions Inside Functions
• Since they are like any other object, you can have
functions inside functions
def foo (x,y) :
def bar (z) :
return z * 2
return bar(x) + y
>>> from funcinfunc import *
>>> foo(2,3)
7
funcinfunc.py
60. Functions Returning Functions
def foo (x) :
def bar(y) :
return x + y
return bar
# main
f = foo(3)
print f
print f(2)
~: python funcreturnfunc.py
<function bar at 0x612b0>
5
funcreturnfunc.py
61. Parameters: Defaults
• Parameters can be
assigned default
values
• They are overridden if
a parameter is given
for them
• The type of the default
doesn’t limit the type
of a parameter
>>> def foo(x = 3) :
... print x
...
>>> foo()
3
>>> foo(10)
10
>>> foo('hello')
hello
62. Parameters: Named
• Call by name
• Any positional
arguments must
come before
named ones in a
call
>>> def foo (a,b,c) :
... print a, b, c
...
>>> foo(c = 10, a = 2, b = 14)
2 14 10
>>> foo(3, c = 2, b = 19)
3 19 2
63. Anonymous Functions
• A lambda
expression returns a
function object
• The body can only
be a simple
expression, not
complex statements
>>> f = lambda x,y : x + y
>>> f(2,3)
5
>>> lst = ['one', lambda x : x * x, 3]
>>> lst[1](4)
16
64. Modules
• The highest level structure of Python
• Each file with the py suffix is a module
• Each module has its own namespace
65. Modules: Imports
import mymodule Brings all elements
of mymodule in, but
must refer to as
mymodule.<elem>
from mymodule import x Imports x from
mymodule right into
this namespace
from mymodule import * Imports all elements
of mymodule into
this namespace
66. Working with MySQL Database
• What is MySQLdb?
MySQLdb is an interface for connecting to a MySQL database server from
Python. It implements the Python Database API v2.0 and is built on top of the
MySQL C API.
• The Python standard for database interfaces is the Python DB-API. Most Python database interfaces
adhere to this standard.
• You can choose the right database for your application. Python Database API supports a wide range
of database servers such as −
GadFly
mSQL
MySQL
PostgreSQL
Microsoft SQL Server 2000
Informix
Interbase
Oracle
Sybase
67. Working with MySQL Database (Contd…)
• Here is the list of available Python database interfaces: Python
Database Interfaces and APIs .You must download a separate DB API
module for each database you need to access. For example, if you need
to access an Oracle database as well as a MySQL database, you must
download both the Oracle and the MySQL database modules.
• The DB API provides a minimal standard for working with databases
using Python structures and syntax wherever possible. This API
includes the following:
- Importing the API module.
- Acquiring a connection with the database.
- Issuing SQL statements and stored procedures.
- Closing the connection
68. Working with MySQL Database (Contd…)
#import database module
import MySQLdb
# Open database connection
db = MySQLdb.connect("127.0.0.1","root","root","mydb" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query
sql = "SELECT * FROM EMPLOYEE"
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0] ; lname = row[1]; age = row[2]; sex = row[3]; income = row[4]
# Now print fetched result
print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" %
(fname, lname, age, sex, income )
except:
print "Error: unable to fecth data"
# disconnect from server
db.close()