Programming Fundamentals
Lecturer xxx
Control flow
tools
i = 1
• While loops have the following
general structure. while i < 4:
print i
while expression: i = i + 1
statements flag = True
• Here, statements refers to one or while flag and i < 8:
more lines of Python code. The
conditional expression may be any print flag, i
expression, where any non-zero i = i + 1
value is true. The loop iterates while 1
the expression is true. 2
• Note: All the statements indented 3
by the same amount after a True 4
programming construct are
considered to be part of a single True 5
block of code. True 6
True 7
Control flow
tools
a = 1
b = 0
• The if statement has the if a:
following general form. print "a is true!“
if expression: if not b:
statements print "b is false!“
if a and b:
print "a and b are true!“
if a or b:
• If the boolean expression print "a or b is true!"
evaluates to True, the
a is true!
statements are executed. b is false!
Otherwise, they are a or b is
skipped entirely. true!
Control flow
tools
a = 1
• You can also pair an else b = 0
with an if statement. c = 2
if a > b:
if expression: if a > c:
statements print "a is greatest"
else: else:
statements print "c is greatest"
• The elif keyword can be elif b > c:
used to specify an else if print "b is greatest"
statement. else:
• Furthermore, if print "c is greatest"
statements may be nested
within eachother. c is greatest
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 is
evaluated first. Then, the first item in the vowel: a
sequence is assigned to the iterating variable vowel:
var. Next, the statements are executed. Each e
item in the sequence is assigned to var, and
the statements are executed until the entire vowel: i
sequence is exhausted. vowel: o
• For loops may be nested with other control vowel:
flow tools such as while loops and if u 1
statements. 2
3
0
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,-
range of integers, typically used in for loops. 2):
These functions are range() and xrange().
print i
• They both create a sequence of integers, but
range() creates a list while xrange() creates an
xrange object. 0
• Essentially, range() creates the list statically 1
while xrange() will generate items in the list as 2
they are needed. We will explore this concept 3
further in just a week or two. 0
2
• For very large ranges – say one billion values – 4
you should use xrange() instead. For small 6
ranges, it doesn’t matter. 20
18
16
Control flow
tools for num in range(10,20):
if num%2 == 0:
continue
• There are four statements for i in range(3,num):
provided for manipulating loop if num%i == 0:
structures. These are break, break
continue, pass, and else. else:
print num, 'is a prime
• break: terminates the number'
current loop.
• continue: immediately begin 11 is a prime number
the next iteration of the loop. 13 is a prime
• pass: do nothing. Use when a number 17 is a
statement is required syntactically. prime number 19 is
• else: represents a set of a prime number
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.
• 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 == Python supports multiple
0: assignment at once.
total = total + f1 Right hand side is fully
f1, f2 = f2, f1 + f2 evaluated
print(total) before setting the
variables.
Output: 4613732
functions
# Defining the function
def print_greeting():
• A function is created with the def print "Hello!"
keyword. The statements in the block print "How are you
of the function must be indented. today?"
def function_name(args): print_greeting() #
Calling the function
• The defskteaytweomrednitssfollowed by
the function name with round
brackets enclosing the arguments Hello!
and a colon. The indented statements How are you today?
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 somelist[0] = 3
language are passed by return 1, 2
myname = "Ben"
reference. mylist = [1,2]
a,b = hello_func(myname,
• However, only mutable mylist) print myname, mylist
objects can be changed in print a, b
the called function.
Hello, Ben !
• We will talk about this in
more detail Ben [3, 2]
12
later.
Function
s
• What is the output of the following code?
Hello, Susan !
Hello, Peter !
Hello, William !
def hello_func(names): The names are
for n in names: now [‘Susie’,
print "Hello,", n, "!" ‘Pete’, ‘Will’] .
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
The Python interpreter will set some special def even_fib():
environmental variables when it starts executing. total = 0
f1, f2 = 1, 2
If the Python interpreter is running the module (the while f1 <
source file) as the main program, it sets the special 4000000:
name variable to have a value " main ". if f1 % 2
This == 0:
allows for flexibility is writing your modules. total = total + f1
f1, f2 = f2, f1 + f2
Note: name , as with other built-ins, has two underscores on
return total
either side!
if name == " main
":
print(even_fib())
input
• raw_input()
• Asks the user for a string of
input, and returns the string.
>>> print(raw_input('What is your name? '))
• If you provide an What is your name? Caitlin
argument, it will be used as a Caitlin
prompt.
>>> print(input('Do some math: '))
• input() Do some math: 2+2*5
• Uses raw_input() to grab a 12
string of data, but then tries to
evaluate the string as if it were a
• PythonReturns
expression.
the value
of the expression.
• Dangerous – don’t use
it.
Note: In Python 3.x, input() is now
just an alias for raw_input()
A solution with
input
Enter the max Fibonacci number: 4000000
from future import print_function 4613732
def even_fib(n):
total = 0
f1, f2 = 1, 2
while f1 < n:
if f1 % 2 == 0:
total = total + f1
f1, f2 = f2, f1 + f2
return total
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.