An introduction to Python

Download Report

Transcript An introduction to Python

Jim Havrilla
Invoking Python
 Just type “python –m script.py [arg]” or “python –c
command [arg]”
 To exit, quit() or Control-D is used
 To just use the interpreter just type “python” and just
issue python commands (called interactive mode)
 FUN FACT: no semicolons needed in python!
 FUN FACT: in Python, the last printed expression can
be referenced as an automatically stored variable
called “_” in interactive mode
Argument passing
 To access arguments passed in a python script type
“import sys” and the arguments are stored in sys.argv
 When no arguments are given, sys.argv[0] is an empty
string
To handle error
 Type Control-C or DELETE (the interrupt character)
cancels the input and returns to the main prompt
 If a command is being executed, it raises the
KeyboardInterrupt exception which could be handled
with a try statement
Things about Python scripts
 # designates comments
 “$ chmod +x myscript.py” to make a script executable in
Unix, and “#! /usr/bin/env python” must go at the
beginning of the script
 “import” at the beginning of a script to make it import
things
 After the initial “#!” line one can define the source coding
style with a special comment like “# -*- coding: iso-8859-15
-*-”
 If you want the python interpreter to do certain things
during start-up, you can set an environment variable called
“PYTHONSTARTUP” to the name of the file containing the
startup commands
Numbers in Python
 Python interpreter can be used as a straight up calculator like





2+2 will come out as 4 with no extra syntax
Integer division/multiplication returns the floor, and integer +
floating point operations return floating point
An equal sign assigns a value to a variable but can do it to
several variables at once like “x=y=z=0”
Can also assign like so “a, b = 0, 1” and a=0, b=1
Variables don’t need type designation, but of course need a
value to be used or else an error will occur
Complex numbers are supported as well in the form of a =
complex(real,imaginary) or a = 3.0+1.5j and returned as
(real+imaginaryj); can be accessed in parts like a.real, a.imag,
or abs(a) gives its magnitude
Strings in Python
 Strings can be in single or double quotes, but usually in
single quotes unless the string is a single quote in two
double quotes
 A string can span several lines of code; newline
character is \n, and to indicate that the next line is a
continuation of the last the \ character is used
 Type “print” to print a string or just a given value of a
whole expression
 Can also surround strings in triple quote pairs “”” “”” or
‘’’ ‘’’ and then newline characters don’t need escaping
More about strings in Python
 Strings can be concatenated with “+” and if the strings are




just string literals they can be concatenated with just a space
between them like word = “lame” “Ya”
word = “lameYa”
Strings can be indexed like char arrays in C, so word[0] = l
Colon has different effects in indexing: “word[0:2] = la” or
“word[:2] = la” or “word[2:] = meYa”
If an index is too large it is replaced by the string size like for
example “word[1:1000] = ameYa”
If an index is too small or too negative it is truncated unless
it is a single-element reference (yes, you can use negative
indices as long as the last element is 0)
More on strings
 Can’t change parts of strings in python, but can easily




create a new string
len(string) returns its length, but length of a slice is
index2-index1
u‘string’ indicates a unicode based string and Python
Unicode-Escape encoding can be used for characters then
or ur‘string’ for raw unicode
unicode() gives access to all Unicode codecs, unicode
strings can be converted with str() to normal strings
string.encode(‘utf-8’) will encode in 8-bit or in whatever
coding is specified in encode()
Lists in Python
 list = [123, ‘abc’] is a list
 Can be indexed and concatenated like strings (but not




using a space)
Slice operations return a new list of the indexed elements
Individual elements of a list can be changed and can be
replaced by slice operations like list[0:1] = 3  list = [3,
‘abc’]
len() still gives length, range() generates arithmetic
progressions of numbers in a list like range(5,20,5) =
[5,10,15,20]
lists can contain other lists mixed with single elements like
list = [[‘k’, 23], ‘f’, 5]
Some syntax
 There is no {} for while or for loops or for if statements,
there must be a tab or spaces for each indented line,
everything within a block by the same amount
 Loop conditions don’t need to be written in
parentheses
 To instead print spaced answers instead of by newline
with print in a while loop use print b, next line instead
of print b next line (trailing comma dodges the
newline after output)
Control Flow in Python
 If statements don’t need elif or else parts but can have
as many elifs as needed, “if elif elif” statement is
equivalent to a switch or case statement
 For statements work as an iteration over items of a list
or sequence like “for x in list[:]:” and then the items are
executed in order that they appear
 Can use “for i in range(len(list)):
print i, a[i];”
to get an iteration through the list easily
More on Control Flow
 break statement breaks out of smallest enclosing loop,
to move on with going to “else” in an if statement for
example
 continue statement moves on with next iteration of
the loop
 pass statement does nothing and is used syntactically
for things like empty classes or used as a placeholder
when you are working on a function or condition
Functions in Python
 The term “def” introduces the definition of a function and is





followed by a function name and in parentheses a list of
arguments
def statement is like “def func(number):”
By default all variable assignments in a function store local
variables
return is used to give back a result
Function can be renamed as a variable and stored to be used in
the interpreter like
“f = func
f(423)”
>>> output
variable.append(new stuff) is the more efficient way to
concatenate new elements at the end of a list in a function
Some more function stuff
 To assign default values one just needs to set each argument in the
definition to a value like:
“def func(number=100, why=“not”, tiny)”
 Also, “in” can be used to test if a sequence has a value like “if func in
(‘no’, ‘not’)
return True”
 If the default value is a mutable object, it is evaluated only once, and a
function can accumulate arguments like
“def func(thing, list=[])
list.append(thing)
return list”
for “print func(1), func(‘f’), func(10)”
This would print “[1], [1,’f’], [1,’f’,10]”
 To fix the above just put if list is None for each call so that it doesn’t
append continually
A bit more on functions
 If a function is written like so “def func(arg, *name, **args)” then the formal parameter **args acts
as dictionary containing the keyword arguments except for the whats already a formal parameter or
*name in this case which just contains the positional arguments (a variable number not including
** args after *name)
 Like in
def func(arg1, *name, **args)
for arg in name:
print arg
key = args.keys()
for keyword in key:
print keyword, “-”, key[keyword]
“func(“hi”, “bye”, “try”, haha = “three”, nine = “five”)” would make
bye
try
haha – three
nine – five
 Functions can be called with arbitrary number of arguments
 Dictionaries can deliver keyword arguments into a function using the ** operator and the *operator
can unpack arguments from a list/tuple
 lambda function can be used to make small anonymous function inside function definition
 Like “def super(arg): return lambda q: q * arg” can be used to say
“func=super(5)
func(5)”
func(5) is equal to 25 and func(10) = 50
Documentation and Style
 Try using 4-space indentation instead of tabs
 Type a string in a function definition without print in
front of it and it can be seen by type func.__doc__ to
see what is called the docstring
Done!
 Any questions?