python hacks 4 (series)

7
Controlling the flow of your programs!  Victor Miclovich V Codes 25 th - 26 th May 09 http://code.google.com/p/lpython Hello, class!!! This, I think, is one of the coolest things you can write about in your source code. Being able to control the interaction and behavior of small pieces of code. I will briefly look at  statements and quickly remind you of what you read about. I will then integrate lists, dictionaries, looping statements, and so much more in a program that will take in scores from a “teacher” and names, populates a dictionary variable (our own copy of a database), and do fancy things: calculate a GPA, maximum score, minimum score; in cases of idealism I will assume that no student has the same mark. 1.0.1 if statement Have you ever had to make a decision in your life. I guess you have. So you might now have to recall the steps you following in making a decision. Take for example, a case of dating. You have just met the “person” of your dreams and you know this is the one, right one. But, you will on several occasions probably ask that person out probably to the movies. This will take you through numerous decision making thoughts such as, “If I don't get money by Saturday night, I am a goner. I think I should make some bucks today.” “If she [he] sees that I'm nervous, I'll ask to be excused and come up with some kind of surprise” Thoughts like those above could come up! It's natural. It is also artificially-natural to programs and software. Decisions like if the password is not write [ this will be displayed in the code: passwordChecker.py ] what does the program/software do (quit or give-another chance), if  you've lost many lives in a video game of some kind, should the video game software as you for a recharge, etc. There are many examples that show the use of the if statement. Syntax if (x > 0): print x+” is positive”

Upload: victor-miclovich

Post on 30-May-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Python Hacks 4 (series)

8/14/2019 Python Hacks 4 (series)

http://slidepdf.com/reader/full/python-hacks-4-series 1/7

Controlling the flow of your programs!  Victor Miclovich

V Codes 25th - 26th May 09http://code.google.com/p/lpython

Hello, class!!!This, I think, is one of the coolest things you can write about in your source code. Being able tocontrol the interaction and behavior of small pieces of code.

I will briefly look at  statements and quickly remind you of what you read about. I willthen integrate lists, dictionaries, looping statements, and so much more in a program that willtake in scores from a “teacher” and names, populates a dictionary variable (our own copy of adatabase), and do fancy things: calculate a GPA, maximum score, minimum score; in cases of idealism I will assume that no student has the same mark.

1.0.1 if statement

Have you ever had to make a decision in your life. I guess you have. So you might nowhave to recall the steps you following in making a decision.

Take for example, a case of dating. You have just met the “person” of your dreams and youknow this is the one, right one. But, you will on several occasions probably ask that person outprobably to the movies.

This will take you through numerous decision making thoughts such as,

“If I don't get money by Saturday night, I am a goner. I think I should make some bucks

today.”“If she [he] sees that I'm nervous, I'll ask to be excused and come up with some kind of 

surprise”

Thoughts like those above could come up! It's natural. It is also artificially-natural to programsand software. Decisions like if the password is not write [ this will be displayed in the code:passwordChecker.py ] what does the program/software do (quit or give-another chance), if 

  you've lost many lives in a video game of some kind, should the video game software as youfor a recharge, etc.

There are many examples that show the use of the if statement.

Syntax 

if (x > 0):

print x+” is positive”

Page 2: Python Hacks 4 (series)

8/14/2019 Python Hacks 4 (series)

http://slidepdf.com/reader/full/python-hacks-4-series 2/7

else if (x < 0):

print x+” is negative”

else:

print x+” is zero”

The if statement is usually accompanied by the else clause (the decision that occurs if the

if condition is not true/fails). The else is a clause because it can't work alone...

1.0.2 The while statement

Imagine some situation where I want to do something over and over again. For instance

while my ice cream cap still has some sweet chocolate in it, continue eating, otherwise (case

 when there's nothing) stop, and wash up!

So we can mimic (copy) a real life situation... and use while statements for the purpose of performing something similar many times.

Syntax/Operation of the while  statement

loopCounter = 0 #value e.g. 0

while (<condition>):

# code that does something

# an iterator...

# code that does something when the conditions are false

Example:

# this prints out numbers from 0 to 10

count = 0

while count <= 10: # you may  put brackets around condition

print count

count = count + 1 # also “count += 1” can work here

Page 3: Python Hacks 4 (series)

8/14/2019 Python Hacks 4 (series)

http://slidepdf.com/reader/full/python-hacks-4-series 3/7

NOTE

We shall get into the details of python's syntax when programming C. There we shall study  why something is the way it is.

In the first round I teach just some basic (but advanced) mathematical algorithms, coding in

GUIs, principle and techniques of writing programs in any language (imperative and object-oriented).

So issues like how the Python stores a variable, what a garbage collector is, dynamic typing,strong typing, etc. will be handled only if you are still strong and up for the challenge.

  Also, don't be surprised by the short length of lecture notes (between 3 to 7 pages long), it'snot me studying the language or art; I am just a way for you to understand stuff. Withexamples, I am sure you will be able to pick up certain concepts; and ask if you get lost.

1.0.3 for statements

When you have a large list, say of names or dictionary key/value pairs, or you want tomine some data from a huge dictionary... you can use the while statement, but it is a turd

easier to use a for statement which we call a list iterator (repeats a crawl thru' the list!).

data = ['victor', 'arnold', 'derick', 'peter']

# using a while loop

count = 0

 while count < len(data):

print data[count]

count += 1

# using a for statements

for someName in data:

print someName

Explanation of the while loop:

It can be read a lot like English;

“While count is still less than the number of elements, print out the element/item foundat an index equal to count (in this case 0), increase the value of count by one, then test thenew value of count and ask yourself whether it is still less than the number of elements of the

Page 4: Python Hacks 4 (series)

8/14/2019 Python Hacks 4 (series)

http://slidepdf.com/reader/full/python-hacks-4-series 4/7

list; if it is still the case, do like we did before; increase count, go out of loop... back to thetesting condition and keep doing that until count is no longer less than len(data)... rememberlen() is a function that returns the length of the list or number of items in the list.

The reason count starts at zero is because counting in many programming languages starts at0; that's why if we are to do something like data[len(data)] we get some error: list index outof range. So the allowable index in our list is 0, 1, 2, 3. Get it?

So when a 4 is reached loop is broken, and we can get of the loop!”

What a mouthful of words, I just hope that made sense... now you know why the for iterator

is better... it took only two lines to implement and do the same thing, while the while

statement took more lines!

More info on the for statement

The for statement will go through a sequence, picking element by element.

>>> for x in “hello”:

print x

The x before the keyword in; in picks an element and assigns it to x... x is then passed to theprint function/statement.

  Also, within the for statement's body you can nest other computations... fancy things thatshould you do with your data. For some applications you will have to refer to the code I'll leaveon the Google code download page site.

 A slight change in way of repeating tasks

I have added to the site page an extended amount of code... that I've tested. I deigned the codeusing Python 2.6.2 but I've tested in Python versions 2.4 and 2.5.1. Python is backward

compatible. This code won't work on Python 3.0 and higher, unless you know how to use thePython 2 to 3 libraries... but this will involve a lot C programming and using many UNIX tools... which many of you don't have yet.

Code that I've added

● StudentScore.py 

● Mysteries.py 

● iteration.py 

Page 5: Python Hacks 4 (series)

8/14/2019 Python Hacks 4 (series)

http://slidepdf.com/reader/full/python-hacks-4-series 5/7

Study this code... try to under... then ask your questions...

I also would love it if you could all get UNIX machines preferably Linux with a kernel of higherthan 2.6; there are several good distros: Suse, Red hat, Ubuntu, etc.

In the next lecture... I will also introduce the use of Integrated development environments... if  you can, read about the Eclipse IDE on http://eclipse.org

 Breaking out of loops

There are times when you want to get of your loop (while or for) prematurely or aftersomething has been done...

food = ['chocolate', 'macaroni']

# let us give someone a chance to guess the food... let's say we give him 5 changes

for chances in range(5):

ask = raw_input('What food do you love? If you get the answer right, you

eat\n')

  if ask in food: # this check whether something is IN the LIST... you can even

see how we use the in operator

  # if this condition is true for either case

  print "\nWait... you got it right! Now you may have your food\n"

  break

  continue

  You see all that above... :)

Think of situations where you repeat something... but when a certain condition is appropriate,  well, you just get out of it. Watch the indentation... Python is strict as far as indentation isconcerned!

The same code can be implemented using the while statement... shown below.

food = ['chocolate', 'macaroni']

# let us give someone a chance to guess the food... let's say we give him 5 changes

chances = 0

while chances < 5:

Page 6: Python Hacks 4 (series)

8/14/2019 Python Hacks 4 (series)

http://slidepdf.com/reader/full/python-hacks-4-series 6/7

ask = raw_input('What food do you love? If you get the answer right, you

eat\n')

  if ask in food: # this check whether something is IN the LIST... you can even

see how we use the in operator

  # if this condition is true for either case

  print "\nWait... you got it right! Now you may have your food\n"

  break

  continue

chances += 1

List comprehension

List comprehension is an interesting feature in python. You use it to generate lists...

The book covers it quite well... am just gonna repeat a few things...

>>> x = [x+x for x in range(3) if x%2 == 0]

>>> print x

>>> [0,4]

The above code will first do range(3)... that is, it will produce the list from the range(3)

function... if will then calculate the remainder values of each x in the list.range(3)

[0, 1, 2] is produced

then...

[0%2, 1%2, 2%2]

then...

  where x%2 produces 0, we add the original x's together

so...

[0, 1, 0]...

The x's that produce zero are 0 and 2. We then do what we set out to do in the first place...

Page 7: Python Hacks 4 (series)

8/14/2019 Python Hacks 4 (series)

http://slidepdf.com/reader/full/python-hacks-4-series 7/7

x + x.

[0+0, 2+2] ---> [0, 4]

Trick: any number that satisfies x%2 == 0, is an even number.. you can test that for yourself 

The way of doing list comprehension....

# start your list '[', write the computation you want done, iterate a number times, you may include a testing conditions...

[ computation, for <something> <condition>]

More examples

[x/2, for x in range(10)] # no conditions here[x/2, for x in range(5) if x % 3 == 0] # here the x is divisible by 3... generate list of x/2

There's a lot more in the book about control

structures; work through as many examples as

possible.

In this lecture, I leave you 3 sets of code to look at

and play with. I also leave a formal assignment

marking the end of simple stuff...

Next lecture...  Abstractions