View
226
Download
0
Category
Preview:
Citation preview
8/2/2019 Harsh Python
1/39
What is Python?
An object- oriented, interpreted, high level
programming language
Is an object oriented scripting language
Easy to learn, read, use
Open Source
Embeddable in applications
8/2/2019 Harsh Python
2/39
History
Invented in 1990 by Guido Van Rossum
The name Python stems from "Monty Python's
Flying Circus"
Python was influenced by ABC and Modula-3
First public release was in 1991
8/2/2019 Harsh Python
3/39
Who is using it?
Google (various projects)
NASA (several projects)
The popular Bit Torrent peer-to-peer file sharing system is aPython program.
Yahoo! (Yahoo mail & groups)
The YouTube video sharing service is largely written inPython.
Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBMuse Python for hardware testing.
Maya, a powerful integrated 3D modeling and animationsystem, provides a Python scripting API.
8/2/2019 Harsh Python
4/39
Data types
Numbers flt_num= 10.0 int_num= 25
Strings my_str = Why are u using Perl?
Lists my_list = [123, 'spam', 1.23]
Tuples my_tup = (1, 4 , 32, *fo , abc+)
Dictionaries my_dict = a : 24, mo : fo-
Objects my_inst = MyClass(foo)
Modules: import myfile
8/2/2019 Harsh Python
5/39
Numbers
Integers:
>>> my_int = 4
>>>my_int / 3
1
Floating Point:
>>> my_float = 5.5
>>> 20/my_float
3.6363636363636362
8/2/2019 Harsh Python
6/39
Strings
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'
8/2/2019 Harsh Python
7/39
Strings
"hello""world "helloworld" # concatenation
"hello"*3 "hellohellohello" # repetition
"hello"[0] "h" # indexing
"hello"[-1] "o" # (from end)
"hello"[1:4] ell" # slicing
len("hello") 5 # size
"e" in "hello 1 # search
8/2/2019 Harsh Python
8/39
String Formatting
Similar to Cs printf
%
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
8/2/2019 Harsh Python
9/39
Lists
Ordered collection of
data
Data can be of different
types
Lists are mutable
Same subset operations
as Strings
>>> x = [1,'hello', (3 + 2j)]
>>> x
[1, 'hello', (3+2j)]>>> x[2]
(3+2j)
>>> x[0:2]
[1, 'hello']
8/2/2019 Harsh Python
10/39
List Methods
append(x) add x to the end of the list
insert( i, x)insert x at a position i
remove(x) remove first item equal to x pop() remove item at the end of list
sort() sort the list
reverse() reverse the list
8/2/2019 Harsh Python
11/39
Examples
>>> a = range(5) # [0,1,2,3,4]
>>> a.append(5) # [0,1,2,3,4,5]
>>> a.pop() # [0,1,2,3,4]>>> a.insert(0, 42) # [42,0,1,2,3,4]
>>> a.pop(0) # [0,1,2,3,4]
>>> a.reverse() # [4,3,2,1,0]>>> a.sort() # [0,1,2,3,4]
8/2/2019 Harsh Python
12/39
Tuples
Tuples are immutable
versions of lists
Coded in parentheses
>>> T = ('spam', 3.0, [11, 22, 33])
>>> T[1]
3.0
>>> T[2][1]
22
>>> x = (1,2,3)
>>> x[1:]
(2, 3)
>>> x[0]
1
>>>len(x)
3
8/2/2019 Harsh Python
13/39
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]
8/2/2019 Harsh Python
14/39
Dictionaries: Add/Modify
Entries can be changed by assigning to that
entry
Assigning to a key that does not exist adds an
entry
>>> 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]}
8/2/2019 Harsh Python
15/39
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'}
8/2/2019 Harsh Python
16/39
Variables
Are not declared, just assigned
The variable is created the first time youassign it a value
Are references to objects
Everything in Python is an object
Variables must be assigned before they can be
used in expressions
8/2/2019 Harsh Python
17/39
Control Flow Statements
If Statements
For Loops
While Loops
8/2/2019 Harsh Python
18/39
If Statements
>>> x = 'killer rabbit'
>>> if x == 'roger':
print("how's jessica?")
elif x == 'bugs':print("what's up doc?")
else:
print('Run away! Run away!')
Run away! Run away!
8/2/2019 Harsh Python
19/39
No Braces???
Python uses indentation instead of braces todetermine the scope of expressions
All lines must be indented the same amount
to be part of the scope (or indented more ifpart of an inner scope)
This forces the programmer to use proper
indentation since the indenting is part of theprogram!
8/2/2019 Harsh Python
20/39
While Loops
While Loop:
x = 1
while x < 10 :
print x
x = x + 1
>>> import whileloop
1
23
4
5
6
7
89
>>>In whileloop.py
8/2/2019 Harsh Python
21/39
For Loops
>>>for varin sequence:
statements
range() function generateslists of numbers :
range (5) -> [0,1,2,3,4]
Example:
mylist=*hello,hi,hey,!+;
for i in mylist:
print i
8/2/2019 Harsh Python
22/39
Grouping Indentation
In Python In C
for i in range(20):
if i%3 == 0:
print i
if i%5 == 0:
print "Bingo!"
print "---"
for (i = 0; i < 20; i++)
{if (i%3 == 0) {
printf("%d\n", i);if (i%5 == 0) {
printf("Bingo!\n"); }}
printf("---\n");}
0
Bingo!
------
---
3
---
---
---
6
---
------
9
---
---
---
12
---
---
---
15
Bingo!
---
---
---
18
---
---
8/2/2019 Harsh Python
23/39
Loop Control Statements
break Jumps out of the closest enclosing loop
continue Jumps to the top of the closest enclosing loop
8/2/2019 Harsh Python
24/39
Functions
Use the 'def' statement
Function body follows; indented!
Basic Def:
def name ([arg 1 , arg 2, +):
statement 1
.
statement n
[return [expression]]
8/2/2019 Harsh Python
25/39
Example Function
def greet(name):
print 'hello', name
greet('Jack')
greet('Jill')
greet('Bob')
8/2/2019 Harsh Python
26/39
The return Statement:
The statement return [expression] exits a function, optionally
passing back an expression to the caller.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them.total = arg1 + arg2
print "Inside the function : ", total
return total;
# Now you can call sum function
total = sum( 10, 20 );
print "Outside the function : ", total
8/2/2019 Harsh Python
27/39
Defining a Class
A class is a special data type which defines how to
build a certain kind of object
Classes are designed to create and manage newobjects
Instances are objects that are created which follow
the definition given inside of the class
You just define the class and then use it
8/2/2019 Harsh Python
28/39
Methods in Classes
Define a methodin a class by including
function definitions within the scope of the
class block
There must be a special first argument self
in allof method definitions which gets bound
to the calling instance
There is usually a special method called
__init__in most classes
8/2/2019 Harsh Python
29/39
Example
>>> class ExampleClass:def __init__(self, some_message):
self.message = some_message
print "New Class instance created, with message:"
print self.message
>>> first_instance = ExampleClass("message1")
New Class instance created, with message:
message1
>>> second_instance = ExampleClass("message2")
New Class instance created, with message:
message2
8/2/2019 Harsh Python
30/39
Instantiating Objects
There is no new keyword as in Java.
Just use the class name with ( ) notation and
assign the result to a variable
__init__ serves as a constructor for the
class. Usually does some initialization work
The arguments passed to the class name are
given to its __init__() method
8/2/2019 Harsh Python
31/39
Constructor: __init__
An __init__ method can take any number
of arguments.
__init__ is a kind of constructor, when an
instance of a class is created.
However, the first argument self in the
definition of __init__ is special
8/2/2019 Harsh Python
32/39
Self
The first argument of every method is a referenceto the current instance of the class
By convention, we name this argument self
In __init__, selfrefers to the object currentlybeing created; so, in other class methods, it refers
to the instance whose method was called
Similar to the keyword this in Java or C++ But Python uses selfmore often than Java uses
this
8/2/2019 Harsh Python
33/39
Deleting instances: No Need to free
When you are done with an object, you donthave to delete or free it explicitly.
Python has automatic garbage collection.
Python will automatically detect when all ofthe references to a piece of memory havegone out of scope. Automatically frees thatmemory.
Theres also no destructor method forclasses
8/2/2019 Harsh Python
34/39
Importing and 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 Three formats of the command:
import somefile
from somefile import *
from somefile import className
The difference? What gets imported from the file and what
name refers to it after importing
8/2/2019 Harsh Python
35/39
import
import somefile
Everything in somefile.py gets imported.
To refer to something in the file, append the textsomefile. to the front of its name:
somefile.className.method(abc)
somefile.myFunction(34)
8/2/2019 Harsh Python
36/39
from import *
from somefile import *
Everything in somefile.py gets imported
Take care! Using this import command can easily
overwrite the definition of an existing function or
variable!
className.method(abc)
myFunction(34)
8/2/2019 Harsh Python
37/39
from import
from somefile import className
Only the item className in somefile.py gets imported.
Take care! Overwrites the definition of this name if
already defined in the current namespace!
className.method(abc) imported
myFunction(34) Not imported
8/2/2019 Harsh Python
38/39
Compared to Java
Code up to 5 times shorter and more readable
Multiple inheritance
Quicker development
no compilation phase
less typing
Yes, it may run a bit slower
but development is much faster
and Python uses less memory (studies show)
8/2/2019 Harsh Python
39/39
Compared to C/C++
Python code is often 5-10 times shorter than
equivalent C++ code!
No compilation phase
No need to declare the variables.
Recommended