At ranges or sequences of numbers and then we'll do a practical example on nesting ranges listing out the first n prime numbers the top right of your screen a link will appear has just appeared and you'll be able to click on that at any time to see not any files to do with the tutorial but also to do some exercises so you can practice and see if you've understood what you've learned but i think that's enough of me so i'm going to vanish now and let's get started.
Life is full of while loops and you may be more of a programmer already than you think you are for example while it's raining you're carrying an umbrella while your cat's pairing i hope you'll keep stroking it and while this tutorial is interesting i hope you'll keep watching it so let's see how this works in python terms the syntax of a while loop is you continue doing something while a condition is true and for as long as that condition remains true you keep executing all the.
Statements which are indented after it when the condition is no longer true you carry on with the rest of the program so let's see how this relates to python so what we're going to do to begin with is to create a program to list out the first few even squares so i'll create a new file and we'll call it list even squares and don't forget the dot py to state to visual studio code that is a python file.
I'm going to create an integer variable and i'll set it equal to one to begin with i is quite a common thing to call your loop counters and then we're going to keep looping until we reach a certain value and to do that i can put a while statement and then the condition which has to be true is i has to be less than or equal to let's say a hundred and then i need to put a colon to say that's the end of my while loop when i press return i come to the statements which are executed while that condition remains too true.
To make it easier to write i'm going to create a variable called square and set that equal to i times itself and then i'm going to print out a message saying the square of 2 is 4 etc so to do this i can put the square of and then i need to concatenate that together with something using the plus symbol the next thing i'm going to do is put in the integer variable holding the integer but i need to convert it to a string using the str function.
What i've done wrong okay so let's run my program so if i press alt ctrl n and you can see it's printing out the square of one is one millions and millions and millions of times so i'm going to try to abort my program and apparently i can do that by pressing alt control m in code runner and that looks like it's stopped the program running but then it just carries on again you can press ctrl c some people say um but that doesn't actually seem to work either and in fact the only way seems to be to close down visual studio.
Code and to start it up again so that's what i'm going to do now and i'll see you after doing that so the thing i did wrong was that my condition remained true permanently i will always be less than 100 less than equal to 100 because it never actually changes so what i need to do within my world condition is i need to increment its value increment is a techie programmer term for just adding one to a variable so to do this i'll show you two different ways to do it the first way is to take the value of i and set it equal.
To what it used to be plus one more and the second way to do it is to say i plus equals one they both do exactly the same thing the second way is probably the neater way to do it there's certainly less characters and you can also type i minus equals one i divide equals one and i star equals one to do similar things so let's try running this i'm more confident now that it's actually going to work so if i tried running it and you'll see it's.
Almost perfect the only thing is i'm printing out the squares of the first odd numbers and the reason for that is i should have started on two not one so i'll just change that and try again and this time it's working it's printing out the squares of the first even numbers and that's almost the end of the story on while loops there's one more thing you can do which is you can add an else condition and the else condition is used when there's something you want to print out if the loop never executes.
So what i'm going to do is add a message saying it never executes and try running it now at the moment that statement will never appear because the loop does execute so i'm going to cheat a bit i'm going to set this to 200 rather than just two and if i now try running my program and what you'll see is because it never the condition is never true at all because i is never less than equal to 100 what it will do is go to the else part.
Of my while clause and print out the message that it never executes and then whether the leap executes or
Not i'll get the final message saying that's it and that's a basic loop statement in python what i'd like to do now is briefly look at how you can exit out of loops prematurely or even say you want to ignore the current loop and go on to the next iteration around it so to do this i will create a new uh program and i'll call it fizzbuzz.And if you never played the childhood game where you had to say fizz when the number was divisible by three and buzz when it was divisible by five oh you missed a treat so what i'm going to do is print out all the numbers divisible by three to do this i'm going to start by creating another variable i'll call this one counter for a change and i'll set it to zero and then i'll keep looping while things are true now that's always going to be true so unless i prematurely exit out of this.
Loop i've got problems it will leap infinitely what i'm going to do firstly is to increment a counter by one each time around the loop then what i'll do is test whether i've gone too far and my definition of going too far is when i've reached a hundred so if counter is greater than or equal to 100 i know i need to stop and to exit a loop prematurely like this you put the word break and what that.
Will mean is it'll drop out the bottom of the loop and carry on with the rest of the statements so the next thing i'll do is test whether it's divisible by three to do that i can say if the counter and then i'm going to use the percent operator and what that does is divide another one number by another and looks the remainder and if the remainder is zero sorry if the remainder isn't zero so i'm going to put exclamation mark equals.
So if the remainder isn't zero then i know i've got a number which isn't divisible by by three and i don't want to process it any further so what i can do is use the continue statement and what that will do is carry on with the next iteration around the loop aborting this current one so if i get to this point i know i've got a variable called counter which is divisible by three and so what i can do is print out the value of it and i'm going to print out two things the value of the variable and then the word fizz.
Which i believe is what you had to say when a number was divisible by three and finally just to show when my loop is finally finished i'm going to print out a statement saying that's it so let's see what happens when we run this program what i should see is all the numbers divisible by three and fizz after them and when it reaches 100 it stops falls out the bottom of the loop and executes the final statement saying that's it.
So those are the two statements you need to know about when you're executing a loop and you want to prematurely end it or prematurely go on to the next item break will exit the loop automatically and you'll drop out and execute the next statement following it whereas for the continue keyword it won't exit the loop but what it will do is go on to the next iteration of it so we'll ignore any subsequent statements and go back up to the wild condition at the top of the loop excuse me and it will start again with the next iteration around it.
I think it's past time that you met our cats and they are annie who's the minx and neo who likes nothing better than to lie with his paw over your arm like that so what we're going to do is to write a program to say hello annie and neo but i'm going to make the program variable so that you can greet your pets instead you'll see what i mean so what we're going to do is to close down any files we have may have opened you can do that by right-clicking on any of the tabs and choose close all.
And what i'll do is create a new program and i'll call it greet pets we get the py so i'm going to create two variables called pet one and pet two and you can at this point set them to be the names of your pets obviously this program only works if you're lucky enough to have two pets and what we're going to do is print the message saying hello annie and neo in three different ways so let's start with the hard way the hard way is to build up a message.
Using a plus symbol to concatenate the various parts of it together and we've seen this several times already so i
Could say print i'm going to put the word a hard way at the beginning just to say what i'm doing and i can put in hello put a plus symbol in put the name of the first pet which is pet one put in the name of the second pet like so and it's a real pain getting the pluses.In and the space is in the quotation marks in but when i run it it should actually give me hello annie and neo so the second way i'm going to do it i'm going to call the easier way and what this will do let's just start it off easier way we can put in placeholders for where we want the pet's names to drop in so the first placeholder i'm going to put in is one for the first pet and the second placeholder i'm going to put in is two for the second and placeholders have to go in curly brackets like that.
Having done that uh when i finish my string i need to put a dot in to format the string choose a format function and the rules are that for however many placeholders i've just created i need to put that many arguments so this time i put two placeholders in so i need to put two arguments the first one will be the name of the first pet and the second one will be the name of the second and in theory what should happen when i run this is it should take the name of the first pet which is annie and just play it there instead of the.
Placeholder and take the name of the second pet which is neo and position that where the second placeholder is but i made one deliberate mistake so it's actually not going to work and if i try running it i'll get this message so this is why programmers get paid so much replacement index 2 out of range for positional argus tuple what could be clearer what this is actually saying is that i've created three placeholders because by default everything in python starts from zero so this is actually the.
Second placeholder and this is the third and yet i've only provided two arguments and that's what it's complaining about it's saying what about the value for the third placeholder which is this one so there's a couple of ways around this i could just add in a third argument so if i did this what it would do is put an empty string in for the first non-existent placeholder i haven't used a xero put the annie's name in for the second and neo's name in for the third.
So if i run this file or this program you can see it says hello annie and neo probably a neater way to do though would be to follow the python programming conventions and put zero in for my first argument and then put one in for my second and if i try running this you should see it gives me the same results again so the third way to do it which i'm going to call the easiest way even though it's not the way i'll probably use in most of this tutorial is to print out a message with the f prefix.
And what the f prefix allows me to do is to insert variables within my string of text in the curly brackets so i can put pet one in there and it will automatically put that in the string of text and i can put the second variable pet2 to display that now it may look like that the easiest way and it probably is but the problem is it only works really well with text with numbers it's not quite so flexible and because i try to avoid showing two.
Different ways to do everything believe it or not we're going to stick to using the format function for most of this series of tutorials but let's just see the third way working if i now run that program you'll see i get hello annie and you a third time so what we're now going to do is to look up formatting numbers we'll do two things the first thing we'll do is print out the first 10 cubes and in doing so.
We will allocate two characters for the number who's which you're cubing and for the cube itself we'll allocate four characters for the second thing we do we're going to go on to look at printing out reciprocals same principle for the first number we'll allocate two digits or two characters and for the reciprocal which is basically one over the number it's a posh way of saying that we'll allocate one character before the decimal place and two decimal places after that.
Now the syntax for doing each of these two things is as follows for the integer the bit before the decimal place is the placeholder so that would be the first item in the list of variables to be displayed on the list of expressions and the bit after the decimal place is the number of digits or characters assigned to it so that's for integers for decimal places it's a similar idea so again you have the placeholder position number before the colon.
And after this colon we have the number of characters and the number of decimal points or decimal places to be displayed and the f there is saying what sort of a number it is it's saying it's a floating point number so let's see how this works in visual studio code i'm going to create a new file let's call it uh list math terms dot py and within this we're going to set another variable i'll call it i to hold the loop counter.
And while i is less than or equal to 10 this all seems very familiar doesn't it i'm going to print out uh both a number and its cube to do that i can put print and i can put the cube of then i can put my first expression so i need to placeholder zero and then i can put is and then put my second placeholder one i then need to put the format function after the string to say what i'm substituting in for each of these two placeholders.
For the first one i'm just putting the number itself and for the second one i'm putting the number raised to the power of three and to the raiser number to the power of something in python you put star star so i can put it like that now i'm not going to make the mistake i made last time i'm going to make sure i increment my loop counter so i can put i plus equals 1 which will make sure that i don't get an infinite loop let's try running that if i press alt ctrl n as usual you can see i get the cube of each number and its cube.
Now i promised i would format them to occupy a certain number of places or characters so to do that for the first placeholder i can put a colon after it and then i could put two to so i want that to occupy two spaces and for the second placeholder i can put a colon and put four to say i wanted to occupy four spaces it's that simple if i now run the program again you'll see i get arguably a better formatted output string so that's how you can format integers what i'm now going to do is to comment out all that code i'll keep it in but.
For reference but i don't want to actually run it the second time and then what i'll do is do the same thing for reciprocals so before we actually print out the reciprocals i think i could do with a comment saying what we're going to do i'm so bad at typing the word reciprocal that i've actually put it in my clipboard because i kept mistyping it so what we're going to do is create a variable called i to hold the number one and for as long as i is less than or equal to 10 we'll print out a message saying.
The we go again the reciprocal of i could put my first placeholder and then i can put my second and after the string within the brackets i need to put the format function and put the two expressions which i want to display within my string the first one is i and the second one is 1 divided by i which is the reciprocal of it and as before i need to make sure that i go on to my next number otherwise i'll.
Get an infinite loop so if i try running that as it stands i get the output but not very well formatted so what i'm going to do now is to add the formatting in and this is going to use the syntax i explained earlier so the first bit of it i can just put two digits but for the second part of it the reciprocal what i'm going to do is put a colon after that i'm going to say i want six characters for it and then i want two decimal places now i've missed out the f deliberately there i just want to show you what.
Happens if i do this if i run that i don't get two decimal places for every single number it depends what the number is i get up to two decimal places so that's why i need the f in to say this is a floating point number and then when i run the program i get exactly the output which i was seeking what we're going to do now is take a bit of a digression away from visual studio code from python so you can rest your typing fingers for a short while and we're going to look at what i would argue is the most important concept in the whole of python.
Which is iterating over sequences let's suppose you have a shopping list you want to buy an apple a banana and a pear the important thing is you buy every single item the order doesn't matter you might always buy things in alphabetical order so you might buy the apple then the banana and then the pear or you might find that the bananas are the first thing which meet your eyes you come into the shop and then you see the pears and then you see the apples or you might buy the pear and then the apple and then the banana.
It really doesn't matter what order you do things in as long as you tick off every single item in your list and that's what a sequence is to do this in python use this syntax you say for every item in a list the list in this context i'll just highlight it is the set of things which you're iterating over and we'll discover it can be one of four main things in a moment and the word item in this context refers.
To a variable which will point to each of the items in the list one by one so in our context the item variable will point first to the apple then the banana then the pair or maybe some different order so let's look at the properties of a sequence it has two main characteristics the first thing is that there should be a way to move on from each object in the list or each object in the sequence to the next item and the second property is that once you've gone on to the final item there.
Should be a way to say that's it i've finished my sequence i've run out of items you can exit the loop and run the rest of the code so what are the main sequences in python well there's four the first one is you can have a range which is what we're going to look at in this tutorial it arranges a sequence of numbers you can also have a string which is a sequence of letters or characters you can have a list which is a mutable sequence of things mutable means you can make changes to it so the shopping list.
Would be an example of a mutable sequence because you can add items to the list when you suddenly remember that you've forgotten to write down cherries on the list and a tuple is an immutable sequence so that's where you've laminated your list so you can't make any subsequent changes to it in the shop so that's a brief look at sequences in python what we're now going to do is go back to python code and show how you can use sequences to loop over ranges.
So we're going to do three examples of ranges to illustrate the syntax and then one full worked example so to create the three syntax example examples let's create a file called range syntax dot py and the three ways you can write the range function the range command you can write it with one two or three arguments so let's start with the most simple one which is with one argument and what we're going to do is just print.
Out the first 10 numbers and the important thing is that ranges start at zero so what i'm going to do is create a variable to refer to the first 10 numbers let's call it first 10 and i'll set it equal to not a single number but a range and if i put the number 10 in there what i want to do is show you that this isn't quite going to do what i wanted to do so i can now loop over the numbers in that range so to do that i can put the word four in.
To start an iterator and then i can use any variable name i like to refer to each of the items in the sequence i'm creating so i'm going to use i because it's nice and short and it's what i tend to use to refer to an integer then i can put the word in in and the thing which follows that has to be the name of some iterable sequence or just a range in this case of numbers so i'm going to use my variable i've created called first 10 and then i need to put a colon to say that's the end of my loop statement.
And press return so what i can now do is run any statements i like and they will execute 10 times once for each time around the loop and each time around the loop i will have a successively higher value so i'm just going to print out the value of i like so and then if i run this program to look at the results of it you'll see it actually starts with zero and takes me up to nine and that's because ranges always start but at zero by default so we can get around that by using the.
Syntax with two arguments what i want to do now is to close down the terminal window and to do that if you press a control and the inverter comma once it takes you to the terminal window and if you press it a second time it closes it down so i'll be doing that quite a bit throughout these tutorials so let's create a second one or second syntax example this one is going to have two arguments and the important learning point about this is that ranges miss out the last term which takes a lot of getting used to.
So this time i'm not going to use the variable to refer to my range of numbers i'm just going to launch straight into my loop so i'm going to say for this time i'm going to use the variable j because i've already used i and i'm going to put for j in use the range function for my first argument i want to say my starting point which i'm going to start at 1 and for my second argument i'm going to put my end point plus 1. because i want to go from 1 to 10 i'm.