Basics of Programming with Python A gentle guide to writing simple programs Robert Montante 1
Topics Part 3 Obtaining Python Interactive use Variables Programs in files Data types Decision-making Functions Repetition Lists 2
What is a function? A group of related program statements Act together to produce a specific small result Independent of other statements Can be called or invoked (or used) from somewhere else within a program Functions split a larger overall program into smaller, more easily manageable parts Better organization Easier to make changes Less duplication of statements 3
General Form of a Function 1 st line defines the function, gives it a name, lists any needed arguments Function's body is indented If the function produces a value, that value is returned (usually as the last statement) def cowtalk( msg ): message = 'Moo! ' + msg + ' Moo.' return message 4
Using a function A user-defined function is called just like any other function: words = raw_input( 'What message? ' ) themessage = cowtalk( words ) print 'The cow says ', themessage The function must be defined somewhere before it is called 5
a complete example 6
more examples def fairdie(): d = random.randint(1,6) return d def badcoin(): c = random.random() if c < 0.6 : flip = 'Heads' else: flip = 'Tails' return flip 7
Topics Part 3 Obtaining Python Interactive use Variables Programs in files Data types Decision-making Functions Repetition Lists 8
Repetition; Loops Many programs require an action to be repeated multiple steps in a random walk repeated coin tosses A loop allows the programmer to repeat things as often as desired as often as desired means? Some fixed number of times Until some Boolean test is True (or False) 9
"fixed" loops Repeat something a certain number of times, or once for each item in a list: this prints a message five times: for n in [1, 2, 3, 4, 5] : print "hello " this lists all the vowels: for v in ['a', 'e', 'i','o', 'u'] : print "vowel ", v Use a for loop 10
the for loop Required format: Remember the colon for <variable> <statement> <statement> in <list-of-values> : The for and in are required keywords The body must be indented relative to the loop The body includes as many statements as needed. <variable> can be used within the loop body (but doesn't have to be) 11
"for" specifics of use "for" performs a block of statements, just like "if" does "for" walks through a list use the range() function to generate a list of numbers "for" uses a variable the variable is assigned each value from the list in turn, and the statement block is performed using that value 12
Lists A list is just a collection of values, all inside of square brackets Examples: vowels: [ 'a', 'e', 'i', 'o', 'u' ] words: [ 'cat', 'dog', 'fish' ] numbers: [ 0, 22, -8, 3.14159, 0 ] Lists can be assigned to variables: v = [ 'a', 'e', 'i', 'o', 'u' ] monthlength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] 13
Counting things Use a list of numbers in order, to "count" things: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] This is a very common case Use the range() function to create a list of numbers: range(10) gives ten numbers, 0 through 9 range(5, 9) gives four numbers, 5 through 8 range(2,100,2) gives all even numbers less than 100 14
more "for" examples Very simple, using range() for n in range(10): print n, "hello", print " --- goodbye" An arbitrary list of values: for ctr in [ 3, 9, -7, 'abcd', 33 ] : print ctr Use a string as a list: for ltr in 'abcdefghijklmnopqrestuvwxyz' : print ltr 15
Uncertain loops Use a while loop to repeat some statements as long as a condition is true: Let the user control the loop: while answer!= 'yes' : answer = input( 'Are you happy? ' ) The loop itself modifies part of the condition: while n%2 == 0 : print n, "is even" n = n / 2 16
the while loop Required format: Remember the colon while <Boolean expression> : <statement> <statement> The body must be indented relative to the loop The while is required The body includes as many statements as needed. The <Boolean expression> generally tests a variable. The variable must have a starting value! 17
"while" loop specifics "while" loops through a block of statements like "for" and "if" "while" checks a condition before each pass through its statement block the condition is a Boolean/logical expression, like those in "if" statements Any variables in the Boolean expression must have some value before the loop occurs! The statement block must be able to change one of the variables, or this will be an infinite loop. 18
more "while" examples Repeat something randomly: coin = random.randint(0,1) while coin == 1: print '"1" means Heads' coin = random.randint(0,1) Just like a "for" loop: n = 0 while n < 10: partyertakesstep( ) n = n + 1 19
The "craps" dice game: A bigger example Players take turns throwing a pair of dice A player can win, lose, or set a point If the player sets a point, then she throws again On each following throw, the player can win, lose, or just keep going If the player wins, she gets another turn If the player loses, the next player gets the dice (Betting takes place on many aspects of the throws.) 20
the game of Craps in detail The come-out throw: Natural: 7 or 11 Craps: 2, 3, 12 or a Point ( any of 4, 5, 6, 8, 9, 10 ) If you set a point, keep throwing again until you: Make your point: match the first throw to win (and get another turn) Seven-out: a 7 loses (and ends the turn) 21
Craps program structure Make the come-out throw Use an if-elif-else structure to decide whether you win, or lose, or keep throwing Record the result with a variable ( if you keep throwing ) Use a while block to repeat throws as long as the result isn't a win or a loss Print each throw; at the end, print the result 22
An Incomplete Craps Program This program shows the main features needed: A function produces each throw of the dice prints the die values returns their sum Three-way if-elif-else on the first (or "Come-out") throw Natural, craps, or keep throwing A while loop to make repeated throws if needed test each throw for a result Missing from this program: first-throw results are wrong counting the number of throws is wrong 23
Craps throws Ways to Make a Point 1 2 3 4 5 6 This isn't needed for the program, but here's how the various throws are named in a casino: (Lots of betting possibilities here) 1 2 2- Snake Eyes 3- Loose Deuce 3- Loose Deuce 4- Hard Four 5- Fever Five 3 4- Easy Four 5- Fever Five 4 5- Fever Five 5 6- Easy Six 6 7- Natural or Seven Out 6- Easy Six 7- Natural or Seven Out 8- Easy Eight 4- Easy Four 5- Fever Five 6- Hard Six 7- Natural or Seven Out 8- Easy Eight 6- Easy Six 7- Natural or Seven Out 8- Hard Eight 9- Nina 10- Easy Ten 6- Easy Six 7- Natural or Seven Out 8- Easy Eight 9- Nina 10- Hard Ten 7- Natural or Seven Out 8- Easy Eight 9- Nina 9- Nina 10- Easy Ten 11- Yo 11- Yo 12- Boxcars 24