11/7/17
A simpler language
• C:
Python Programming printf(“Int val is %d; string val is %-20s\n”,
12, “hello”);
Harry S. Delugach, Ph.D.
Computer Science Department
University of Alabama in Huntsville • Python:
SRE-RAM
November 9, 2017 print("Int val is",12,"; string val is", “hello")
An interpreted language Features
• Statements are processed one-by-one • Interpreted language with dynamic strong typing
• Objects are created when they are assigned a value
• Simple but powerful data structures
• Interactive environment invoked to run python programs
• Supports object-oriented programming
• Command line interface
• Integrated help system
• IDLE runs a python shell
• Prompt is “>>> “ • Integrated module (library) system
• Continuation is “…” • Integrated documentation features
• Optional (and default-able) function arguments
• Code can be “compiled” for faster execution
Brief history Dynamic typing
• Created in the early 1990’s by Guido van Rossum at • Objects get a type when they get a value
Stichting Mathematisch Centrum (Netherlands)
• You can “ask” an object what type it is:
• 1995: Moved to Corporation for National Research
>>> a = 42
Initiatives (CNRI) in Reston, Virginia
>>> type( a )
<class ‘int'>
• 2000-2001: Moved to Python Software Foundation (PSF).
Zope Corporation is a sponsoring member.
>>> a = 42.5
>>> type( a )
• All Python releases are Open Source
<class ‘float'>
• Python versions 2.x.x were to end in 2015, but extended to
>>> a = "hello"
2020
>>> type( a )
<class 'str'>
• Python versions 3.x.x are backward-incompatible with 2.x.x
1
11/7/17
Strong typing Test an object’s type
• Dynamic typing doesn’t mean “anything goes”
• Object reference must already exist
• Objects’ types must match
>>> a = 42
• You can test for an object’s type:
>>> b = 13
>>> a + b
55 >>> a = “hello"
>>> a = "hello"
>>> type(a)
>>> a + b
Traceback (most recent call last): <class ‘str'>
File "<stdin>", line 1, in <module>
TypeError: must be str, not int >>> type(a) is str
True
>>> fib("hello")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in fib
TypeError: '<' not supported between instances of 'int' and
'str'
Functions Some more features
Block begin
statement ends
Multiple
with “:”
def fib(n): assignment on one
line
a, b = 0, 1 def fib(n): No parentheses for
conditions
while a < n:
Optional named
a, b = 0, 1
print(a, end=' ') arguments while a < n:
a, b = b, a+b
print()
print(a, end=' ')
a, b = b, a+b
Optional arguments
>>> fib(1000) print()
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 Multiple assignment
evaluates all right-
hand side before
executing
Indentation
denotes nesting
Default arguments Conditional statement
def ask_ok(prompt, retries=4, reminder='Please try again!'):
while True:
ok = input(prompt) >>> x = int(input("Please enter an integer: "))
if ok in ('y', 'ye', 'yes'): Please enter an integer: 42
return True
if ok in ('n', 'no', 'nop', 'nope'): >>> if x < 0:
return False
retries = retries - 1
... x = 0
if retries < 0: ... print('Negative changed to zero')
raise ValueError('invalid user response')
print(reminder)
... elif x == 0:
... print('Zero')
>>> ask_ok( "Enter yes or no: ")
... elif x == 1:
Enter yes or no: huh? ... print('Single')
Please try again!
Enter yes or no: yes
... else:
True ... print('More')
>>> ask_ok( "Enter yes or no: ", reminder="Wrong answer!" ) ...
Enter yes or no: huh? More
Wrong answer!
Enter yes or no: yes
True
2
11/7/17
Compound values Loop statement
• List is an ordered set of values delimited by square brackets
[ “this”, “is”, “a”, “test” ]
• List can be heterogeneous
[ “some text”, 42, 8.333, ‘hello’ ] “for” statement operates on a set of values in order:
• List can be empty >>> words = ['cat', 'window', 'defenestrate']
[ ]
>>> for w in words:
• List elements accessible by index in the usual way ... print(w, len(w))
>>> a = [ "this", "is", "a", "test" ] ...
>>> a[1] cat 3
'is' window 6
>>> a[4] defenestrate 12
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
• List elements also accessible by “slicing”
Iterating with integers List “slicing”
• The “range” iterator produces a list of integers:
range(5) produces 0,1,2,3,4
days =
["Sun","Mon","Tue","Wed","Thu","Fri","Sat" ]
range(2,5) produces 2,3,4
>>> days[0:3]
range(0,10,2) produces 0, 2, 4, 6, 8 ['Sun', 'Mon', 'Tue']
>>> days[:2]
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
['Sun', 'Mon']
>>> for i in range(len(a)): >>> days[2:]
... print(i, a[i]) ['Tue', 'Wed', 'Thu', 'Fri', 'Sat']
... >>> days[-1]
0 Mary
1 had
‘Sat'
2 a
3 little
4 lamb
List functions Associative arrays
• Allows array “index” to be any key you want to look up a value
• append
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
• reverse >>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
• sort >>> tel['jack']
4098
>>> del tel['sape']
• len >>> tel['irv'] = 4127
>>> tel
• list “comprehensions” {'guido': 4127, 'irv': 4127, 'jack': 4098}
[x**2 for x in range(10)] >>> list([Link]())
['irv', 'guido', 'jack']
produces >>> sorted([Link]())
['guido', 'irv', 'jack']
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
3
11/7/17
Function docstring Function annotations
• Functions support a docstring (one or more lines)
• Accessible through __doc__ data attribute • Function argument types and return type can be declared (but not
checked!)
>>> def my_function(): def square( n : float ) -> float:
... “””Doesn’t do anything.""" """Returns the square of the given argument."""
... pass # a “do nothing” stmt return n * n
...
>>> square( 3.0 )
>>> print( my_function.__doc__) 9.0
Doesn’t do anything. >>> square.__annotations__
{'n': <class 'float'>, 'return': <class ‘float’>}
>>> help(my_function) >> square.__doc__
'Returns the square of the given argument.'
Help on function my_function in module __main__:
my_function()
Doesn’t do anything.
Classes Larger scale programming
• Python supports dynamically created classes • Use interactive shell for testing and debugging
• Constructor is called __init__
• Put tested/debugged functions into files
• Self reference is “self” (equiv. to “this”)
• All functions in a single file are called a module
>>> class Complex:
... def __init__(self, realpart, imagpart):
• Modules included with import command
... self.r = realpart
... self.i = imagpart
...
• Modules can have executable statements for
initialization the first time a module is loaded
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5) • Python has many built-in modules that do not require
import
Resources
• [Link]
• Download Python 3
• Tutorials and Documentation