Lecture1 Cis4930
Lecture1 Cis4930
ABOUT PYTHON
• Development started in the 1980’s by Guido van Rossum.
• Only became popular in the last decade or so.
• Python 2.x currently dominates, but Python 3.x is the future of Python.
• 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.
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.
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:
#!/usr/bin/env python
print "Hello, World!"
$ ./helloworld.py
Hello, World!
INTERPRETER: INTERACTIVE
MODE $ python
>>> print "Hello, World!"
Let’s accomplish the same task Hello, World!
(and more) in interactive mode. >>> hellostring = "Hello, World!"
>>> hellostring
'Hello, World!'
>>> 2*5
Some options: 10
-c : executes single command. >>> 2*hellostring
'Hello, World!Hello, World!'
-O: use basic optimizations. >>> for i in range(0,3):
-d: debugging info. ... print "Hello, World!"
More can be found here. ...
Hello, World!
Hello, World!
Hello, World!
>>> 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"""
• Comments should express information that cannot be expressed print "I'm in a function!"
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.
• 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 unlimited in >>> 18 % 5
3.x. 3
• float: equivalent to C’s doubles. >>> abs(-7)
• long: unlimited in 2.x and unavailable in 3.x. 7
• complex: complex numbers. >>> float(9)
9.0
• Supported operations include constructors (i.e. int(3)), >>> int(5.3)
arithmetic, negation, modulus, absolute value, 5
exponentiation, etc. >>> complex(1,2)
(1+2j)
>>> 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).
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.
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four
million, find the sum of the even-valued terms.
A SOLUTION USING BASIC
PYTHON
from __future__ import print_function Notice we’re using the Python 3.x
version of print here.
total = 0
f1, f2 = 1, 2
while f1 < 4000000:
if f1 % 2 == 0: Python supports multiple
total = total + f1 assignment at once.
f1, f2 = f2, f1 + f2 Right hand side is fully evaluated
print(total) before setting the variables.
Output: 4613732
FUNCTIONS
# Defining the function
def print_greeting():
A function is created with the def keyword. print "Hello!"
The statements in the block of the function print "How are you today?"
must be indented.
print_greeting() # Calling the function
def function_name(args):
statements Hello!
How are you today?
The def keyword is followed by the function
name with round brackets enclosing the
arguments and a colon. The indented
statements form a body of the function.
The return keyword is used to specify a list
of values to be returned.
FUNCTIONS def hello_func(name, somelist):
print "Hello,", name, "!\n“
name = "Caitlin"
All parameters in the Python language somelist[0] = 3
are passed by reference. return 1, 2
myname = "Ben"
However, only mutable objects can be mylist = [1,2]
changed in the called function. a,b = hello_func(myname, mylist)
print myname, mylist
We will talk about this in more detail
print a, b
later.
Hello, Ben !
Ben [3, 2]
12
FUNCTIONS
Hello, Susan !
What is the output of the following code? Hello, Peter !
Hello, William !
def hello_func(names): The names are now [‘Susie’, ‘Pete’, ‘Will’] .
for n in names:
print "Hello,", n, "!"
names[0] = 'Susie’
names[1] = 'Pete’
names[2] = 'Will’
names = ['Susan', 'Peter', 'William']
hello_func(names)
print "The names are now", names, "."
A SOLUTION WITH
FUNCTIONS
from __future__ import print_function
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.