Lecture1 Cis4930
Lecture1 Cis4930
Python
ABOUT PYTHON
• Development started in the 1980’s by Guido van Rossum.
• Only became popular in the last decade or so.
• General purpose.
• Very comprehensive standard library includes numeric modules, crypto services,
OS interfaces, networking modules, GUI support, development tools, etc.
PHILOSOPHY
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.
#!/usr/bin/env python
print "Hello, World!"
$ ./helloworld.py
Hello, World!
INTERPRETER: INTERACTIVE
MODE $ python
>>> print "Hello, World!"
Let’s accomplish the Hello, World!
same task (and more) in >>> hellostring = "Hello, World!"
interactive mode. >>> hellostring
'Hello, World!'
>>> 2*5
10
Some options: >>> 2*hellostring
'Hello, World!Hello, World!'
-c : executes single >>> for i in range(0,3):
command. ... print "Hello, World!"
-O: use basic ...
optimizations. Hello, World!
Hello, World!
-d: debugging info. Hello, World!
More can be found here. >>> exit()
$
SOME FUNDAMENTALS
• Whitespace is significant in Python. Where other languages may
use {} or (), Python uses indentation to denote code blocks.
# here’s a comment
• Comments for i in range(0,3):
print i
• Single-line comments denoted by #.
def myfunc():
• Multi-line comments begin and end with three “s. """here’s a comment about
• Typically, multi-line comments are meant for documentation.
the myfunc function"""
print "I'm in a function!"
• Comments should express information that cannot be expressed
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.
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.
Furthermore, if statements
may be nested within c is greatest
eachother.
CONTROL FLOW TOOLS for letter in "aeiou":
print "vowel: ", letter
for i in [1,2,3]:
The for loop has the following general form. print i
for i in range(0,3):
for var in sequence: print i
statements
If a sequence contains an expression list, it vowel: a
is evaluated first. Then, the first item in the vowel: e
sequence is assigned to the iterating vowel: i
variable var. Next, the statements are
vowel: o
executed. Each item in the sequence is
assigned to var, and the statements are vowel: u
executed until the entire sequence is 1
exhausted. 2
3
For loops may be nested with other control
flow tools such as while loops and if 0
statements. 1
2
CONTROL FLOW TOOLS for i in xrange(0, 4):
print i
for i in range(0,8,2):
print i
Python has two handy functions for creating a
for i in range(20,14,-2):
range of integers, typically used in for loops.
print i
These functions are range() and xrange().
They both create a sequence of integers, but
range() creates a list while xrange() creates an 0
xrange object. 1
2
Essentially, range() creates the list statically 3
while xrange() will generate items in the list as 0
they are needed. We will explore this concept 2
further in just a week or two. 4
For very large ranges – say one billion values – 6
you should use xrange() instead. For small 20
ranges, it doesn’t matter. 18
16
CONTROL FLOW TOOLS for num in range(10,20):
if num%2 == 0:
continue
for i in range(3,num):
There are four statements provided
if num%i == 0:
for manipulating loop structures.
These are break, continue, pass, break
and else. else:
print num, 'is a prime number'
• break: terminates the current loop.
• continue: immediately begin the 11 is a prime number
next iteration of the loop. 13 is a prime number
17 is a prime number
• pass: do nothing. Use when a 19 is a prime number
statement is required syntactically.
• else: represents a set of
statements that should execute
when a loop terminates.
OUR FIRST REAL PYTHON
PROGRAM
Ok, so we got some basics out of the way. Now, we can try to
create a real program.
I pulled a problem off of Project Euler. Let’s have some fun.
if __name__ == "__main__":
limit = raw_input(“Enter the max Fibonacci number: ")
print(even_fib(int(limit)))
CODING STYLE
So now that we know how to write a Python program, let’s break for
a bit to think about our coding style. Python has a style guide that
is useful to follow, you can read about PEP 8 here.
I encourage you all to check out pylint, a Python source code
analyzer that helps you maintain good coding standards.