Weekly Topics
•
In this weeks lecture and lab we will look at the following areas:
•
Why branching is so important to computer programs.
•
What conditional operators exist and how can we use them.
•
Using arrays / lists to store sets of data.
•
Different types of loops and how to use them to process array / list data.
•
There’s a lot to take in, so please tune in!
•
If there’s something you don’t understand –ask!
3
Branching
•
Branching is a term used to describe how we can do one thing out of a range of possible things based on one or more conditions.
•
You already know a lot about branching -you do it everyday in your lives!
•
Let’s take some plain-English examples of branching behaviour you might do on any given day:
•
IF your cup of coffee is cold you might MICROWAVE it.
•
IF your phone rings you might either ANSWER it or IGNORE it.
•
IF your car is LOW ON FUEL you might FILL UP AT A PETROL STATION or RISK RUNNING OUT OF GAS!
•
IF it’s raining AND you have an umbrella AND you’re outside, you might PUT THE UMBRELLA UP.
Simples!
4
Conditional Operators
•
When we branch in a programming language, we use conditional operators to help us specify the conditions under which we want to do one thing, or a different thing (i.e. the behaviour of our program changes depending on what’s going on!)
•
To do this we can use any of the conditional operators from the table below*:
- = there are one or two others like “===” (strict equality), but we’re not too fussed about them right now.
Conditional Operator
Meaning
Example
Evaluates to…
< Less than if (3 < 4): DoSomething() 3 < 4 is True <= Less than or equalto if (3<= 3): DoSomething() 3<= 3 is True >
More than
if (5 > 4):DoSomething()
5 > 4 is True
=
More than or equal to
if (5 >= 4): DoSomething()
4 >= 4 is True
Equal to
if (5 == 4): DoSomething()
5 == 4 is False
!=
Not equal to
if (5 != 4):DoSomething()
5 != 4 is True
5
Conditional Operator Testing
•
If we open the Python command line and entered each of the following lines in turn, what would it come out as? Each answer is either Trueor False-and the >>> is just the command prompt (ignore it):
3 < 4 4 < 3 4 <= 3 3 <= 3 4 == 4 4 == 5 5 > 4
5 >= 4
4 >= 4
3 >= 4
3 != 4
4 != 4
6
Conditional Operator Testing
•
If we open the Python command line and entered each of the following lines in turn, what would it come out as? Each answer is either Trueor False-and the >>>is just the command prompt (ignore it):
3 < 4True! 4 < 3False! 4 <= 3False! 3 <= 3True! 4 == 4True! 4 == 5False! 5 > 4True!
5 >= 4True!
4 >= 4True!
3 >= 4False!
3 != 4True!
4 != 4False!
7
“if” Statements
•
Whenever we want to perform one operation or another, different operation depending on circumstances, we can use an ifstatement.
•
if statements in Python are arranged like this:
if (some-condition-is-true):
do-something
•
What’s really important here is that we put the colon (
after the closing braces of our condition, and that we tab-indentthe code that we want to run if the condition is true!
•
For example:
if (3 < 4):
print(“three is less than four!”)
print(“three is still less than four!”)
Note: We can perform this ‘if-test’ without using brackets if we want, i.e. if 3 < 4: instead of if (3 < 4):
8
“if” Statements (Cont’d)
•
Python uses indentation to determine “blocks” of code, so in C/C++/Java etc. you might specify a block of code like this:
// Double-forward slashes mean a comment in C/C++/Java
// It’s the same as using the hash symbol (#) in Python
•
In Python we’d do the same thing like this:
In main code here…
In new code block here because of indentation!
Still in the new code block as still indented!
Back to the “main” now that we’re not indented anymore!
•
We’ll get to “code blocks” and why they’re important when we cover variable scopenext class!
9
Using “if” with “else”
•
Commonly we might want to do one thing under certain conditions, and something else otherwise -and the way that we do this is to use if statements in combination with else statements, like this:
currentDay= “Tuesday”
weekendStartDay= “Saturday”
if (currentDay== weekendStartDay):
print(“Yay!”)
print(“What fun stuff shall we do?”)
else:
print(“Boooo!”)
print(“Work workwork… Bah!”)
print(“What’s for lunch?”)
Will the final print statement everrun, sometimes run or always run?
Which one of these two blocks will run?
10
If / Else with Multiple Options
•
When using if / else statements we get one of two behaviours:
•
Either the if statement evaluates to Trueand we run the “if” block of code,
•
Or it doesn’t, and we run the “else” block of code.
•
But what if we wanted four options? Or forty options? We could do it like this:
cost = 0
num= int( input(“Please enter the number 1, 2, 3 or 4: “) )
if (num== 1):
cost = 1000
else:
if (num== 2):
cost = 2000
else:
if (num== 3):
cost = 3000
else:
if (num== 4):
cost = 4000;
else:
…………four hundred options, anyone?
Can you see where this is going?
To indent HELL! =(
11
The elifStatement
•
Fortunately for us, we don’t have to indent things out to absurdity -we can use the elifstatement, instead!
•
For example, the previous code can now be written like this:
cost = 0
num= int( input(“Please enter the number 1, 2, 3 or 4: “) )
if (num== 1):
cost = 1000
elif(num== 2):
cost = 2000
elif(num== 3):
cost = 3000
elif(num== 4):
cost = 4000
print( “Final cost is: $0”.format(cost) )
No ridiculous amount of indentation required!
12
The switchstatement in Python
•
If you’ve never heard of a switchstatement -please ignore this slide!
•
If you really, really want to use something like a switch statement, you can use:
if (something == 1):
doThing1()
elif(something == 2):
doThing2()
else:
doDefaultThing()
•
You can have as many elifstatements as you require, and if neither the initial if or any of the elifstatement conditions are True, then the final else block runs.
There is noswitch statement in Python!
13
Short-hand Notation to Manipulate Variables
•
A very common operation is to add some value to the existing value of a variable. We’ve already seen that we can do so like this:
myNumber= 5
myNumber= myNumber+ 10# myNumberis now 15
myNumber= myNumber+4# myNumberis now 19
•
Because this is such a common operation, there’s a “short-hand” way of doing this without having to type the variable name over and over again:
myNumber= 5
myNumber+= 10# myNumberis now 15
myNumber+= 4# myNumberis now 19
•
Both of these pieces of code do the exact same thing-the second one is just a little bit quicker to type! You can use whichever one your prefer.
14
Short-hand Notation to Manipulate Variables (Cont’d)
•
We can also use the same type of “short-hand” to perform subtraction, multiplication or division, like this:
myNumber= 5
myNumber= myNumber+ 10# myNumberis now 15
myNumber= myNumber* 2# myNumberis now 30
myNumber= myNumber-6# myNumberis now 24
myNumber= myNumber/ 2# myNumberis now 12
•
Short-hand equivalent:
myNumber= 5
myNumber+= 10# myNumberis now 15
myNumber= 2# myNumberis now 30 myNumber-= 6# myNumberis now 24 myNumber/= 2# myNumberis now 12 15 Using OR in Python • All languages have some manner of ORoperator, and in Python we use the word ‘or’ for this operation. • We generally use the ORoperator, when we want something to happen if one or more conditions is met. • A pseudo-code example: If I am thirstyORI am too hot: Drink something cold. • Another example might be: If it is rainingORit is cold: Wear a jacket. “Pseudo-code” is just a plain language (not computer code) description of what the code does! 16 Using OR in Python (Cont’d) • Let’s say that we have two booleanvariables (True/False values) called cond1 and cond2(i.e. conditions 1 and 2). • If we create a “truth-table” using these two conditions, we get this: • We can see from the above table that for an ORoperation to be true, either condition A must be true ORcondition B must be true. • And if both of them are true, then great! But we only needed one to be true to get a result of true! Valueof cond1 Valueof cond2 Resultof OR operation True True True True False True False True True False False False 17 Using OR in Python (Cont’d) • Now let’s write some code to make sure we can see how this works in Python. Take another look at the pseudo-code below: If I am thirstyORI am too hot: Drink something cold. • If we were thirsty, but not too hot, we might write this in Python as follows: thirsty = True tooHot= False if (thirsty == True) or (tooHot== True): print(“Hmm, I feel like having a cold drink”) else: print(“I don’t feel like a cold drink.”) • Which of the two print statements will get executed in the code above? 18 Using OR in Python (Cont’d) • When we’re comparing booleanvalues in an if-statement we can use a little bit of shorthand, if we’d like to, in order to save ourselves some typing. • For example, instead of writing the code if (todayIsSunday== True): [DO-SOMETHING] • We could instead write: if (todayIsSunday): [DO-SOMETHING] • We can do the same to check if something is Falseby using the NOT operator, which is an exclamation mark ( ! ). • So if (!todayIsSunday) and if (todayIsSunday== False) also the exact same thing. Use whichever you’d prefer! These mean the exact same thing! 19 Using OR in Python (Cont’d) • Now let’s get some feedback from the user, and act on it. But first, just to make things clear, let’s write some pseudo-code which describes what we want to do: Ask the user if they understand the ‘or’ operator If the user answers “Y” OR”y” then: Display “Yay! Good stuff!” Otherwise: Display “Keep trying -it’ll make sense soon!” • We could then write the following Python code to perform the above: answer = input(“Getting the OR operator? (y/n): “) if (answer == “Y”) or (answer == “y”): print(“Yay! Good stuff!”) else: print(“Keep trying -it’ll make sense soon!”) 20 Using OR in Python (Cont’d) • So far, we’ve been performing one of two actions depending on whether at least onecondition has been true. Instead of directly jumping into some code, we can also do things like set other variables. For example: wearJacket= False raining = input(“Is it raining? (y/n) “) cold = input(“Is it cold outside? (y/n) “) if (raining == “y”) or (cold == “y”): wearJacket= True if (wearJacket== True): print(“Brrr! Definitely jacket weather!”); else: print(“It’s quite nice out today -no jacket req’d!”) 21 Using OR in Python (Cont’d) • Sometimes we want to get input from a user, but we’re not sure the exact format that the input will be provided in, for example: name = input(“Please enter your name: “) if (name == “Bruce Wayne”): print(“It’s the Dark Knight himself!”) else: print( “Hi, !”.format(name) ) • If I enter precisely”Bruce Wayne” into the above code then the first block will run (“It’s the Dark Knight himself!”), but… • …if I enter “brucewayne”, or “BRUCE WAYNE” or “BrUcEWaYnE” or anything which doesn’t exactly matchthe comparison string then it’s going to run the second block (“Hi, [whatever-was-entered]!”). 22 Using OR in Python (Cont’d) • We could fix this by modifying our code to something like this: name = input(“Please enter your name: “) if (name == “Bruce Wayne”) or (name == “brucewayne”) or (name == “BRUCE WAYNE”) print(“It’s the Dark Knight himself!”) else: print( “Hi, !”.format(name) ) • But that’s still only three possibilities.. and there’s a large number of possible combinations we could get: bRUCEWAYNE, BrUCEWAYNE etc. etc. etc. • So we should probably find a better way of doing this instead of trying to cater to all the possible UPPERCASE and lowercase combinations… 23 Converting Cases • We can make comparing input easier on ourselves by converting the input into either uppercase or lowercase. Let’s try it out: name = “Bruce Wayne” name = name.upper() print(name) • Which prints out: BRUCE WAYNE • While to convert to lowercase we could use: name = “BrUcEWaYnE” name = name.lower() print(name) • Which prints out: brucewayne 24 Converting Cases (Cont’d) • Just for completeness, we could have written the previous code to convert all input to uppercase (in this example), as follows: name = “Bruce Wayne” print( name.upper() ) • This will print out “BRUCE WAYNE” like before, only now -what if we decide we want to print out the name again? For example, we could change our code to be: name = “Bruce Wayne” print( name.upper() ) print(name) • By not changing the data stored in the variable, the second time we print the name it’s still going to be in its original (non-fully-uppercase) format! • If we want to change the variable data itself, we’d have to use code like this: name = name.upper() Why the extra spaces surrounding name.upper()? Just so it’s easier for us as human beings to read! 25 Converting Cases (Cont’d) • Another way of doing the same thing would be to change the users input to either upper or lower case as soon as we get it, for example: name = input(“Please enter your name: “).upper() if (name == “BRUCE WAYNE”): print(“It’s the Dark Knight himself!”) else: print( “Hi, !”.format(name) ) • We could just as easily force the input to lowercase and then compare against lowercase -it doesn’t matter either way and will work identically. Input forced into uppercase -then compared against uppercase! 26 Capitalising The First Letter of a String • If you want to convert the first letter of a string to a capital letter, then you can do so using the capitalize()function, like this: sentence = “this is a sentence.” print(sentence) sentence = sentence.capitalize() print(sentence) • Which will output: this is a sentence. This is a sentence. 27 Using AND in Python • Now we know how the OR operator works, let’s take a look at the AND operator, which is designated by an ampersandsymbol: & • We generally use the ANDoperator, when we want something to happen if more than one condition must be met. • A pseudo-code example of this could be: If my mobile phone has chargeANDmy mobile phone has signal: I can receive a phone call. • Another example might be: If I have a valid passportANDI have a plane ticket to Paris: I can fly to Paris. 28 Using AND in Python (Cont’d) • To take this a bit further, let’s say that we have two booleanvariables called cond1 and cond2(i.e. conditions 1 and 2). • If we create a truth-table for the AND operatorusing these two booleanvariables, we get this: • We can see from the above table that for a ANDoperation to be true, both condition A ANDcondition B must be true. Valueof cond1 Valueof cond2 Resultof AND operation True True True True False False False True False False False False 29 Using AND in Python (Cont’d) • Let’s give this a go -take a look at the following pseudo-code: If I my mobile phone has chargeANDhas signal: I can receive a phone call. Otherwise: I can’t receive a phone call. • We might write this in Python as follows: mobileHasCharge= True mobileHasSignal= False if (mobileHasCharge== True) and (mobileHasSignal== True): print(“Call me!”) else: print(“The number you have dialled cannot be reached.”) • Which of the two print statements will get executed in the code above? 30 Using AND in Python (Cont’d) • Now let’s get some feedback from the user again, and then act on it. First, some pseudo-code: Ask the user for their height in cm If the entered height is more than or equal to 163cm AND less than or equal to 193cm: Display “You can be a fighter pilot!” Otherwise: Display “You’re too big or small to fit in a jet!” • We could then write the following Python code to perform the above: height = int( input(“Please enter your height in cm: “) ) if (height >= 163) and (height <= 193): print(“You can be a fighter pilot!”) else: print(“You’re too big or too small to fit in a jet!”) Quiz: What would happen if we’d used an OR operator instead of an AND operator in the above code? 31 Using a Mixture of Data Types with Conditionals • So far we’ve been using the same types of data for our AND or ORstatements, but we don’t have to -we can mix up the data types if we like: name = “Dave” sunny = True cash = 350 if (name == “Dave”) and (sunny == True) and (cash > 300): print(“Dave is winning! =D”) else: print(“It’s just another day…”) • In the above code, if any single oneof the three conditions that we’re testing for evaluates to False, then the program will print “It’s just another day…” Stringdata of type str Booleandata of type bool Integerdata of type int 32 Creating and Working With Ranges of Numbers • Python allows us to create a set of integers between zero and an end value by using the range statement. • We can then print out that range of numbers using the printstatement, for example: print( range(5) ) • When we run the above command, it will display all the whole numbers from zero up until it’s at “one step less than”the end value we specified, going up by 1 per time. • So if we run the above command, the output we’ll see is: [0, 1, 2, 3, 4] End value 33 Creating and Working With Ranges of Numbers (Cont’d) • We can also use a two parameter version of the range statement where we specify a starting value and an ending value. print( list( range(4, 10) ) ) • Again, when we run the above command, it will display all the whole numbers from the first number we specified, up until it’s at “one step less than”the end value we specified. • So if we run the above command, the output we’ll see is: [4, 5, 6, 7, 8, 9] First parameter: startvalue Second parameter: endvalue 34 Creating and Working With Ranges of Numbers (Cont’d) • When we just saw the range function, we provided it: • A range-start value of 4, and • A range-end value of 10. • Because we only provided two parameters (i.e. 4and 10) to the range statement, the numbers in our range increased by 1each time as the default behaviour. • But what if we wanted the numbers in our range to increase by 2’s? Or 5’s? Or 7’s? In this case, we can specify a thirdparameter, which controls how much to increase the value of the numbers in our set by! • This might sound complicated -but it’s really very simple! Try running this: print ( list( range(0, 10, 2) ) ) • If we run the above command, we’ll generate a set of numbers starting at 0and going up by 2each time until the value is one step less thanour end value of 10: [0, 2, 4, 6, 8] 35 Creating and Working With Ranges of Numbers (Cont’d) • The technical term for this “one step less than” behaviour is that the range statement returns us a set of numbers in what’s called a: half-inclusive range • In maths, you might see this specified as: [Start-value, End-value) • The square bracket [means that the number is INCLUDED in the range. • The parenthesis) means that the number is NOT INCLUDED in the range. • Let’s try some examples… 36 Creating and Working With Ranges of Numbers (Cont’d) • What if we want to have our list in descending order? (i.e. start with a high number, and then decrease the value each time until we reach our end value). • It’s easy! To count backwards from 10 to 1, we just specify: • Our start-value as 10, • Our end-valueas 0, and • Our step-changeas -1 • Like this: print ( list( range(10, 0, -1) ) ) • Which will display the following output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 37 But Why Doesn’t It Go To 0? • The rangefunction uses what’s called a half-closed interval. • An interval (in maths) is defined by using either/both: • A square-bracketsuch as “[” to indicate that a number is included, and • A parenthesissuch as “)” to indicate that a number is not included. • So, for example: • [5,10) means the range of numbers 5, 6, 7, 8, 9 • [5,10]means the range of numbers 5, 6, 7, 8, 9, 10 • (5, 10]means the range of numbers 6, 7, 8, 9, 10,and • (5, 10)means the range of numbers 6, 7, 8, 9 The range function in Python uses this one! 38 A Few Simple Ranges To Make Sure We’re All On Point! • What are the following ranges? • [2, 5] • (3, 6) • [2, 5) • (3, 6] • (7, 10] • [8, 9] • (8, 9) Quiz: Which one of these ranges corresponds to how the Python range function works? 39 Range Answers • What are the following ranges? • [2, 5]2, 3, 4, 5 • (3, 6)4, 5 • [2, 5)2, 3, 4 • (3, 6]4, 5, 6 • (7, 10]8, 9, 10 • [8, 9]8, 9 • (8, 9)[ ] –empty set! Quiz: Which one of these ranges corresponds to how the Python range function works? 40 Can We Increment or Decrement Our Range By Float Values? • You mean, for example, can we go from 0.0 to 10.0 in steps of 0.5 like this?: print( list( range(0.0, 10.0, 0.5) ) ) • Unfortunately no-the range function only works with integer data, sorry! • If you try it, you’ll get this: print( range(0.0, 10.0, 0.5) ) Traceback(most recent call last): File “”, line 1, in print( range(0.0, 10.0, 0.5) ) TypeError: ‘float’ object cannot be interpreted as an integer • If we really need a range of floating point values, we can either do a little bit of math to generate them from an integer range, or use numpy.arrange()
41
Variables and Lists
•
As we’ve seen, a variable is a named piece of data, and it usually only contains a single piece of information.
•
For example, these are all variables:
total = 123
name = “Bob”
price = 49.95
•
A list, on the other hand, is still a named piece of data -but this time it usually contains more thana singlepiece of information, for example:
beatles= [“John”, “Paul”, “George”, “Ringo”]
•
Or it could contain a set of the last seven days temperatures:
lastSevenDayTemps= [23, 25, 28, 34, 23, 23, 17]
42
Variables and Lists (Cont’d)
•
Let’s just take a quick look at our Beatles example again:
beatles= [“John”, “Paul”, “George”, “Ringo”]
•
If you’ve programmed before, you might recognise this looks like an array-however, while arrays are typically fixed in size Python lists are dynamic in size, and they can also store different types of data (unlike typical arrays).
•
Every item in the list has a numbered location called its index that starts at 0 and goes up to one-less-than-the-number-of-items.
•
So in the above example:
•
beatles[0]is “John”,
•
beatles[1]is “Paul”,
•
beatles[2]is “George”, and
•
beatles[3]is “Ringo”.
Quiz: What’s the value of beatles[4]?
43
Storing a Set of Values in a List
•
So far, we’ve seen that we can print out a range of numbers. But if we want to, we can also storeour range of numbers in a variable, like this:
myList= range(0,15,3) #Start at 0, end before 15, step by 3
print(myList)
•
However, when we print this our we get:
range(0, 15, 3)
•
That might not be quite what we want… To make the myListvariable actuallycontain the generated list we need to cast (i.e. convert) it to a list, like this:
myList= list( range(0,15,3) )
print(myList) # Prints [0, 3, 6, 9, 12]
•
Once we have a listof data elements, we can access each individual element by specifying the elements index using square-brackets notationlike this:
print( myList[3] ) # Prints 9
Quiz: Do you think printing myList[3] will work without converting myListto a list?
44
Storing Different Types of Data in Lists
•
In most programming languages if you create an array / list, then all the data in it has to be of the same type (i.e. integers, floats, strings etc).
•
In Python, because it’s a dynamically typed language this is not the case and we’re free to mix and match data types.
•
For example, the following is perfectly legal in Python:
myList= [ ‘Bananas’, 123, True, float(3.14159) ]
•
Printing it out gives you exactly what you’d expect:
[ ‘Bananas’, 123, True, 3.14159 ]
45
Adding and Removing Elements to/from Lists
•
Lists are dynamic structures, which means that not only can we modify the data in a list, we can add things to them and remove things from them as we please. For example:
shoppingList= [‘Milk’, ‘Bread’]
shoppingList.append(‘Sugar’)
print(shoppingList) # Prints [‘Milk’, ‘Bread’, ‘Sugar’]
shoppingList.remove(‘Milk’)
print(shoppingList) # Prints [‘Bread’, ‘Sugar’]
shoppingList.insert(1, ‘Bananas’) # Params: index, data
print(shoppingList)# Prints [‘Bread’, ‘Bananas’, ‘Sugar’]
del shoppingList[2]
print(shoppingList) # Prints [‘Bread’, ‘Bananas’]
Note: When we call remove and give a specific item, only the first element that matches is removed, not all of the matching elements!
46
Multidimensional Lists
•
We can embed lists inside other lists to create multidimensional lists if we want to, for example:
first = [1, 2, 3]
second = [4, 5, 6]
third = [7, 8, 9]
myList= [first, second, third]
•
To access the elements of a multidimensional array we use multiple sets of square brackets:
print(myList) # prints [ [1,2,3], [4,5,6], [7,8,9] ]
print(myList[0]) # prints [1,2,3]
print(myList[1]) # prints [4,5,6]
print(myList[2]) # prints [7,8,9]
print(myList[0][0]) # prints 1
print(myList[1][1]) # prints 5
Note: We can embed lists as deeply as we’d like, so we can have a list which contains lists which contains lists which contains lists and so on.
This list contains lists!
47
Tuples
•
Tuples (pronounced too-ple) are similar to lists, but once you’ve put some data into a tuple then that data cannot be changed. The technical term for this is that tuples are immutable.
•
So for example, I could create a tuple of two elements like this:
myTuple= (‘Star Wars’, 1978)
•
To access the elements we could use code such as:
print(‘The film’, myTuple[0], ‘was originally released in’, myTuple[1])
•
If we try to modify a tuple’s value we get an access violation:
myTuple[1] = 2078
Traceback(most recent call last):
File “”, line 1, in
myTuple[1] = 2078
TypeError: ‘tuple’ object does not support item assignment
48
Tuples (Cont’d)
•
This immutable property of tuples extends a little further than not being able to modify the data in a tuple, for example:
•
You can’t addelements to a tuple. Tuples have no appendor extendmethods.
•
You can’t removeelements from a tuple. Tuples have no removeor popmethods.
•
We canfind elements in a tuple, since this doesn’t change the tuple, and we can also use the inoperator to check if an element exists in the tuple (because again, the tuple is not modified).
•
So why would we want tuples at all? The reason is that it allows us to create a kind of read-only data structure, that once set cannot be modified (not on purpose, not by accident, not maliciously by a third-party).
49
Introduction to Loops
•
A loopis a piece of code that can run over and over again, without you having to enter the code over and over again!
•
For example, probably the most famous (or infamous!) loop you might have seen in the BASIC programming language might have been something like:
10 PRINT “Are we there yet?”
20 GOTO 10
•
In BASIC, this will keep printing “Are we there yet?” over and over and over -forever! Or until we pull the plug or kill the process!
•
The above is an example of what’s called an infinite loop, because it never ends -which means your program will never, everleave the loop.
•
This is typically considered a bad thing!
50
Introduction to Loops (Cont’d)
•
The Python equivalent of the previous nagging loop can be written as:
while True:
print(“Are we there yet?”)
•
We’ll take a look at the different ways which we can use to repeat sections of code in the following slides….
51
Loop Types
•
When we use loops in modern programming languages, there are only three different types of loops that we can use:
•
We can use a forloop, or
•
We can use a whileloop, or
•
We can use a do-whileloop equivalent (there is no exact do-whileloop in Python -but we can create something that works the same way).
•
Those are our only three options(we don’t use GOTO statements anymore -it’s not considered good practice in modern programming)
•
The type of loop that we decide to use (for, whileor do-while) depends on two important factors that we have to ask ourselves:
1.
Do we know exactly how many timesthe loop should execute (yes/no), and
2.
Do we always want the loop to execute at least once? (yes/no)
Note: We’ll come back to these two questions shortly -first, let’s take a look at each type of loop in action!
52
“For” Loops in Python
•
The syntax for writing a forloop in Python is:
for [VARIABLE-NAME] in [SOME-KIND-OF-SET]:
[DO-SOMETHING]
•
Let’s try it out by using a loop to print out the values from 1 to 10:
for loop in range(1, 11):
print(loop)
•
This will print out:
1
2
…
9
10
When to use “for” loops:
We use “for” loops when we know exactly how many times we want the loop to execute before it even begins.
53
“For” Loops in Python (Cont’d)
•
Now let’s try printing the “three times table” from 1 times 3 up to 10 times 3:
for loop in range(3, 33, 3): #start: 3, end:33, step: 3
print(loop)
•
This will print out:
3
6
9
…
24
27
30
We could also have used the following if we wanted -it would produce the exact same outcome:
for loop in range(1, 11):
print(loop * 3)
We could have used any of 31, 32or 33as the endvalue here, because any of them are “one step less” than another multiple of 3.
54
“For” Loops in Python (Cont’d)
•
Our last example wasn’t very informative -it just printed out the answers! If we wanted to see what’s going on and provide a bit more information, then we could re-write the code to be something like this:
for loop in range(1, 11):
answer = loop * 3
print( “0 times 3 is 1”.format(loop, answer) )
•
Which will print out:
1 times 3 is 3
2 times 3 is 6
…
9 times 3 is 27
10 times 3 is 30
Quiz: Do we have to store the ‘answer’ in a variable?
Remember we talked about variable substitution? That’s what’s going on above!
55
“For” Loops in Python (Cont’d)
•
The set of data that we “loop through” (the correct term for this is: iterate) doesn’t have to be just numbers though -we can iterate through any kind of set!
•
Let’s write a short loop that prints out all the names of the Beatles band members:
beatles= [“John”, “Paul”, “George”, “Ringo”]
for loop in beatles:
print( “0 was in the Beatles!”.format(loop) )
•
This will print out:
John was in the Beatles!
Paul was in the Beatles!
George was in the Beatles!
Ringo was in the Beatles!
56
“While” Loops in Python
•
A while loop continues to run whilea certain condition is true, for example:
counter = 1
while (counter <= 5): print(“value of counter is: “.format(counter) ) counter += 1 • Which will produce the following output: value of counter is 1 value of counter is 2 value of counter is 3 value of counter is 4 value of counter is 5 Quiz: What would happen if we forgot to put the counter += 1 line inside our while loop? When to use “while” loops: We use “while” loops when we want to continue looping while a condition is true, and we might not know how many times it’ll run. If the condition is never true, then the loop may never run at all! 57 “While” Loops in Python (Cont’d) • Another example of a while loop might be to keep looping until the user provides some input which causes us to terminate the loop, for example: arrived = False while (arrived == False): reply = input(“Are we there yet? (y/n)”) if (reply == “y”): arrived = True print(“Finally! Phew!”) • This loop will only end when we finally provide “y” as our reply, which sets our arrived variable to True! • As the loop is created to run only”while (arrived == false)” –when this is no longer the case, the loop no longer runs and we print out our “Finally! Phew!” message. Note: The specific value used to stop a while loop from executing is called a sentinel. 58 “While” Loops in Python (Cont’d) • What will happen when we run the code below? arrived = True while (arrived == False): reply = input(“Are we there yet? (y/n)”) if (reply == “y”): arrived = True print(“Finally! Phew!”) • This time, the loop will never execute because the initial conditionof arrived being False is never met! • So in this case, we’d skip the loop entirely, and go straight to the “Finally!” message. Initial value changed from False to True 59 “Do-While” Loops in Python • Sometimes, we want a loop to always execute at least once–and in most languages, we’d use what’s called a do-whileloop for this –but in Python, there is no such thing, so we have to make our own! • Luckily for us, it’s actually very easy to do: counter = 1 while True: if (counter <= 5): print( “Value of counter is: 0”.format(counter) ) counter += 1 else: break • In the above loop, when counter is greater than 5 the else condition runs, which calls the break statement -and the break statement breaks us out of the loop so we don’t get stuck in an infinite loop! 60 “Do-While” Loops in Python • The same do-while loop: counter = 1 while True: if (counter <= 5): print( “Value of counter is: 0”.format(counter) ) counter += 1 else: break When to use “do-while” loops: We use “do-while” loops when we want to continue looping while a condition is true, and we might not know how many times it’ll run -BUT -we always want the loop ‘body’ to execute at least once. 61 Automatically Generating Indices When Looping • If we have a list of items, then sometimes we may want to know the index of the item in the list, which we could do like this: index = 0 shopping_list= [‘Milk’, ‘Bread’, ‘Sugar’] for item in shopping_list: print(‘ is at index ‘.format(item, index)) index += 1 • However, there’s an easier way to do this using the enumerate keyword: shopping_list= [‘Milk’, ‘Bread’, ‘Sugar’] for index, item in enumerate(shopping_list): print(‘ is at index ‘.format(item, index)) • Pretty straight forward! 62 Wrap up • We’ve covered a lot of ground this class, such as: • Using conditional operators ( <, <=, ==, >, >=, != ).
•
Using if, elifand else statements to branch to different sections of code.
•
Using shorthand operators save us typing ( +=, -=, *=, /=).
•
Using the logical operators AND as well as OR.
•
Generating lists of numbers using the range statement.
•
Looping over sections of code using for-loops, while-loops and (what is essentially) do-while loops!
•
Please make sure you understand all of this as it is fundamental to writing computer programs! Ask questions if unsure!
The post Week 3 -Conditionals, Lists and Loops appeared first on My Assignment Online.