- Hello! Welcome to the Path to Programming; the audio supplementary materials for introduction to computer science! - I am a former student that took this introductory course and today I want to talk to you about Sequences and Loops! - Last week talked about conditionals and how our computer can make decisions for us based on a condition we gave to our computer. - This week we will talk about how your computer would behave if you wanted your computer to keep working until you gave it a condition to stop working. - A basic example we can consider is counting the number of vowels in a word. We already know how to write our own function, from the previous weeks, to determine if a letter is a vowel or not. - If we could apply this function to each letter in a word and count the results, then we could count vowels. But first, let's talk about sequences. - Strings, lists, and ranges are all sequences and we need to learn about the properties of sequences such as indexing in order to be able to understand how to use loops on sequences. - We can use a lot of built in functions on sequences to get information about them. - So far we talked about strings, but we haven’t really touched on what lists and ranges are. We will talk more about both of them in this episode. - You will also be learning more about lists in the future as their own data type. - But let's start with common properties of all sequences, using strings as an example... - To begin with, every sequence in python can be indexed: you can use an integer to pull out a single item. - Indices start at 0 and go to the length of the sequence minus one. - For example if you had the string “Path” and you accessed the third index you would get the letter h (as a single-letter string). P A T H zero one two three. - To index a sequence in Python, write the sequence (or the name of the variable you've stored it in) and then add square brackets afterwards, with the index integer inside the brackets. You could also use a complex expression or variable in the brackets. - In addition to indexing them, sequences can be sliced: use square brackets just like an index, but put a colon inside to separate two integers, and you can grab a sub-sequence between those two positions. - For example, if we sliced the word "path" from index zero to index two, we'd get the letters P and A (the slice goes up to but NOT including the end index). - A slice can even use two colons to provide three numbers, where the third number is a step value indicating how fast to go; a step of 2 would skip every other letter, for example. - Since indices are used so often for dealing with sequences, Python actually has a special kind of sequence called a "range" that can be used to easily generate indices for any other sequence. - The built-in "range" function can be called with 1, 2, or 3 parameters, to specify a start, stop and step, and it gives you back a special range-type sequence of integers that starts at the start value, ends just before (but not including) the stop value, and changes by the step value each time. - If you just call range with 1 parameter, it uses a start value of 0 and a step value of 1, so it will give you a range containing the integers from 0 up to but not including the number you gave it, and if that number is the length of another sequence, that range will contain exactly the indices of that sequence. - This is why range(len()) is a kind of idiom in Python: throw any sequence inside of len, and call range on the result, and you'll get a special sequence containing the indices of the first sequence, including the part where it starts at zero and stops before it reaches the length of the sequence. - For example, the word "hello" as a string is a sequence with 5 items, which are the individual letters, and it has indices zero, one, two, three, and four. - If we call len(hello), we'll get the number 5, and if we call range(5), we'll get a range with the numbers zero through four. - So if we call range(len("hello")), we'll get the right indices to use with that string. - But why would we want the indices of a sequence as another sequence, how is that even useful? - It turns out that one of Pythons loops, the for loop, operates exclusively on sequences. With a for loop, we can take a block of code and cause it to repeat once for each item in a sequence. - And what's even better is that with a for loop we get to declare a loop variable, which automatically gets assigned to the current item in the sequence. - We can use a for loop directly with a sequence, and our loop variable will hold items from that sequence, like letters if it's a string. Or, we could use range and len like we just talked about so that the for loop will iterate over the indices of our original sequence, which is called an index loop. - If we just want to repeat some code a set number of times and we don't care about a sequence, we could also use the range function, without len, to construct a sequence of numbers that has the length we want. - In all three cases: iterating over values, iterating over indices, or iterating over a custom range, the for loop works the same way. - You write for "loop variable" in sequence, put a colon, and then add an indented block of code. - You get to pick the name of the loop variable of course, so you might write "for letter in word" or "for number in range(5)". Python will then repeat the code in the block once for each item in the sequence, and during each repetition (called an "iteration") the loop variable will take on the value of a different item in the sequence. - So if we need to do something like count vowels in a word, we could use a for loop to do that, getting letters into the loop variable and checking them one by one. - There are actually two kinds of loops in Python. In addition to or loops, there are also while loops. - Last week when we talked about conditionals we talked about the if statement. You can think of a while loop as an if statement that constantly repeats itself until its condition becomes False. - When you execute a while loop you write the word while and then your condition, which is a boolean expression just like for an if statement. - The difference is that once the following block of code is complete, an if statement will continue to the code afterwards, but a while loop will check the condition again, and keep repeating its block of code until the condition evaluates to False. - So what exactly happens in your computer when you write a while loop? - First of all a line of code that starts with the keyword "while" is a while loop, so when you computer sees this keyword it starts executing the while loop. - Then your computer gathers all of the lines of code which are indented at the same level as the first line of code following the while line (including that first line of code). This is the loop body. - Your computer has to determine whether or not to run the loop body and the way that is determined is by checking the continuation condition. - If the continuation condition evaluates to True (because remember the continuation condition is a boolean expression), the loop body is executed using all of the normal rules for executing code, including these rules about loops. - If the continuation condition is not met, the loop body is skipped and execution continues after it. - If the loop body is not skipped, when the body is finished executing the while statement is revisited and the steps start again. - So the loop condition is simplified again, and if it still simplifies to a true boolean, the loop body is run again. - This process continues until the loop condition simplifies to a False value, at which point the loop body is skipped and the loop ends. - If the loop condition never becomes False, the loop will continue indefinitely, which is called an "infinite loop." - That’s why it’s easy to think about while loops as if statements that repeat themselves. - A concrete example would be counting down, like for a rocket launch. - First, we could set up a variable called n, with the value 10. - Then, we could use a while loop with the condition n is greater than or equal to zero, and in the loop we could write print(n). - With just that code, Python would keep printing 10 forever. - But if we add another line of code inside the loop that says n gets n minus one, then it will count down, starting at 10 and counting until it reaches zero. - After it prints zero, n will be assigned to -1, which will cause the condition to be False, and the loop will stop. - One last thing I want to touch on in this episode is the use of accumulation variables. - Often when we use loops, we want to build something up across different iterations, perhaps by adding numbers together into a sum, or by concatenating strings together into a longer message. - To do these kinds of things, we can create a variable before the loop begins, and then update that variable in the loop by adding to it. - Since each iteration of the loop will add to the same variable, by the end of the loop it will have accumulated a result. - For more complex results, you can use a conditional inside the loop as well, so that the counter is only updated on some iterations, not all the time. - This kind of setup is how you would solve the counting vowels problem we talked about at the beginning of this episode. - This week we talked about sequences, and for loops which are used to iterate through sequences. - We also talked about while loops, which use a continuation condition instead of a sequence to control their iteration. - Make sure you understand the properties of sequences, such as indices and how these properties are used when iterating using loops. - This was Path to Programming hope! It was great talking to you, see you next time.