Programming Fundamentals: Lecturer XXX

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 30

Programming Fundamentals

Lecturer xxx
What will I be
doing? Weighting (% of total marks
Type of Assessment When assessed for the unit)

Week 6
Assessment 1: midterm exam 15%

Week 3
Assessment 2: Quizzes Week 8 5%

Week 10
Assessment 3: Individual programming assignment 20%

Assessment 4: final exam Week 14 60%


The
Book.
Mark Lutz. (2013), Learning Python,
5th Edition. O'Reilly Media, ISBN:
978-1449355739
Getting
Help.

Office Hours.

Can ask for help from your TA during labs.


Academic
Offences

You should do all the work that you submit (work by your
assignment partner counts).

Never look at another teams works.

Never show another team your work.

Applies to all drafts and partial solutions.

Discuss how to solve an assignment only with course
staff.
About
Python
• Development started in the 1980’s by Guido van Rossum.
• Only became popular in the last decade or so.
• Python 3.8+.
• Interpreted, very-high-level programming language.
• Supports a multitude of programming paradigms.
• OOP, functional, procedural, logic, structured, etc.
• General purpose.
• Very comprehensive standard library includes numeric modules, crypto
services, OS interfaces, networking modules, GUI support, development tools,
etc.
Philosoph
y
• From The Zen of Python (https://www.python.org/dev/peps/pep-0020/)
• Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to
guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Notable Features
• Easy to learn.
• Supports quick development.
• Cross-platform.
• Open Source.
• Extensible.
• Embeddable.
• Large standard library and active community.
• Useful for a wide variety of applications.
Getting Started
Before we can begin, we need to actually install Python!

The first thing you should do is download and install our custom guide
to setting up a virtual machine and write your first Python program.
We will be using an Ubuntu virtual machine in this course. All
instructions and examples will target this environment – this will make
your life much easier.
Do not put this off until your first assignment is due!
Getting Started
• Choose and install an editor.
• For Linux, I prefer SublimeText.
• Windows users will likely use Idle by default.
• Options include vim, emacs, Notepad++, PyCharm, Eclipse, etc.

Throughout this course, I will be using SublimeText in an Ubuntu


environment for all of the demos.
Interpreter
• The standard implementation of Python is interpreted.
• You can find info on various implementations here.
• The interpreter translates Python code into bytecode, and
this bytecode is executed by the Python VM (similar to Java).
• Two modes: normal and interactive.
• Normal mode: entire .py files are provided to the interpreter.
• Interactive mode: read-eval-print loop (REPL) executes statements
piecewise.
Interpreter: Normal mode
• Let’s write our first Python program!
• In our favorite editor, let’s create helloworld.py with the following
contents:
print "Hello, World!" Note: In Python 2.x, print is a statement. In
Python 3.x, it is a function. If you want to get
into the 3.x habit, include at the beginning:
from future import
• From the terminal: print_function

$ python helloworld.py Now, you can write


Hello, World! print(“Hello, World!”)
Interpreter: Normal mode
Let’s include a she-bang in the beginning of helloworld.py:

#!/usr/bin/env python
print "Hello, World!"

Now, from the terminal:

$ ./helloworld.py
Hello, World!
Interpreter: Interactive mode
$ python
>>> print "Hello, World!"
• Let’s accomplish the Hello, World!
>>> hellostring = "Hello,
same task (and more) in World!"
interactive mode. >>> hellostring
'Hello, World!'
>>> 2*5
10
• Some options: >>>
2*hello
-c : executes single string
command. 'Hello,
-O: use basic World!
Hello,
optimizations. World!'
-d: debugging info. >>> for
i in
More can be range(0
found here. ,3):
Some fundamentals

• Whitespace is significant in Python. Where other languages


may use {} or (), Python uses indentation to denote code blocks.
# here’s a comment
for i in range(0,3):
• Comments print i
def myfunc():
• Single-line comments denoted by #. """here’s a comment
• Multi-line comments begin and end with threaeb“osu.t
• Typically, multi-line comments are meant for documetnhteatmioynf.unc function"""
print "I'm in a
• Comments should express information that cafnunnocttiboen!
e"xpressed in code – do not restate code.
Python
typing
• Python is a strongly, dynamically typed language.
• Strong Typing
• Obviously, Python isn’t performing static type checking, but it does
prevent mixing operations between mismatched types.
• Explicit conversions are required in order to mix types.
• Example: 2 + “four”  not going to fly
• Dynamic Typing
• All type checking is done at runtime.
• No need to declare a variable or give it a type before use.

Let’s start by looking at Python’s built-in data types.


Numeric
Types
• The subtypes are int, long, float and complex.
• Their respective constructors are int(), long(), float(), and complex().
• All numeric types, except complex, support the typical
numeric operations you’d expect to find (a list is available here
).
• Mixed arithmetic is supported, with the “narrower” type widened
to that of the other. The same rule is used for mixed comparisons.
Numeric
Types $ python
>>> 3 + 2
• Numeric 5
• int: equivalent to C’s long int in 2.x but >>> 18 % 5
unlimited in 3.x. 3
• float: equivalent to C’s doubles. >>> abs(-7)
• 7
long: unlimited in 2.x and
unavailable in 3.x. >>> float(9)
• complex: complex numbers. 9.0
>>> int(5.3)
5
• Supported operations include
>>> complex(1,2)
constructors (i.e. int(3)), arithmetic,
negation, modulus, absolute value, (1+2j)
exponentiation, etc. >>> 2 ** 8
256
Sequence data types
• There are seven sequence subtypes: strings, Unicode strings, lists,
tuples, bytearrays, buffers, and xrange objects.
• All data types support arrays of objects but with varying
limitations.
• The most commonly used sequence data types are strings, lists, and
tuples. The xrange data type finds common use in the construction of
enumeration-controlled loops. The others are used less commonly.
Sequence types:
Strings
• Created by simply enclosing characters in either single- or double-
quotes.
• It’s enough to simply assign the string to a variable.
• Strings are immutable.
• There are a tremendous amount of built-in string methods (listed
here).
mystring = "Hi, I'm a string!"
Sequence types:
Strings
• Python supports a number of escape sequences such as ‘\t’, ‘\n’, etc.
• Placing ‘r’ before a string will yield its raw value.
• There is a string formatting operator ‘%’ similar to C. A list of string
formatting symbols is available here.
• Two string literals beside one another are automatically concatenated
together.
print "\tHello,\n" $ python ex.py
print r"\tWorld!\n" Hello,
print "Python is " "so cool."
\tWorld!\n
Python is so
cool.
Sequence Types: Unicode
Strings
myunicodestr1 = u"Hi Class!"
• Unicode strings can be used to store myunicodestr2 = u"Hi\u0020Class!"
and manipulate Unicode data. print myunicodestr1, myunicodestr2
• As simple as creating a normal newunicode = u'\xe4\xf6\xfc'
string print newunicode
(just put a ‘u’ on it!). newstr = newunicode.encode('utf-8')
print newstr
• Use Unicode-Escape encoding for
print unicode(newstr, 'utf-8')
special characters.
• Also has a raw mode, use ‘ur’ as
a Output:
prefix. Hi Class! Hi Class!
äöü
• To translate to a regular string, use äöü
the .encode() method. äöü
• To translate from a regular string to
Unicode, use the unicode() function.
Sequence Types:
Lists mylist = [42, 'apple', u'unicode apple', 5234656]
• Lists are an incredibly useful print mylist
compound data type. mylist[2] = 'banana'
• Lists can be initialized by print mylist
the constructor, or with a mylist[3] = [['item1', 'item2'], ['item3', 'item4']]
bracket structure containing print mylist
0 or more elements. mylist.sort()
Lists are mutable – it is print mylist
possible to change their print mylist.pop()
contents. They contain the mynewlist = [x*2 for x in range(0,5)]
additional mutable print mynewlist
operations.
Lists are nestable. Feel free [42, 'apple', u'unicode apple', 5234656]
to create lists of lists of [42, 'apple', 'banana', 5234656]
lists… [42, 'apple', 'banana', [['item1', 'item2'], ['item3', 'item4']]]
[42, [['item1', 'item2'], ['item3', 'item4']], 'apple', 'banana']
banana
[0, 2, 4, 6, 8]
Sequence data types
$ python
• Sequence >>> mylist = ["spam", "eggs", "toast"] # List of strings!
• str: string, >>> "eggs" in mylist
represented as a True
sequence of 8-bit >>> len(mylist)
characters in Python 2.x. 3
• unicode: stores an >>> mynewlist =
abstract sequence of ["coffee",
• codelist:points.
a compound, "tea"]
mutable data type that >>> mylist +
can hold items of varying mynewlist
types. ['spam',
• tuple: a compound, 'eggs',
immutable data type that 'toast',
can hold items of varying
types. Comma separated 'coffee',
items surrounded by 'tea']
parentheses. >>> mytuple =
• a few more – we’ll tuple(mynewlist
cover them later. )
>>> mytuple
Common sequence operations
Operation Result
x in s True if an item of s is equal to x, else False.
• All sequence x not in s False if an item of s is equal to x, else True.
data types s + t The concatenation of s and t.
support the s * n, n * s n shallow copies of s concatenated.
following s[i] ith item of s, origin 0.
operations. s[i:j] Slice of s from i to j.
s[i:j:k] Slice of s from i to j with step k.
len(s) Length of s.
min(s) Smallest item of s.
max(s) Largest item of s.
s.index(x) Index of the first occurrence of x in s.
s.count(x) Total number of occurrences of x in s.
Common sequence operations

• Mutable sequence types


further support the
following operations.
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 t.
del s[i:j] Same as s[i:j] = [].
s[i:j:k] = t The elements of s[i:j:k] are replaced by those of t.
del s[i:j:k] Removes the elements of s[i:j:k] from the list.
s.append(x) Add x to the end of s.
Common sequence operations

Mutable sequence types further


support the following operations.

s.extend(x) Appends the contents of x to s.


s.count(x) Return number of i’s for which s[i] == x.
s.index(x[, i[, j]]) Return smallest k such that s[k] == x and i <= k < j.
s.insert(i, x) Insert x at position i.
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.
Basic built-in data
types
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange']
• Set >>> fruit = set(basket)
>>> fruit
• set: an set(['orange', 'pear', 'apple'])
unordered >>> 'orange' in fruit
collection of unique True
objects. >>> 'crabgrass' in fruit
False
• frozenset: an >>> a =
immutable version of set('abracadabra')
set. >>> b = set('alacazam')
set(['a',
>>> a 'r', 'b', 'c', 'd'])
>>> a - b
set(['r', 'd', 'b'])
>>> a | b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
Basic built-in data
types
>>> gradebook = dict()
>>> gradebook['Susan Student'] = 87.0 • Mapping
>>> gradebook • dict: hash
{'Susan Student': 87.0} tables, maps a
>>> gradebook['Peter Pupil'] = 94.0
>>> gradebook.keys()
set of keys to
['Peter Pupil', 'Susan Student'] arbitrary objects.
>>> gradebook.values()
[94.0, 87.0]
>>> gradebook.has_key('Tina Tenderfoot')
False
>>> gradebook['Tina Tenderfoot'] = 99.9
>>> gradebook
{'Peter Pupil': 94.0, 'Susan Student': 87.0, 'Tina Tenderfoot': 99.9}
>>> gradebook['Tina Tenderfoot'] = [99.9, 95.7]
>>> gradebook
{'Peter Pupil': 94.0, 'Susan Student': 87.0, 'Tina Tenderfoot': [99.9, 95.7]}
Python Data
Types
• So now we’ve seen some interesting Python data types.
• Notably, we’re very familiar with numeric types, strings, and lists.

That’s not enough to create a useful program, so let’s get some


control flow tools under our belt.

You might also like