Download Introduction to Python

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Introduction to Python
March 25, 2015
Output
# Evaluates expression and prints result.
>>> 4 + 5
9
>>> 7 * 3
21
>>> "Hello, world!"
’Hello, world!’
# print-function is used when writing on standard output
>>> print("Hello, world!")
Hello, world!
Dynamically typed variables
>>> v = None
# Creates a new variable v on the stack holding
# a reference to an instance of NoneType.
>>> v = 42
# Updates the v variable with a reference to an
# instance of built-in type int of value 42.
>>> s = "Hello"
# Creates a new variable s on the stack holding a
# reference to a built-in type str object of value
# ’Hello’.
>>> s + v
#
#
#
#
#
>>> v + s
# Same as above but __add__ is invoked on 42.
Invokes the +-method, or more
__add__-method on the ’Hello’
referenced by the s variable.
a TypeError as the str object
to add an int to a str.
1
accurately, the
str object
This will raise
does not know how
>>> str(v)
’42’
# The str-function returns a printable string
# representation of the object. In this case
# ’42’. Invokes the objects __str__-method.
>>> s + str(v)
’Hello42’
# Returns the concatenated string ’Hello42’
>>> dir(s)
[’__add__’, ...]
>>> s, v = v, s
# Returns a list of the attributes defined for the
# object referenced by s.
# Multiple assignment: Swaps the values of v and s.
Lists
>>> l = [v, s]
>>> print l
[’Hello’, 42]
# Creates a list containing ’Hello’ and 42.
>>> l.append(3.0) # All kinds of types may be mixed in a list
>>> print l
[’Hello’, 42, 3.0]
>>> l.pop()
’3.0’
# Removes and returns the last element in list.
# Index arg may be given, i.e. l.pop(0) pops
# first element
>>> print l
[’Hello’, 42]
>>> l = range(1, 4)
# range([start], stop[, step]) is used to create
# lists containing arithmetic progressions# Useful for looping, for instance.
>>> print l
[1, 2, 3]
>>> l = l + [4, 5, 6]
>>> print l
[1, 2, 3, 4, 5, 6]
# Concatenation of lists
# Loop over each element in the list l and summarise in sum.
>>> for element in l:
...
the_sum += element
...
# Above loop will crash as sum is not defined. A NameError
2
# exception will be raised as Python cannot find the variable
# name the_sum.
>>> the_sum = 0
>>> for element in l:
...
the_sum += element
...
>>> print the_sum
21
List access and slicing
>>> lst = [’a’, ’b’, ’c’, ’d’]
#
#
#
#
#
Three arguments may be given to the []-method, : is used to
separate the arguments. First argument is the starting position.
Second argument is optional and denotes the end position. Third
argument is optional and is used for step. Negative arguments
denotes positions counting from the end of list.
>>> lst[1]
’b’
# Returns ’b’ as 1 is the second position in list.
>>> lst[-1]
’d’
# Returns the last element of the list.
>>> lst[7]
# Indexing outside of bounds will raise exception.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> lst[1:2]
[’b’]
# Returns a new list containing ’b’
>>> lst[:3]
# Returns everything from beginning of list to 4:th
[’a’, ’b’, ’c’] # index exclusive.
>>> lst[2:]
[’c’, ’d’]
# Returns everything from 3:rd index to end of list.
>>> lst[:]
# Returns a copy of the list
[’a’, ’b’, ’c’, ’d’]
>>> lst[::-1]
# Returns a copy of the list reversed.
[’d’, ’c’, ’b’, ’a’]
3
Tuples
# Tuples are like lists, only they are immutable and
# much more efficient than lists.
>>> t = (1, 2, 3, 4)
# Creates a new tuple. Parenthesis may be
# omitted.
>>> print t
(1, 2, 3, 4)
>>> t[2]
3
>>> t[2] = 1
# Raises exception!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ’tuple’ object does not support item assignment
>>> l = list(t)
# Creates a new list object containing a copy
# of the tuple: (1, 2, 3, 4)
# The reversed is also possible:
>>> t = tuple([1, 2, 3])
Associative arrays (Hashes/Dictionaries/Maps)
# Create a new dict, with unordered mappings.
>>> d = { ’one’: 1, ’two’: 2, ’three’: 3, ’four’: 4 }
>>> print d
{’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1}
# Note that order may differ!
>>> d[’one’]
1
# Lookup value stored under key ’one’]
>>> d[’three’] = d[’four’]
# Update dict with map ’three’: 4, overwriting
# previous mapping
>>> print d
{’four’: 4, ’three’: 4, ’two’: 2, ’one’: 1}
>>> d.keys()
4
[’four’, ’three’, ’two’, ’one’]
>>> d.has_key(’four’)
True
# Check if key ’four’ can be found in d
>>> 4 in d.values()
True
# values() returns a list of the dict’s
# values.
>>> for key, value in d.items():
# Loop over all keys and
...
print("{0} => {1}".format(key, value)) # values in the dict and
...
# print both keys and
four => 4
# values
three => 4
two => 2
one => 1
Control Structures, iteration, ranges again
#
#
#
#
The Python if-statement begins with "if" and a conditional followed by a colon.
Remember that Python keeps track of nesting using indentation.
Just like in Ruby, "None" and "False" evaluates to false in Python. However,
0 evaluates to false, like in C.
>>> if None:
...
print "None is true"
...
>>> if False:
...
print "False is true"
...
>>> if 0:
...
print "0 is true"
...
# Logical operators ("and" and "or") can be used to combine
# conditionals. Also note that empty sequences evaluates to
# to false in Python.
>>> if 0 or [] or {} or ’’:
...
print "0 or [] {} or ’’ is true"
...
# If-statements can be combined using "elif". The "else" clause
# will be run if none of the conditionals above evaluated to
# true.
5
>>> name = "Guido"
>>> if name == "Yukihiro":
...
print "Ruby"
... elif name == "Guido":
...
print "Python"
... else:
...
print "None of the above"
...
Python
#
#
#
#
#
#
"or" and "and" will be evaluated as boolean true/false.
Like Ruby, "and" and "or" does also return values.
In case the first operand is false, "and" will return its value,
otherwise the second operand will be returned.
In case the first operand is true, "or" will return its value,
otherwise the second operand will be returned.
>>> names = {"Yukihiro": "Ruby", "Guido": "Python"}
>>> print names[name] or "None of the above"
Python
>>> result = (False or ’Beatrice’ or False)
>>> result
’Beatrice’
>>> result = ("Beatrice" and [] and ’Erik’)
>>> result
[]
# Negation of boolean values is done using "not".
>>> not False
True
# The Python while-loop starts with "while" and a conditional
# followed by a colon.
>>> i = 0
>>> while i < 10:
...
print i
...
i += 1
...
0
1
.
.
8
6
9
# Several other ways of looping exists for example iterating
# over a range.
>>> lst = range(1, 10)
>>> for i in lst:
...
print i
...
1
2
.
.
8
9
#
#
#
#
Below we see an example of operations that we could do with
lists. Using the "zip" function we create a new list
containing tuples of the elements from the original lists
that were found on the same index.
>>> cs = ’abc’
>>> ns = [1, 2, 3]
>>> z = zip(cs, ns)
>>> z
[(’a’, 1), (’b’, 2), (’c’, 3)]
# The list of tuples is looped over using a standard for-loop
# and assignment of multiple variables.
>>> for k, v in z:
...
print k, v
...
a 1
b 2
c 3
# We can unpack the zipped list using the zip-function. The
# *-operator does in this context unpack the list and passes
# the elements as arguments to the zip-function.
>>> char, nums = zip(*z)
>>> char
(’a’, ’b’, ’c’)
>>> nums
(1, 2, 3)
# We can reverse the tuples in the list using list comprehensions.
>>> rev = [(n, c) for c, n in z]
7
>>> rev
[(1, ’a’), (2, ’b’), (3, ’c’)]
# Lambda functions lets you define anonymous functions; functions
# that are not defined by a name.
>>> g = lambda x: x**2
>>> g(4), g(6), g(10)
(16, 36, 100)
#
#
#
#
#
#
Lambda functions are often used together with functions like
filter(), map() and reduce(). The map() functions takes two
arguments, one function and one list that the function should
be applied to all elements of.
This example will take a sentence, and return a list containing
all words in the sentence and their length.
>>> name = "Guido van Rossum"
>>> zip(name.split(), map(lambda word: len(word), name.split()))
[(’Guido’, 5), (’van’, 3), (’Rossum’, 6)]
8