By Carmen Berros / @mcberros
Interactive Interpreter
$python # Unix/Linux
python% # Unix/Linux
C:>python # Windows/DOS
Script from the Command-line
$python script.py # Unix/Linux
python% script.py # Unix/Linux
C:>python script.py # Windows/DOS
#! /usr/bin/env python
$ chmod +x myscript.py
# First comment example
var = 1 # second comment
# ... and now a third
def get_var_l(l):
# Compute var r
if len(l) <= 1:
return [l]
def perm(l):
# Compute var r
if len(l) <= 1:
return [l]
All other values are considered as True
Operation | Result |
---|---|
x and y | if x is false, then x, else y |
x or y | if x is false, then y, else x |
not x | if x is false, then True, else False |
Operation | Result |
---|---|
x+y | sum of x and y |
x-y | difference of x and y |
x*y | product of x and y |
x/y | quotient of x and y |
x//y | (floored) quotient of x and y |
x%y | remainder of x / y |
-x | x negated |
+x | x unchanged |
Operation | Result |
---|---|
abs(x) | absolute value or magnitude of x |
int(x) | x converted to integer |
long(x) | x converted to long integer |
float(x) | x converted to floating point |
divmod(x,y) | the pair (x//y,x%y) |
x**y | x to the power y |
There isn't a character type; these are treated as strings of length one
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
This function converts the expressions you pass it to a string and writes the result to standard output
>>> print 'Hello World!'
Hello World!
>>> print 10
10
>>> name ='Zara'
>>> weight=55
>>> sentence='My name is %s and my weight is %d' % (name,weight)
>>> print sentence
My name is Zara and my weight is 12
Lists are mutable: support additional operation
s that allow in-place modification of the object
list1 = [1990, 1992, 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
tup1 = (1990, 1992, 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = ("a", "b", "c", "d")
print u'Hello, world!'
Operation | Result |
---|---|
x in s | True if an item of s is equal to x, else False |
x not in s | False if an item of s is equal to x, else True |
s + t | the concatenation of s and t |
s * n, n * s | n copies of s concatenated |
len(s) | length of s |
s.index(i) | index of the first occurence of i in s |
s.count(i) | total number of occurences of i in s |
s[i] | ith item of s, origin 0. If i > len(s) then raises IndexError |
Operation | Result |
---|---|
s[i:j] | slice of s from i to j. If j > len(s) then return until the end of the string |
|
|
s[i:j:k] | slice of s from i to j with step k |
|
Operation | Result |
---|---|
s[i]=x | item i of s is replaced by x |
s[i:j] = t | slice of s from i to j is replaced by the contents of the iterable t |
del s[i:j] | same as s[i:j] = [] |
s.append(x) | same as s[len(s):len(s)] = [x] |
s.extend(x) | same as s[len(s):len(s)] = x |
s.count(x) | return number of i‘s for which s[i] == x |
Operation | Result |
---|---|
s.insert(i, x) | same as s[i:i] = [x] |
s.pop([i]) | same as x = s[i]; del s[i]; return x |
s.remove(x) | same as del s[s.index(x)] |
s.reverse() | reverses the items of s in place |
s.sort([cmp[, key[, reverse]]]) | sort the items of s in place |
dict = {'Mercy': 12, 'Joe': 17, 'Henry': 45}
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
# Wins 'Manni'
# Nooooooo
dict = {['Name']: 'Zara', 'Age': 7};
Operation | Result |
---|---|
len(d) | Return the number of items in the dictionary d |
d[key] | Return the item of d with key key. Raises a KeyError if key is not in the map |
d[key] = value | Set d[key] to value |
del d[key] | Remove d[key] from d. Raises a KeyError if key is not in the map |
key in d | Return True if d has a key key, else False. |
key not in d | Equivalent to not key in d |
Operation | Result |
---|---|
popitem() | Remove and return an arbitrary (key, value) pair from the dictionary. |
clear() | Remove all items from the dictionary |
copy() | Return a shallow copy of the dictionary |
Operation | Result |
---|---|
items(), iteritems() | items() return a copy of the dictionary’s list of (key, value) pairs. iteritems() return an iterator over the dictionary’s (key, value) pairs |
keys(), iterkeys(), iter(d) | keys() return a copy of the dictionary’s list of keys. iterkeys() and iter(d), return an iterator over the dictionary’s keys. |
values(), itervalues() | values() return a copy of the dictionary’s list of values. itervalues() return an iterator over the dictionary’s values. |
Operation | Meaning |
---|---|
< | strictly less than |
<= | less than or equal |
> | strictly greater than |
>= | greater than or equal |
== | equal |
!= | not equal |
is | object identity |
is not | negated object identity |
Operator | Description |
---|---|
or | Boolean OR |
and | Boolean AND | not x | Boolean NOT |
in, not in, is, is not, <, <=, >, >=, <>, !=, == | Comparisons, membership tests , identity tests |
+, - | Addition, subtraction |
*, /, //, % | Multiplication, division, remainder |
+x, -x | Positive, negative |
** | Exponentiation |
Operator | Description |
---|---|
x[index], x[index:index], x(arguments...), x.attribute | Subscription, slicing, call, attribute reference |
(expressions...), [expressions...], {key:value...}, `expressions...` | Binding or tuple display, list display, dictionary display, string conversion |
The equal sign ('=') is used to assign a value to a variable
width = 20
height = 5*9
A value can be assigned to several variables simultaneously
x = y = z = 0 # Zero x, y and z
»> x,y = 1,2
»> x,y
(1, 2)
# equal as
»> x, y = [1,2]
»> x, y = (1,2)
Python 3 deprecates this feature and offers taking rest of tuple into last variable
»> x,y,*z = 1,2,3,4,5
»> x,y,z
(1, 2, [3, 4, 5])
#!/usr/bin/python
var1 = 100
if var1:
print "var1 is true"
#!/usr/bin/python
var2 = 0
if not var2:
print "var2 is false"
print "Out if"
var = 100
if var > 100:
print "var > 100"
elif var < 100:
print "var < 100"
else:
print "var == 100"
#!/usr/bin/python
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is greater than 5"
for iterating_var in sequence:
statements(s)
#!/usr/bin/python
fruits = ['banana', 'apple', 'mango']
for fruit in fruits:
print 'Current fruit :', fruit
A more concise way to create lists
>>> print [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print [i for i in range(20) if i%2 == 0]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> nums = [1,2,3,4]
>>> fruit = ["Apples", "Peaches", "Pears", "Bananas"]
>>> print [(i,f) for i in nums for f in fruit]
[(1, 'Apples'), (1, 'Peaches'), (1, 'Pears'), (1, 'Bananas'),
(2, 'Apples'), (2, 'Peaches'), (2, 'Pears'), (2, 'Bananas'),
(3, 'Apples'), (3, 'Peaches'), (3, 'Pears'), (3, 'Bananas'),
(4, 'Apples'), (4, 'Peaches'), (4, 'Pears'), (4, 'Bananas')]
def add(a, b): # add 2 numbers
"""Add to numbers."""
c = a + b
return c
# Now call the function we just defined:
add(1, 2)
3
def print_arg(arg):
print arg
>>> print_arg()
Traceback (most recent call last):
File "", line 1, in
TypeError: print_arg() takes exactly 1 argument (0 given)
>>>
#!/usr/bin/python
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return
# Now you can call printinfo function
printinfo( age=50, name="miki" )
#!/usr/bin/python
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )
#!/usr/bin/python
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
# Now you can call printinfo function
printinfo( 10 );
printinfo( 70, 60, 50 );
# Module hello in hello.py file
def print_func( par ):
print "Hello : ", par
return
# Using the module hello
#!/usr/bin/python
import hello
hello.print_func("Zara")
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
Call the class using class name and pass in whatever arguments its __init__ method accepts
# This would create first object of Employee class
emp1 = Employee("Zara", 2000)
# This would create second object of Employee class
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
#!/usr/bin/python
class Parent: # define parent class
def __init__(self):
print "Calling parent constructor"
def parentMethod(self):
print 'Calling parent method'
class Child(Parent): # define child class
def __init__(self):
print "Calling child constructor"
def childMethod(self):
print 'Calling child method'
c = Child() # instance of child
c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
class A: # define your class A
.....
class B: # define your class B
.....
class C(A, B): # subclass of A and B
class Parent: # define parent class
def myMethod(self):
print 'Calling parent method'
class Child(Parent): # define child class
def myMethod(self):
print 'Calling child method'
c = Child() # instance of child
c.myMethod() # child calls overridden method
#result
Calling child method
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
#result
Vector(7,8)
#!/usr/bin/python
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print self.__secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount
#Result
1
2
Traceback (most recent call last):
File "test.py", line 12, in
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'
print counter._JustCounter__secretCount
# Result
2