Python Code for Beginners | Grant 'Angular' K | Skillshare
Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
53 Lessons (6h 2m)
    • 1. Introduction to Software Engineering for Noobs

    • 2. Get Setup Visual Studio Code and Python

    • 3. Square Peg Round Hole Variables and Types - Explanation

    • 4. Square Peg Round Hole - Variables and Types

    • 5. Variables and Types Task

    • 6. Variables and Types Task Solution

    • 7. Stamps and Coins Arrays and Collections - Explanation

    • 8. Stamps and Coins - Arrays and Collections

    • 9. Arrays and Collections - Task

    • 10. Arrays and Collections Task - Solution

    • 11. Special Forces Operators - Explanation

    • 12. Special Forces Operators in Python

    • 13. Operators Tasks - One is Very Hard

    • 14. Operators Tasks in Python - Solutions

    • 15. Strawberry to Banana Conversion Between Types - Explanation

    • 16. Strawberry to Banana - Conversions in Python

    • 17. Conversions in Python - Task

    • 18. Conversion Tasks in Python - Solution

    • 19. Mine is Bigger than Yours Comparisons - Explanation

    • 20. Mine is Bigger than Yours If Else Comparisons in Python

    • 21. Comparisons If Else in Python - Task

    • 22. Comparisons If Else in Python Task - Solution

    • 23. A Merry Go Round - Loops - Explanation

    • 24. Merry Go Round - Loops

    • 25. Loops - Task

    • 26. Loops Task - Solution

    • 27. Getting it Done Methods or Functions - Explanation

    • 28. Getting it Done Methods or Functions in Programming

    • 29. Methods or Functions - Task

    • 30. Methods or Functions Task - Solution

    • 31. Sorting Things Out - Classes - Explanation

    • 32. Function Returns in Programming and Some Forbidden Fruit

    • 33. Function Returns in Python - Task

    • 34. Function Returns Task - Solution

    • 35. Confusion Reigns Classes vs Objects - Explanation

    • 36. Sorting Stuff Out - Classes

    • 37. Classes - Task

    • 38. Classes Task - Solution

    • 39. Confusion Reigns - Classes vs Objects

    • 40. Classes and Variables - A Warning

    • 41. You Are Rich - Inheritance - Explanation

    • 42. You Are Rich - Inheritance

    • 43. Inheritance in Python - Task

    • 44. Inheritance Task - Solution

    • 45. Shh Its a Secret - Encapsulation - Explanation

    • 46. Hide and Seek - Encapsulation

    • 47. Tell Me What to Do - User Input

    • 48. Input in Python - Task

    • 49. User Input Task - Solution

    • 50. Class Project - Setting Requirements

    • 51. Class Project - Solution Part 1

    • 52. Class Project - Solution Part 2

    • 53. Class Project - Solution Part 3

  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels
  • Beg/Int level
  • Int/Adv level

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.





About This Class

This is Why You're Here:

Have you ever stared at a wall of code wondering what on earth is happening?

Have you ever been in a coding course and wondered what is this dude talking about?

Have you ever ... (ok, you get the idea)


My 500,000 Student Survey Says...

I've taught about half a million people to code online and you know what I've realised?

People don't want to learn to code - they want to make things. Code is just the tool they need to do it.

Once I changed my courses to this focus I saw success in my learners many times greater than even I could have imagined!


But Code is Hard, Right?

Code, though, seems pretty complex - but in reality it isn't. 

The problem stems from many places, but a big source is existing engineers and course developers. That's because we want to feel clever.

Every time we use a big word or new acronym we feel great and you feel not so great. We seem to get our status by putting you down. Is it any wonder that many learners tune out?


You Need Fundamentals

In addition to that, most courses still don't boil down the course to the fundamental issue:

You just want to learn code to build something!

What I see every day in other courses:

  1. Many courses are hyper focused on correct code (not a bad thing).
  2. But they don't give you software engineering principles.
  3. You are guaranteed to fail if you don't learn these principles.

I've watched the above dynamic play out since 2014 and is exactly why I started iAmDev. Yes, I should have started earlier, but the second best time to start something is right now!


So What Does this Course do for You?

This entire course was designed fro the ground up to be a prime example of my "engineering first" philosophy:

  • It presents code in the context of building things
  • I get you to build something after every video (that's the best way to learn!)
  • By the end you'll build a full text based accounting app for a coffee shop


How This Will Enhance Your Skills

Coding software isn't about the code, really. It's abut engineering a solution to a problem. To reinforce that I leave you with intriguing questions in every section, such as:

  • "How could you make this better?"
  • "What bugs would this introduce to your software?"
  • "Would a paying client be happy with this?"

Fundamentally, this beginner course is my way of showing you the truth behind software engineering.


Code is not hard, nor is it the goal you're seeking.

Instead, let me show you how to become a software engineer.


About You

  1. You are confused by terms like "object, class and variable". If you're already a proficient engineer then this is definitely not the course for you!
  2. You like to take things at your own pace.
  3. You want principles for software engineering, which open doors to bigger and better career options.


About the Course

The course runs at a very slow pace, ensuring you understand the basic principles of all software engineering. You can always speed up playback to suit your learning style.

This course uses Python as the code language but once you're done you'll have the tools to use any language out there. In fact I even give tips and hints when using certain things in those other languages.

The course includes over 10 practice exercises and one large final project. To help you on your way I give solutions and hints so you can figure it out yourself!


What You'll Come Out With

By the end of this course you'll have:

  • The tech skills needed to make any software in any language. No, I'm not kidding - that's the power of teaching principles!
  • A better understanding of "solution thinking".
  • The ability to think critically about problems (useful in all areas of life!)
  • And a whole load of tips from a tutor who's learnt, freelanced, published apps and taught others for over a decade.

I look forward to seeing you on the other side!

Meet Your Teacher

Teacher Profile Image

Grant 'Angular' K

Crazy about Angular!


A passionate Angular developer. Let's make cool stuff together!

See full profile

Class Ratings

Expectations Met?
  • Exceeded!
  • Yes
  • Somewhat
  • Not really
Reviews Archive

In October 2018, we updated our review system to improve the way we collect feedback. Below are the reviews written before that update.

Your creative journey starts here.

  • Unlimited access to every class
  • Supportive online creative community
  • Learn offline with Skillshare’s app

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.


1. Introduction to Software Engineering for Noobs: Now I assume that because you're here watching this, you want to be a software developer, whether that salaried freelance or just making your own applications. That's why I've made this course. Too many courses give you a whole bunch of facts and they throw those facts at you and then expect you to make sense of all the facts. So case in point, the top selling courses on all the platforms I use our house, make Android apps, helps make iOS apps. And I've been guilty of this in the past. What those courses do is they don't tell you how to make apps. They show you An someone made previously, and they don't outline the fundamental structural items that are contained in that code. That's why I created this course, because I want to give you the fundamental structures for programming in any language, not just Python. We just using Python because it's the world's most popular language at this point. But at some point it won't be. This course is there, so that you can understand those fundamentals and carry them over to all the other languages that you want to learn in the future. It's something that took me a while to learn when I was learning. But once I got those, any language was open. I, if I never use Java, I could just jump right in and use Java. You'd never believe from watching this course that I hadn't written any Python up until two or three weeks ago when I started planning this course. But that doesn't matter because I understand the fundamental concepts. All I needed to look up was the syntax, how the code is laid out, but the concepts stay the same across everything. So that's what I wanted to give you as the learner. You take this course, you will understand any language just with a little bit of extra work for each new language. Ok, now this course is for you if you've never programmed before, okay? If you know what a variable is, a class is an object is, and you understand those, this is definitely not for you. You will find it so slow and heavy going. If you don't know what those things are, then you're in the right place because I explain them all. But I explained them all in the context of becoming a software engineer. So throughout this course, you're gonna learn stuff like variables, functions, classes. You're going to learn how to smash them all together to make a fully functioning piece of software that you can easily maintain and you can easily upgrade. That will be the final class project. Okay, so all those weird words you've just heard, if you have never heard them before, by the end of this course, you'll be saying them every day and you'll be one of the developer crew asked people who uses big words all the time. Now the way I've laid out this course is how I would like you to follow it. You don't have to, but I think it's a good idea if you do. So the first video in each section, each important topic is just an iPad scribbling session with me scrolling on it explaining what that item is. Variables, for example, why are they different kinds of variables? Numbers, sentences, strings? How are these things different, and why are they different? Then we jump into the code. So you'll see a little bit of code like that where I'll be typing in real-time onscreen. Please follow along with what I'm typing, cause just the mere fact of you typing with your fingers will really get things to settle in your brain. Following each section, most sections, I give you a little problem that I want you to solve. So in this case, I get you to create a program that stores your house number and street name in different variables and then print them out to combine them into a sentence. And then of course below that, I give you the answer in the following video. But please don't just skip to the answer videos. You don't learn by just watching. You learn by doing. I cannot emphasize that enough. Please try the exercises I give you. If you get stuck, by all means, look at the solution. That's fine too. But just the mere act of making an effort will get you much further ahead. Everybody else that once that Python programming job that you're after. So that's how it works. The final parts of this course is a project where I get you to make an accountancy app for a coffee shop that keeps track of daily profit, income and expenses. Believe it or not, by the end of this, you'll be able to do that. It also allows the user to enter inputs and receive messages back from your app, all in basic Python and all of that you will learn within a couple of hours of consolidated effort, right? That's everything about the course and the introduction. I'll see you on the other side. 2. Get Setup Visual Studio Code and Python: The first thing we have to do, of course, is install the program that allows us to edit Python code. Now there are many, many options for this, but I find one of the best is Visual Studio Code, which we can get at code dot Visual Just download the correct version for your operating system. It's on every system and install that. Once you've finished installing VS code, then you will actually need to install Python. It's self. So in the VS Code documents, there is a document that tells you how to run stuff in VS code using Python. It's the first thing you need to do is get Python 3.7 from So if I click that, it actually gives us 3.85 is the latest version, that's fine. You could probably also do this on four because this isn't going to be a very complicated cause. When that's finished running, I finished downloading. Then we're just gonna run it, install it wherever, and let it do its thing. And we're gonna go ahead and close that off that there is one more thing to install, and that's to install the extension from the Visual Studio code marketplace, just called Python, and it is by Microsoft. But could that 23 million installs? Pretty amazing. So should let that finish. I think that should be about enough for now. We're going to run VS Code. And I'll show you how to install the extensions. Let me just get rid of some of this junk. So these little icons at the side here on the left, one of them is extensions. If you click that, then you can search for Python. And it is usually should be the first version, which again is Microsoft. So we're gonna go ahead and install that. And that allows Visual Studio Code to autocomplete your code to tell you what things are wrong and when, when it comes to creating Python code. So that's installing, We can actually close the browser. But before we do, let's see what we've got here. This Microsoft article in this dress, if you want to go to it, runs through all the steps you need to run code. It tells you we have auto completion IntelliSense. And if you're new to programming, autocomplete just means it can guess what you're trying to say and then modify it guesses in the future. So it always gets it right for you. Lamenting, just simply analyzes your code for potential areas. And that makes it easy to navigate to and between different problems. And as a software developer in the making, problems is your main currency debugging. So we can ignore that this is all stuff that I'm going to cover. We're going to cover some of it because I can't possibly cover all of it today. So Python is now installed. Ok, there is a little thing down here called Disabled max path length changes your machine conflictual our programs including Python, to bypass the 2.6D character Max path limitation. Now in windows and some operating systems, the amount of characters you can have in the address for a file is limited. So if you have lots of subfolders, you can actually exceed that limit. So it's up to you if you want to disable this. If you have something in Dropbox, it's actually enlight, uses your name, Dropbox, something, something. And quickly you can get to the end of that path limit. So if you see this keyword anywhere max path, then you know there's an issue with the path. So you can go ahead and disable that if you so wish. I'm not going to do that for the purposes of this course because I know I am good to go. So once you've installed Python, that's pretty much it. We've installed the extension. The runtime is in the back. You'll notice that Visual Studio gives you a little hint down here that says no python interpreter is selected. You need to select Python interpreter to enable features such as IntelliSense lynching and yada, yada. So I'm going to hit Select. And it's going to say here are all the options I found on your system. So I still have Python 2.7, and that's from something else I installed in Visual Studio. But the one we just installed was 3.8.5, 32-bit. So this bottom section, go ahead and select one of those. And all the areas should be clear and we are good to start the course. 3. Square Peg Round Hole Variables and Types - Explanation: Let's discuss variables in software engineering. But let's start first with cake. How do we bake a cake? Well, let's sketch that out. We've got 2x. We've got two cups of flour. We've got a cup of I can't spell Sugar. We'll leave it at that, the world's worst k. So what do we have here? We have bits of information, right? 2x is a bit of information to cups, and one cup of sugar are also bits of information. We have three chunks of information. Why do we need the chunks of information? Well, because at some point we are going to process those bits of information. We're going to cook something. And then at the end, we shall have our cake and eat it too, or Ital cake and have it to, which is the correct way of saying that expression. Ok. So these things at the start are called variables, which is the same concept we have in software engineering. Variables are simply a little piece of information that we can then manipulate, multiply, add, subtract whatever it is through some processes that we defined in our software to produce an end result, which is in this case a piece of cake case. That's all a variable is just information. Now you can imagine if you have a computer program, you want to show the user, let's say a list of their train tickets they've purchased over the past. So here we go. We've got our Android or iOS screen. And we have a list of tickets here. Like so. And this scrolls up and down for getting all the graphics, all the things that go behind this, like getting stuff from servers and whatnot. All this is, is little chunks of information. So here we might have five variables, here we might have six variables that we're showing because there's something else on that ticket. Here, we're back to five variables. And of course this will go on and on. So variable, again, it's just a chunk of information. You'll notice that I've used this word var, which is quite a common word. You will also see things like Val, you'll see const, or you won't see anything at all, just the name of something declared as a variable. All these do in programming languages is say, this is a variable piece of information that you will store in the computer's memory. So I can come back, retrieve it later, manipulated, do something to it, and show it to the user. Ok. So on that note. We're going to come to the next very important thing about variables. And it's something that's stumped. A lot of people stumble over as they're learning to program stuff, becomes software engineer. What's that stumbling block? Well, let's just have a drawing here of the ram or the memory of your computer. And let's say we've got our train tickets. We said, hey, this one costs a 100, this one costs 200, and this one cost 302. You compute a needs to store that in the memory. So it can display these later on in that list of stuff. Or when you tap one of the lists of stuff, it'll open a new page. And then again, it's going to access these things in its own memory and say, hey, where was that value? I need to show it to the user, right? So the variables are stored in RAM. But let's say you have a list of 10 thousand tickets. Do we have enough room here for 10 thousand tickets? The answer, of course, as you can see, is no, we don't, because these ones take up way too much room. So what's the solution for this solution is pretty simple. Look very carefully what we've got here. These are whole numbers, right? Not just any old number. There are basic whole number, no decimals, and they're all positive. So we could say in software engineering that they have a basic type. There are basic number. So what we can do is say, I'm going to restrict this dataset of stuff here to only consists of the characters 1234, et cetera, et cetera, to 0. So 456789. And don't forget, we need to have 0. So there are only ten characters in this dataset. And that has the brilliant effect of reducing the amount of memory that we require to store all of these. Right? So the more you can narrow down a problem in software, the less space you'll actually use. But that is a double-edged sword. It can come back to bite you later on. So we will get into that as you learn. So now because I've defined these as a whole number, we can put these into the memory, and now we have loads of space to fail with all the other variables, fill it up to our heart's content. So we start to specialize. These whole numbers in most languages are called integers, and it's usually given in short form as int. You might see it as in 32 or 64. But basically int is there. If you had a number that was like 100.1, you might see words like float or double, or indeed number. But you can imagine if there's a decimal that is kind of another bit of information we need to include. So I don't know this for sure. But that would be represented by a float. Will I do know that beneficial? But a float I recommend would be larger in memory terms than an integer. It would take more space to hold the same number of digits. Okay? Because it's got taken to account this extra little bit of information, the decimal point. So I have just introduced you to the idea of typing. So you have a variable. But to reduce the memory footprint and for other reasons, we are going to shoehorn them into a box, fits exactly what kind of thing they are. Kind of like an egg box. And egg box is designed specifically to hold those. What's the correct term for an egg shape or blow it, something like that. There's those opioid, what's anywhere now is Opioid forms, and we pop six of them in a box. And egg box is not designed to hold six sets of giant Dice, Are they? They don't fit, right? And that's the idea behind types. Okay, so I'll just introduce you to one more type. We will get introduced to lots of types as we work through this whole course. So another type is something like this. A word IRR, GR. Well that's clearly not a number, is it? So it ain't an integer. It Aigner floated a number, it ended double. And if you try to make it that your software coding program is going to have a right Windsor at you and say, I can't do that. What are you doing? This is called a string. And a string is, is a set, a string of characters literally like you a beating something, you putting beads on a string. This is putting a set of characters along a string which makes a word or a sentence, you can hold a whole sentence. But with a string. You could also hold something like a number. 100 would be in this one. But 100, the string and 100 the number are not equivalent, right? The computer sees this one as a number. It sees this one as a string. So this the thing with types, we save a lot of space. We ensure compatibility when we're comparing types to each other or multiplying them or adding them, whatever we do to them, manipulating them. But we have to be very careful that we don't say try and add the 100 string to the 1-800 number because that's simply won't work. Well, it can work, but there are ways we have to work around that. Okay? So those are variables, chunks of information and types, space optimized ways of storing those chunks of information. And those types also exist so that when we compare chunks of information and do calculations with them, they will be stored in a compatible way that we can actually perform those processes. 4. Square Peg Round Hole - Variables and Types: Let's talk about the fundamental building block of all applications in any language on any device. And that is the variable. It's the first thing we're gonna do actually is to create a new Python Project in Visual Studio. So open up VS code. You're nice to get a little prompt to the left here, open folder or clone repository, where we're going to open a folder. And if you can't access that, go to file at the top open folder, we are basically going to create our own folder. So I've gots the foldy hair or I'm preparing the videos for you guys. And I'm going to right-click new. Just create a folder is obviously will look different if you're on a Mac or Linux. If you're on Linux, you should know how to do this already. And let's have live code sessions, even call this anything you like. This is basically a folder that will hold all of our code files. I'm going to select that folder. And when you do so, VS code opens up this little welcome screen and you can create a new file. We're not going to do it that way. We're just gonna close that welcome thing there. We are gonna cover which the side here right-click and hit New File. You can also access this extension to create a new file. At the top here, the screen just jot and it looks like everything zoomed in. It's because I realized that the text wasn't big enough for people watching on small devices, so I quickly changed it, right, so we're back at our new file creation. What are we going to call this? Well, let's just call it something really obvious. Variables dot PY. Py identifies this file as a Python file, which means Python can execute it. Right? So we have variables file. What's the first thing that we need to do? Well, all variables need to have a name. So let's actually call a variable name. And inside that variable we want to put my name grant. So the way we assign stuff into variable, variables is by pressing equals open and close quotes. Grant. Ok, we can put capital because this is case-sensitive after all. So we have a variable name. We have an equals, which is called the assignment operator. It assigns a value into a variable. Surname is the box in memory. This is assigning a value into that box and the value is Grant. Why is it in quotes? Well, the reason it's in quotes is because this is a string or a set of texts. And the way we do it in most software programming is to put that value in quotes to signify this is actually a string. You'll notice if you've programmed or seen other tutorials for other languages. We don't do things like this. We didn't have var name, we don't have val name. In other languages. Usually something like var denotes that this is a variable, hence the name. Far. In Python, we don't actually need to do that. We just give it a name and hey, presto, it's there. What if I want to assign an age to ground? Well, this is going to be a number. So numbers don't require the quotes, but they can have them. In this case, I just type the number, 37 years old. Right? Now, Python knows that this is a number and not a string, because it doesn't actually have these quotes around it. What else do we have? Well, we can also have a height in meters, which would be 1.9. Now believe it or not, this number is different to this number in its inherent characteristic in that this one has a decimal point. You wouldn't think that wouldn't met, that would make a difference, but it actually does. I'm going to explain how we see what types of things these are as we move on. Then we have another kind of variable. This variable is a Boolean, which means simply true or false one 0's. So let's have is male equal to true. So that is a Boolean. So what else are we going to have here? Well, it would be nice if we could see what the types of these things are. And the way we do that in Python is to have the following type name. Now that fires up Python and says, I need you to pull out the type of this name is a string, Text. Is it an integer, a whole number? Is it a float, which is a decimal number? Is that a Boolean which is a true or false? Now how do we see how Python sees this? Well, there's a simple command here called print, whoops, name. And we have to surround these things with these brackets on each side. So what this is gonna do is get the type and then it's going to print it to our screen. So let's save this. And the way you run this is to right-click. Go to Run Python file in Terminal. You'll get a little window that opens at the bottom. It will automatically execute the code for you where it is. And down below, you're going to see the output from that print line. This is class STR, which is short for string. Now what happens if I double-click Name and I replace it with age? I save that. You can right-click and goes there again, or you can go to the terminal below. So just click on this little window below, press upon the keyboard. Once it fires up the old command, you just ran, press Enter, and there we have it. The class here is an integer. And again, what is height? Save that. Run it again. Class float. Finally, let's have is male. And the class there is a Boolean. So I've just given you how to name a variable, how to assign a value into that variable. And what you probably noticed is that Python automatically decides what kind of variable this is going to be. It will choose the correct version for you. So over here, when we have the two quotes, it knows that this is a string. There's no two ways about that. If there are no quotes and a number, it'll say, Is there a whole number? Yes. Therefore, an integer. Is that a high? Sorry, is it a number with a decimal? It will put a decimal in and say This is a float, which is a way of storing the decimal numbers. And then finally, if you have true or false, it will say it is a Boolean. So we just discovered types. So as I discussed in the explainer video, the type is there to reduce the memory usage and to ensure compatibility when we do things with these types in our programming. Okay, so whilst we're on the printing trade, let me just drop this down a bit. What we can actually do is we can directly print the name. Okay, so if you save that, we hit up in the bottom terminal placenta. We get the first print line as we expect, but the next print line has the name ground. So this is taking this variable and doing something with it. It's accessing it and then printing it out to the command line. Now there's something very interesting here. And what is that you might say, well, let's print the name. And what if we want to make this into a sentence? Well, we can add another string. So this is another way of creating a variable, but without actually giving it a name, it's anonymous. Everywhere in the software world, you'll see the word anonymous. All anonymous means is that we didn't give the thing a name. We didn't give it a format. Formal name. It has no formal upbringing or something like that. So in here we can type is. So I'm gonna say grounds is, and then I'm going to put in the age. But you'll notice first that I've actually put a space at the start and the space at the end. So if I actually save that and then run it, whoops, up and run, we get our usual output. But down here, we have ground is those spaces are counted as characters in strings. So if I put a space up there that consumes memory is not just nothing. Okay. So coming back to this line, grant is, and what are we going to do? Well, let's put our agent plus h. I'm gonna press enter to save. Come down here, run it. We've just had our first crash. So Scratch starts up here. It tells you where the crashes. So as a developer, you need to know which bit of the code crashed. And it tells you in the module, we haven't defined modules, so we'll just leave that for now. It tells you the line where that happened. So you can actually search your workspace using control click in Visual Studio. So it's really helpful to find where this line is. But the actual error we need to see is type error can only concatenates string not into string. Now this may seem a little confusing at first if you've never programmed before, but it's really simple to decipher. Concatenate simply refers to match two strings together. That's what these pluses, it's saying, take this string and this string at the end of it. That's all it does. But what is complaining about here is saying, hey, you gave me a string, which is fine. But then you gave me an integer and that's not a string broke. So I can't use that. So what we have to do is change this into a string away from being an integer. And why do we do that? Well, when you're working with types in programming, it's like apples and oranges. If you going to have a basket of apples, you can't put some oranges in and say, hey, those are apples. No, it's apples and oranges. In programming, it's more or less the same. You need to work with the same type. So every, every simple example is, if I'm doing some maths, I can only add numbers, right? So if I said two plus two plus Fred, that doesn't make sense. Saman programming. So we have to say, I'm going to change this age to a string. Now that's really simple to do. We're just going to put SCR in front of it, open and close brackets on top of it, save that file. So we're going to get onto this in a subsequent lesson. This is called type conversion when converting from one type to another type. But there are some dangers to be aware of, which I'm not gonna go into now. But for now we're just creating a sentence. So back down to the terminal, press up and press enter. It runs it. We have no errors and we get the answer that we expect. So simple enough, what I'm going to do up here is actually prints nothing. And below here, I'm going to print nothing, perhaps twice. So it's really obvious where this program runs. So this is going to look something like this. It's gonna put some space in. So if you're following along on the screen, you can see where these things are. A k. So we've got our prints. Name is string and age. So here's a simple one. How do I add the height? I'm going to say plus. And is. Oh, and height is. And then let's have a plus. And then height is a number as well. So we're going to string up that and popping height. Save that. Let's run it. There we go. So that works perfectly fine. So you've just been introduced two types of variables. You've looked at how to kind of convert between variables in a way. And what else we're going to look at our, I think that kind of covers it for now. So what I'm gonna do is give you a task in the next video, and then also the solution in the next video. 5. Variables and Types Task: Alright, it's time to test out your knowledge and the best way to learn how to code is of course, to do it. So that's what you're gonna do after every lesson that I've given you in this course, the task, so I'm gonna give you are very, very easy and simple, but it helps reinforce everything I've just shown you. So what you're gonna do is create a Python program that stores your house number in one variable and the street name in another variable. And then guess what? You are going to print out a sentence that combines both the variables to show the full address. So I'm gonna give you a clue to start with. All of your variables are going to be of the type string. But don't forget those empty spaces that you need to form a good sentence. Good luck. 6. Variables and Types Task Solution: Let's discuss the homework. So first of all, we needed two variables. One was your house number and one was the address. So let's have house number is equal to now you could have whatever number it is, nine, but guess what? This is now an integer. It's a whole number. That's not gonna play very nice with the print line. So what you can do is actually this. You can have it as a string immediately. And then what else? We can have the address, or perhaps let us call this street name is equal to Fox crescent, something like that. And then finally we are going to print out the house number plus Fox crescent plus street name. There we go. So if I save this and I come down and I run it all, we have a problem right apart for my bad spelling of crescent, the actual problem we have is there is no space after nine, so we need a space. You can put a space here, or you could put it here. But you know what? Both of those are bad programming. Why? Because you may need to use these somewhere else. And if you stop modifying them to suit your needs now for display purpose, you might have to unmodified them later on when you need them for a different purpose that doesn't require the space, you've got to be very careful with this. What I would do is actually put this in here. Like so I will put the space in the middle. So if we save that and ran that, oops, let's run it. There we go. Now we have the correct nine of Fox crescent, which I'm going to correct the spelling of. Okay, so that's a little warning for you. Don't modify variables just to suit or how you're going to display them. If you need to display them, then modify them at the display time or rather at the things you need to or create new variables that will actually do the modification and store it in that new variable rather than in the old variable. It's kind of a concept you'll get used to as you learn more and more. There's another thing like in here. Before I go there, I'm going to warn you about house number is nine as a string, right? Let's say a, it wasn't house number. Let's say the thing that you were looking at with age and you just made it a string to make it very convenient. Ok, ignore the errors that are down here with not bother about that right now. If you made it convenient at this point, later on, if you wanted to add up all the ages in your program that you might be storing. Having a String is not convenient because you can't add strings in a maths way. You can only add numbers which are integers. So what you would do in this case is you store this as a nine. And then down here, you would turn it into a string. In order to display it. Everything would then be fine. Okay, so again, same principle that we had before of adding this space. Don't modify your variables to suit the display. Keep the variables in a Type II, a number, a string, a Boolean that suits that particular variable. That is a very important concept to get right from the start. 7. Stamps and Coins Arrays and Collections - Explanation: So let's discuss another kind of variable which is called a collection, an array, a list. They're pretty simple. Let's say you have a shopping list. You want to buy eggs, milk, bread. Now all of these things are contained on a piece of paper. It's a shopping list. After all. You can imagine if you had a software program, an app, or a web app that kept track of people's shopping lists for them. And you said to it, you can only put 20 things in this list because that's the maximum amount of variables I'm going to assign to you. Well, people wouldn't really use the app. They use it up to a point and then go, this is a stupid limitation. So the way around that is to have a list variable that works in the app. So the way we would define this is to put something like square brackets around it. So now we're telling our program, instead of creating three variables, eggs, milk and bread, I want you to create one variable, eggs, milk and bread, which is contained in a set of items or an array as this is nine. And then we would put that variable into say, var shop list. So now shop list would contain our three items. And what's brilliant about arrays and collections is that we can have any length items in the array. We can expand it to as big as it needs to be, or shrink it to as small as it needs to be. So that's basically what an array is. It holds a whole bunch of values. Now, there are times and there are certain languages that say, if you have an array, let's say 123. And you say var array is equal to that. This is fixed in some languages, you can't actually add anything to it. Other languages you could say a dot, push, throw in a new value and it would add four to the end of that array, or you can insert it somewhere inside the array. Other languages, yet, other languages say arrays are fixed and you can't add anything to them and that's the end of that. So what they say is, let's have a var b equal to a list. So a list is an array kind of, but it can expand its size or decrease its size accordingly. So it's a list 123. Now ignore the syntax with the square brackets and these normal brackets because they change depending on what language you're going to code. What's important is the concept here. Now arrays, you can add lists, you can, generally speaking, those things can change. Javascript as usual. Bang the notable exception to all of this. So those are very basic arrays and we use them to store a whole range of variables, particularly when those variables can change their length, right? So in a shopping list, you might have a shopping list one day that has three items, the next day it has 30 items. And so you use an array to store the shopping list because it's a variable length. Pretty straightforward. The other thing you need to be aware of are things called generally sets. Now a set, I could say he has one too. Three, What happens if I then say, show me that set. Or you might see something printed out on the screen as 213. And the next time you say show me, it'll be three to one. Or 132. Usually a set is an ordered is just a set of items. So if you have a set of coins that you're collecting, they're not necessarily ordered unless you order them yourself. So every time you pull them out the bag and you put them on the table, they come out in a different order, right? Same as stamps. Whatever Collection you've got, they come out in a different order. You can't guarantee the order. And in software engineering, sets are pretty much the same. So be very careful when using sets because the order isn't necessarily guaranteed. Again, caveat, different languages behave differently. So always look these up. If you using them for the first time or you'll get unpredictable results. So those are sets. There's only really one other thing worth mentioning. And these are dictionaries or in some languages, maps. So if you have a book, or even better if you have an actual dictionary with words in it. And you want to see all the words contained under the letter a. What do you do? Well, you flipped the page that starts with a, right. So what you might have is say, I want you to, I'm going to feed you a. And then it's going to spit out all the words that start with a simple enough that's kind of intuitive. In software engineering, we have the same kind of idea behind dictionaries and maps. So what we do is use a special notation of this triangular brackets like, uh, so. And we have on one side a key, on the other side the values. So in the key, in this case, we would have a character, a char, or a string, which represents the a. And on the other side, we would have a string, right? So that would represent a word, one word beginning with a. Now if I wanted to turn this into a dictionary, what I could do is this creates a list, char. And then over here, I would say this is actually a list. So we come back to the list concept of strings, and then we close the outside bracket. So we're going to feed it the letter a. It's going to return us a list of all the words that begin with the letter a. And remember we can expand our list size so we can shove all the a words into that second part into this list of strings. So you've just learned how to use a dictionary to store stuff under a particular value. So another example might be kids born in 1990. So you'll keep a list of all the kids in your school born in 1990. You would have perhaps an int or a date, depends how you sort these things. And then you would have, again. A list of strings like that. So you feed in the date and it would spit out a list of all the kids that were born at that date. So you're getting the idea here, but hind lists and arrays. A list basically stores a whole bunch of things. Oh, and I should mention lists and arrays actually store things in order, right? So if I say access the first part of the array, it will always return the first thing. So that's something I should actually expand on in this little section. So we'll just do an array for now 123. Now if I want to access something in this array, first, let's give it a name, var a equals that, I would say, go to array a and then access one of its members. Let say we want to access the first member one. Now there's a little trick here that I haven't told you. A re-start from member 0. Everything is what they call 0 indexed. So if I want the first array, this is actually at position 0. So that's position 0, that's position one, position two. So if I wanted to access something at position two, I would put two. Now remember, this is accessing the first item, and this is accessing the third item. So these, this slight disparate discrepancy between the numbers, you really need to watch out for. Same thing for loops. If you use a loop to access everything in an array, you'll get two loops eventually, probably in a couple lectures time. So we have, this is how we basically access these values. So the first value and the third value. Now these are always in the same order that you put them into the array or the list in C, you're guaranteed to get those out. And that's in contrast to sets. Same thing applies when you're using dictionaries. If the second half is the list of strings, I went right style again because you can remember it. If the second half is the list of strings, then you're guaranteed to get those strings out in the correct order. So x I will write it out because this is very important. In our dictionary example, we would have a character representing a OB, whatever. And then we have a list of string. So these would always come out in order. So if you put them in alphabetically in order, everything you get out would come out alphabetically. Aardvark and Bill. And that would happen every time. Now, maybe tempting. And I have seen people do this to use a set here because you're like, well it's a word and there are no two words the same. And a set says, I can't put the same thing in the same set. It only has one of each member, but a set isn't ordered. So every time you wanted to show an ordered list of these words, what would your problem B, you'd have to reorder everything. You'd have to do a comparison, and that eats up processing cycles. So for this example, you'd use a list, all right, onto the actual code. Examples. 8. Stamps and Coins - Arrays and Collections: Let's talk about collections of stuff, lists or arrays. Now if you recall, we've already covered variables and variables kind of looks something like this. We have an aim and we assign a value into the variable. But what if we have a bunch of variables that are similar in nature? But there could be a lot of them. What do we do in that case? Well, if we had 20 different ages, we wouldn't want to copy the age variable 20 times and call it something different each time. It'll be handy if we could kind of collect them together in one lump. So that's what arrays do. So in our project, let's right-click New File, and let's call it whatever you want to. I'll just do Arrays dot p, y. And let's first define an array. So let's do an array of colors. Colors is equal to. Now, arrays in most languages are defined using these square brackets in that order. So open and then close. Except in Python, we don't really have arrays, we have lists, technically speaking. But for now, we can call these arrays. It's perfectly fine. What are we going to put in here? Well, let's put the color red. And these are all strings, as you know by now. Lets put in blue and let's put in green. So now we have an array that has three colours in it. And we know there are three because every time we put a camera in that separates out the elements of the array, or denotes that a new element is coming in to that array. Now what would happen if we printed out the colors array? Well, let's save that. Right-click it. Run. There, we have it red, blue, green. I'm just gonna do my usual little trick here of creating some space for us so we can see, oh, running regular grade. Okay, simple enough. What if I need to access something in the array? Well, now we come to the concept of array indexing. All indexing means is the position where the thing is stored in the array. So this is the first position, the second, third, same in every language, except if I type print colors and I open and close the square brackets and I say, I want you to give me the first thing in nasa re, what do you think it's going to print out? So I'll just actually remove this. What do you think it's going to print out here? Well, you will. Instinct says red. So let's save and run it. And it prints out, blew, it prints out the second one. Why is that? Well, the answer is very simple actually, because arrays don't start at the number one. They start at the number 0. Like that. So all I've done here with this hash is to make a comment. That means the Python interpreter Akan knows whatever's in this line with the hash. And the green in. It says it's a comment. It's something that program is used to organize their thoughts and say what items are. Okay? So arrays or lists in pretty much every programming language in existence throughout all of history, even in the Stone Age, started at position 0. So in order to get the first one, we actually have to use the number 0. So if we ran that, now we get red, which is the correct answer. Okay? So this is called technically speaking 0 based indexing, IE we start at 0 and work our way up. This is a very common thing that begins to programming get wrong, okay, so you need to remember that it would be nice if we could tell how big this list or array is. How do we do that? Well, we're going to use Len colors. Now this is Python specific other languages we use something like dot count, something like that. So if we again run this, it tells us we have three items and we're still printing out the first one at position 0. So everyone gets confused at this point, there are three items, but we start at 0. So later on when I teach you about loops and how to access things inside of these arrays. That is quite an important distinction to make, but we'll get onto that in the future for now, let's concentrate on these lists. What if I want to add the color white to this array? While India explain a video when I was drawing stuff on the iPad, I said that arrays, most times you can't add things to them. Except in Python, we don't have arrays, we just have lists and lists. You can add things too. So I can say colors dot append. That means add something to the end of the list. I open and close the brackets. And let's throw in white. Of course we can save that. And then afterwards, let's print the whole array. Run Python. And there we have four. But you'll notice that before that we still have three in the array and the first element is still red. It's because at this point, we're running in order from the top to the bottom. When we print the length here, there are only three elements. Then we add another, then it adds the colors, so that's running from top to bottom. What else do we do with this? Well, we can actually remove things. Colors dot remove, and we can pass it the thing we want to remove. So we can say, if you find anything that says blue, I want you to remove it. And then we can do the same thing again to print the colors, save and run. So we've removed blue from our list of items. We are manipulating the array or modifying the array as far as technically more correct. What if we just want to remove something from the list? Depending on its position? Or again, that's easy. Colors dot pop. Pop means to pop off something from the stack. It's a term that you'll see used in iOS development, in Android developments in quite a few places now. And it's becoming more popular because it's quite descriptive in and of itself. So I'm gonna pop 0, which is the first element. And then of course let's print again. So it's pops the first element which was read completely gone. We can also, what can we do? We can insert things. So I can say colors dot inset, and then I give it an index. So you'll notice when you type the bracket in Visual Studio code, it gives you some hints. So you can always pause at these points and see what it's expecting. The index is the position. So I say at position 0. So right at the beginning, I want you to insert the following magenta. And then of course I'm going to print the colors, copy and paste, save and run. And it's inserted magenta at position 0. So that's the basics of arrays and lists and all these things like append, remove, pop. Inserts are methods or functions that you'll see in many other different languages. So it doesn't really matter that your learning Python, you're actually learning other languages as we go. Because I've noticed a trend over years and years of doing this, that all languages tend to converge on the same set of verbs and nouns to describe things. Because really what is language but an appropriate assignment of letters and sounds to an object. Programming languages are just the same. So when you say something like remove, well that's obvious what it does. You can't really call it anything else, can you? So congratulations, you are learning all the languages at once. Onto the next section. 9. Arrays and Collections - Task: By now, you know about variables, types, and arrays. So got a task that kind of combines these two things together for you. And your task is the following. To create two lists, one with three ages, one with three names, make them the same length. So they both have, let say, three elements in them, three ages, three names. Then I want you to print out the age and name of each index in the list. So I've given you an example here. Print H naught plus name. Note. You can of course add things to prettify it, like the quotes with a space in them. Totally up to you. You can put a comma D, whatever you like. But what I want you to get is primarily there's two lists, three edges, three names, and then print them out to the corresponding line. Good luck. 10. Arrays and Collections Task - Solution: Right, let's get on with the solution. Let's create two lists, one with three edges, one with three names. Let's call this lists something obvious like ages. Let's have thirty three, sixty four, seventy five. Let's give it some names is equal to I knew array. Then. Fred. Grant. Now what's we going to do? We're going to print out the corresponding index in these lists. So let's have print names 0 plus ages 0. And remember I said, we can prettify this a little bit. Let's try that. Let's just try this and see what happens. Here we go, we get an error. Can only concatenate string, not int. So if you recall, we've had this arrow before. We can't use an integer here. So what we can actually do is convert that into a string by putting brackets around it. Now we should be able to run it. And there we have been 33. So let's copy this line. Let's drop it in and we can access element number one. And of course we can do the same again for element number two. Element index to node number two, this would be number three, technically speaking. And now we have all three lined up perfectly for us. Ok? But as we're going to discover throughout this course, software engineering has one basic principle that you should follow. You should stick to like glue. And that is, do not repeat yourself. And what have we done here? Well, this is all very kind of similar, isn't it? We've repeated ourselves many times. We've done the string function many, many times. It would be nice if we kids offload some of this work so that if we need to change our program, we're not going to change it in three places. For example, if I need to change this to that, well now I have to find wherever this is and change it every time. It may not seem that difficult to do now, but later when your programs at tens of thousands of lines long. And that's a simple program. Saving repetitive code or not doing repetitive code is going to save you a whole lot of time and trouble. So trust me on this. So I'm going to show you one little shortcut. Let's create a new variable called spacer equal to that. Save that. And then drops spacer into here. Now we still have these print lines repeated. We'll get onto that eventually. But if we run this code, that space is added in for us. So now you can see the direct advantage of doing this. I can change this to whatever I need to write. I only have to change it in one place. And there's a golden rule in software engineering that if you find yourself changing something, if you find yourself changing one thing in multiple places, then your code isn't structured quite right? It's not to say that you are a terrible engineer if that happens, because it happens to all of us, we can't get it perfect from the start. But that is the goal to strive for, not repeating yourself, only changing things in one spot. So did you get the right answer to this homework? If you did, then comment below, if you didn't, and comment below as to why you didn't and the mistake that you made and what you realized from it. If indeed you realized anything. 11. Special Forces Operators - Explanation: Now let's discuss operators. So we started with variables, a little chunk of information that say holds the number 123. And we have another little chunk of information that holds the number four. Well, these things are pretty useless in and of themselves, just chunks of information. Usually we want to process information and transform it into something that the user appreciates or something the user expects or wants to see, right? So what might we do with two numbers? What is pretty simple? We might add them. So we might have 123 plus four is equal to one to seven. So this little plus section here is called an operator. It is performing an operation between two variables. Pretty obvious, of course, other operators are multiply. But in software engineering terms, this is usually an asterisk character, the star character, because x is a letter, right? We also have minus, we also have plus. I'm sure you're pretty used to all of these. Not only these, we have different kinds of operators, right? So to introduce the next operator, I'm gonna give you a new concept. And this concept is one of Booleans. Booleans simply hold a true or a false. Either something is or it isn't, it's a one or a 0, right? So in the computer language, remember we discussed binary. I think a true is a one and a false is 0. Okay? But we'll just talk about the English language way of doing this as true or false. So another operator we can have is to say, let's say, we say, what I want you to do is I want you to take two variables, and I want you to tell me if one of them is false, right? So we have to variables here. So let's say you're making a piece of software that allows someone to access an online course, much like the one you're watching. Now, what you want to do is say, number one, check this person is logged in and number two, check this person has actually paid for this course. If so, give them access to it. So what you want to do is make sure that whatever operator you choose between these gives you that end result of true, right? You need to check that both are true. So what you could say is, is this one true? Is this one true? If yes, then inform our program both the true or you could use an operator. And the operator in this case would be the symbol ampersand. I've always got trouble as an S, isn't it? I always have trouble during an ampersand and wonder if I can type on this. No, I can't. Anyway, whatever. It's how does it work? It's something like, is it this way round? I think it is. Well, just look on your keyboard. I'll look on my keyboard Actually. I know that I was right. That is correct. Okay. So it's an ampersand. Let's say I've got two random variables and I need an operator between them. What is that operator? Well, in software, this is called an ampersand and we would usually put two of them in there. And, and, and that operator compares those two. And if both are one value, false, it will return false. If both are true, it will return true. If either one is true and the other is false, then it will return false, right? So that's an example of a result of an operation, the ampersand. You can have many, many other operators. You have ores and things like that. I'll just show you one more because I think you get the idea now. So again, we have our two variables. And let's say in this case, what I want to do is compare them. And what I wanted to do is always check to see if either one is true. So let's say you have a weird situation where someone has signed up for your site and could have paid for the course. Or they could have not signed up for your site. And they have paid for the course, or they've signed up for your site and not paid for the course. But you being a generous proprietor of the courses such as myself. You say, hey, if they're logged in but haven't paid, give it to them anyway. If they've paid but haven't logged in, give it to them anyway. So what we do use as an operator in that case is the or. And this is called the pipe symbol. Usually it's somewhere near the one key on your keyboard. But it can also be like on a Mac above the Enter or Return key, or in that vicinity depends what layout you've got. And it's a very long symbol. It's longer than I or longer than one. Okay. That's the pipe symbol. So with this pipe symbol, what that would return is it would, it would return. Let's say. I'm going to introduce a new concept here, but don't worry about it for now. We would say something like if that, so if either this or this are true, then it will automatically return true. Okay? Now, if the first one was true and the second one was false, it would still return true. Because what you've said is, I want you to return either or you're simply saying if either of them is true, return true. Okay? Simple as that. There are many, many more operators. And just to show you here, I've pulled up the Microsoft C-sharp operators. Obviously, this section of the video isn't about C-sharp, but you might see this video in reference to learning about C-sharp, which is the fast language Island. If you scroll down to the bottom of this page, there are tons and tons. So we've got Switch. We've got x dot dot Y, which is a range. Can I select these Think side? There we go. We've got multiplication, we have edition. So if you're trying to do something in soft in your program, whatever that thing is, then what is handy to have is a little cheat sheet or the webpage open of the particular language we're using. Because if you are trying to define, if you are trying to find out if something was true or false in combination with another variable, then there are always, always operators that do that in a very short and succinct way for you. Ok? Now normally and causes you don't really see stuff about operators because it comes as a natural part of learning the language. But I thought I'd actually include it. So you're not stumped when you start to see weird symbols between variables. 12. Special Forces Operators in Python: Let's look at operators in Python. So let's create a new file in our project and call it Operators dot p, y. And what is an operator? Well, it's something that performs an operation on variables. Not necessarily just variables, but various other things as well. So let's create two variables. Let's say we have a word which is my, with a space in it. What else can we have? Let's have. Next word is equal to laptop. Ok, now, you've seen this before. We're going to print these out and we're gonna join them up. So word plus next word. What you've just typed, there is an operator. This plus in this case isn't a math operator, but it's called a concatenation operator. So I'll just spell that for you. Concatenate Nation. The verb is concatenate. To concatenate simply means to join two things together. And in this case we're joining two words together. Of course we can run that in our terminal and it will come out as my laptop. I've also discovered rather late in this that if you just run Python in terminal, it will auto save the file for you before it does it. So I don't actually have to press Control S. Ok. So that's concatenation. That is an operator, the plus. Obviously you can't have minus onwards because how do you subtract a word from a word? I know we could probably do it in plain English language, but in programming that doesn't really work as a concept. So what are we going to have now let's have a is equal to an integer, and b is equal to another integer, a 100, for example. So let's run through the other operators we could do with numbers. And these will be all of the operators that you are familiar with, for example, a plus b. And now we can copy all of that. And I'm going to paste in a couple more times. We can have a minus b. We can have a times b, which is the asterisk character and programming. That's the same across all languages. And we can have a divided by b. So what are we going to do? Let's right click and run this. And there we have the answers to our various maths questions. Now there are two more I'd like to show you here. So let's paste this again. This one is, I believe it's called the modulus. So if we run that, we get an answer of eight. So what that does is divide one by the other and give you only the remainder. So eight divided by a 100 is 0 because it doesn't go into, or a 100 doesn't go into eight. More than 0 times is 0, but the remainder you have is eight. There are times when you use that, not very often in my experience, but they can be times. And there's another one, which is I forget the name of it right now, but it's the double star, the double asterisk. And what we have here is to the power of. Eight to the power of a 100. Is this really, really, really long number? Ok, that's fairly straightforward. Now I'm going to show you some of the things that can perhaps go wrong here. So let's get a bit more programming and say on-site equals a plus b. Ok, so now we have a basic answer. And what we want to do is go, what kind of variable is the answer? So a here is an integer and b is an integer. So let's see what happens when we add these and we ask it for the type. So let's right click and run. There we go. It's added them up and we now have an integer as the answer. What happens if I do something like this? Well, first I'm just going to print the answer. The answer is anyway. And then we're going to have absolutely my notes here. There we go. So I don't want to mess this up. C equals 8.1 because it's kind of an obscure problem I'm going to show you, but it can affect you. It fairly often if you're doing some kind of calculation app. So we're going to print c divided by b. Okay? And what are we gonna do? Let's make yeah, c divided by b, so it's going to be 8.1 divided by a 100. Now, if I run this in a calculator, the answer that you should know anyway, divided by a 100 is 0.081. You know, it's a nice three decimal place number. Fixed. Watch what happens when I print this answer? Nothing happens. We're perfectly fine, right? You know, I did this on a different computer and it gave me a different answer, some suspicious. Let's try one further thing. Let's have dy equals 10. And then let's print c over d. And again, let's run that. There we go. That's more like what I was after, right? So here we had a float because there's a decimal, this is going to get costs into a float type. So the answer it gave for that was 0.081. And who knows why it got that right? I think it shouldn't or I'm just getting confused as to what I remember. But then I said, hey, let's create the number ten or actually let's create the number 100. Let's run that. Yes, that works fine. Hang on. Let's leave it at ten for now. So then I said ten, That's creates another float. And then I said 8.1 divided by 10 should be 0.81 with no recurring digits. Look what we get down here. It's totally in correct, isn't it? Why has it skipped off? What what number is that? Like? 0.01. Why is it skip that off? Well, that's something to do with the accuracy of the types in Python. So a float divided by float, It's gonna give you a very slight error if it's not an exact figure. Although even if it isn't exact, forget as you've seen here, you get a slight error. So when you're using operators, it's always a good idea to run some pre checks if your app is very important in terms of keeping track of accurate numbers. So you can imagine, like we've done in previous exercises, if this was a financial app and you got these numbers wrong, there are actually very big consequences to not getting the numbers right. Least of which is your users will abandon the rat because it basically gives them wrong answers. Okay, so I've given you a couple of warnings. But mostly in this section, I've shown you the math operators and that you've already been using an operator to concatenate words or strings together. Okay, there are many, many other operators, and we're going to cover a few of them as we progress through this course. But if you search for any programming language and then the word operators, you will get a full list wherever you need them. But it pretty much only need these. And the ones who are going to show you in the next couple of lessons. 13. Operators Tasks - One is Very Hard: Here's the task or two tasks that I want you to fulfill for this particular section. First of all, I've given you three numbers, basic floating point numbers first, second, third, 1 is to one is 21, is eight. I could also set these as integers if I wished, but obviously, this one can't be an integer. You can have them as integers or floats. The first two that is, as you see fit. What I want you to do is to divide this by this and then multiply that answer by this. So there it is just not there. Divide the second by first, then multiply the answer by the third. Now if you're not familiar or too familiar with math, so you don't remember it. There is a rule that's always applied called BAD mass, which is brackets, orders, division, multiplication, addition, subtraction. So your maths operations always happened in that order. It's just a universal maths rule that's not really relevant for this task. I just thought an extra bit of information can't head. So that's the first part, and that is probably fairly simple, right? The second part of this is that the number that it prints out is actually going to look something a little like this down at the bottom. But we have no 9's repeating nines. We only have a 0.001. I want you to diagnose exactly where the problem is, not to solve it, just where the problem is going wrong. That is a crucial skill that developers need to have, is to be able to narrow down the problem to a single line of code, a single function call or a single variable. So they can address that particular problem all too often. And this is another piece of great life advice. I have gone looking for a problem in my programs. I think I've found it, I've changed something, but all I've done because I haven't dug far enough is layer another problem or a plaster on top of a much deeper problem. And that plastic can't hold the app together. So I start to get problems in other places sometimes exacerbated by the fact that I put a plaster on the wrong place. So what I'm trying to get you to do here is to think critically about your own application and narrow down where to find these particular problems. So, good luck with those two tasks. 14. Operators Tasks in Python - Solutions: So how did you find it was a difficult Was it easy? I'm guessing the first part was fairly easy, but the second part was probably fairly difficult if you're new to all of this. So first let's actually, let's create an answer which is equal to what was it? Second divided by first, and then multiplied by the third. So what I want to do here is open and closed some brackets to ensure that that operation happens first. And then I'm going to multiply. So what am I going to multiply it by a third? So now we have an answer. We can actually print that out. It might have to change it to a string, but let's find out. No, we don't, because it's just a single one. So Python can guess that this needs to be a string. And then we have the answer that I was referring to. Let me just put some space into here. So that answer is incorrect, right? Because if you did this in a calculator, you'd come out with 80.01, not 0.0099999. So there's a rounding error somewhere because of the types that are used. Remember the computer doesn't want to store an infinite number, so it doesn't, it just rounds it down. And floating point numbers in 64 bit, they go, it's like a 100 and something powers. That means basically that means really, really long. We are using Python 32-bit here. That means the numbers are actually somewhat smaller, probably half that size, which is still very, very large. And it shouldn't be a constraint to how we run, right, how we write our Python programs. So the second part of this was to narrow down the source of this era. We're not trying to fix it, which sort of narrow it down to see where the issue is. So first of all, what I would do is I've removed this third and make sure this first operation runs correctly. So that's 10. And of course 20 divided by two is ten, except this is giving us a float and an integer, as you'll notice here. So it is converted them to a float to do the division calculation. That might be an issue, but it doesn't look like it. What I'm then going to do is I'm going to simply print third. And let's see if that comes out as normal. Yes, it does. Okay. So the issue isn't with the first calculation, the issues probably with the second calculation. So we can test that by going next. I'll answer equals answer times third. And then I'm going to click that run Python. We haven't actually printed it halfway. Whoops, I'm going to cut this and paste it below. And then I'm going to print the next answer. Let's make some space. You can see what's going on here. Okay? So the problem lies in this multiplication here. What happens if I just put a number ten here? Instead of that answer from before, let's click that. We still get the same issue. So we've ruled out the fact of this calculation causing the problem. Because if we put applying ten in, that still causes the same issue. So a pretty safe with this answer. The issue is here in the operator of multiplication times a third, and then we print the next answer. So as a software developer, how often do you run into this? Well, I don't particularly make financial apps. I make more consumer apps, you know, music players, stuff like that. If you're making calculator, this is something you need to take into account. What I would say to you is to perhaps go find what are called libraries. Libraries do lots of functionality for you in a particular language or framework you're using. And the library will have corrected many of these problems in very clever ways. So the problems no longer exist. So if I was gonna make a Python calculator, I would actually try and find a library first to see if someone else has solved the problem. Usually, libraries are free, but please do give the office credit if you publish your code or your app because they deserve it. Software engineers aren't cheap and they give their time away for these libraries for free. So that would be my solution to that. Otherwise. What else could you do for this? You might multiply this to get rid of the decimal point, to make it 8,001, and then divide it again. But I think you'd be stuck with the same errors. And that's just adding another layer of complexity. And you definitely probably don't want to do that. Don't add layers of complexity. Unnecessarily should be a last resort. So to be honest, I don't know what the answer is for this particular one. I don't I think what you could do is, let's say you do come up with an answer. You would run a test suite around this to make sure it's still spitting out sensible values no matter what you feed into the program. But that's a much more advanced topic for a totally different day. For now. I'm just happy if you got to the point where you discovered it was this multiplication that was causing the bug. 15. Strawberry to Banana Conversion Between Types - Explanation: We've discussed the variables and we discussed that variables have types. And the reason they have types is so that they're more memory efficient and that we know how to handle that particular kind of variable within our program. So I'll just give you a little catch up there, which is to say, let's have a number 123, which would be of type integer. Or we have the name grant, which is of course of type string. Okay? You know the difference between these types and you know, intuitively that they're not the same, right? So we have an integer, we have a string. They are not actually the same thing because they're stored differently. If you have an egg box, you can't store all your Legos in it very neatly anyway, but you can store eggs perfectly. Ok. Now the problem comes, and the problem in this case mostly comes when we get stuff from a server. So here we have the great big internet. And here we have a server on one side. And on the other side, let's say we have your app, mobile app, a Web app. It doesn't matter. Most apps these days we'll get some data from a server. What does the server pass over in terms of data? When it passes over specialized formats, right? So I'm telling you a lot more than you need to know at this point, but it's going to lead into why we may want to convert types, okay? So what does it pass over? Well, there's some formats. There's XML, markup language, there's JSON. And you've probably seen these without knowing that you've seen them. If you've dabbled in software engineering before. Programming even XML or JSON. Xml is on the way out, is only in legacy stuff. Everyone uses JSON these days because it is pretty simple to understand. The Apple uses XML for their podcast feeds, just FYI. Anyway, JSON looks something like this. We have a little brackets. We have the identifier of the thing that we're sending. So name is grounded, and then we might have ID 123, and then we close those squiggly brackets. Pretty straightforward, right? What do you notice? Well, the first thing that you should notice is that grant is a string and one to three is a number or an integer. In this case. Of course one, T3 could be any kind of number. It doesn't matter. The point is they're different types. Now when your app picks these and you want to display, let say the ID to the end user. So you will have the ID here of 123. You are going to feed that ID into something like a text view on the screen. A text view in the user settings, whatever it is. But integers aren't compatible with what the TextView expects. The TextView expects a string because it is showing text, it doesn't show integers. Now in reality, most software has figured this out and it kind of lets you do this, lets you get away with it. Because it automatically convert the integer for you. But let's say we've gone old school and we have to convert the integer ourselves. What do we do? Well, we grab this integer and we do something to it. So here's our integer. It'll be called a variable, so it will be called something like user ID. And then we would do some stuff that's built into the language, which looks kind of like this, but not always dot two string, open and close brackets. Now we haven't covered functions or methods yet, but that's all that represents its functions or methods. Don't worry about it for now. But basically, this little sequence will convert the user id, which is the 123 here. It'll convert that to a string. And you might say, well, that's fine, that's well enough. I'm sure it can do that. And he writes it can because most things have a string representations. So when you convert, the computer just says they go done. Okay? There's a problem. There's always a problem because now you're becoming an engineer. So your life will be full of problems from this day forward. That problem is what happens if someone sends over a bit of JSON that says ID and they make it into a string. So this is either the guy making the server or it's you making the server. And you've sent the ID as a string. That's fine, right? But your app expects the ID in a integer. So any calculations you tried to do will now be a string, for example, times an integer. If you're using the ID for something and you're going to have trouble. So what you have to do is make sure that you can convert this integer, or rather this string. It's my fault, this string into an integer. And just like the string method, there are various ways in the various languages of doing it. But we would say the id variable dot two, int, I, open and close brackets. This is probably C-sharp for memory, whatever, it doesn't matter which one is actually. Okay. Remember I said two string works fine because everything pretty much can go to a string, but not ever, they couldn't go to a number. So what if the ID was changed and had a little a on it? And then we try and run this ID to integer. Well, what's going to happen? Clearly, you can't change an a to a number Kenya, which means this is going to blow up, right? It's not gonna work anymore, and that will crash your entire program. Ok? So what we have to do is be very careful when we're converting stuff between each other. Usually numbers to other kinds of numbers is generally alright. If you're going from a most simple objects to a more complex type of object, then you'll be okay. So an integer to a string. An integer is simpler in computer science terms than a string, right? So that's easy to convert. But if you go from complex, which is a string over to an integer, then that doesn't work. If you get a spanner in the works like this little a. So that covers the basics of conversion. And I've just told you the main reason why you would ever want to convert anything, and usually it's server data. Now, before I go in this particular lesson, I just want to give you a big word of warning. I'm going to save you. Yes. And I'm not kidding. Years of your life before you make an app of any kind on the web, JavaScript, whatever. Well, JavaScript doesn't technically apply, will leave at, say Katlyn Swift, C-sharp, whatever. Makes sure you get your types correct, right? So if you're creating something that has an integer, which is used for ID and you have string for username. Just think ahead in your app and say, is there any place where I'm likely to want to change this to a string. If I'm storing this Id, sometimes I can't store an integer. Well, you can store an integer everywhere these days. But let's say it's a more complicated type and you need to store it somewhere. Well, what happens if you can't store it? The default reflex when you start learning to code is to convert things. So you would say, oh, change my integer to something, right? And then when you get the integer back from storage, you'd say, Hey, could you do the integer back to int? And you could do that, and that could work. But sometimes you can lose things in the conversion process. So I'll give you one example and then it will be over, I promise. And then we'll get onto exercises on how we convert between things and how we catch those errors that could happen. So, a dreadful mistake lots of people make, right? We have an integer which is a whole number, 4-5-6. Simple enough, right? Actually we don't have an integer. We have, let's say a float, 4-5-6, 0.3 seems simple enough. And you go, well, that doesn't fit in how I store stuff. I'll just change it to an integer. So people will change that to an integer. Once you do that. In most cases, in most languages, it goes into 4-5-6. So the three gets dropped off the end. Then let's say you retrieve that integer, right? You say 4-5-6, dots to float. And you know what, that's going to come out as 456 dot 0 because the three was a piece of information that you lost. So when we're converting stuff, you have to be ultra careful of what you converting from two. And if you're going to convert back what the consequences and repercussions of those R. So whatever language you're using, you should jump on the web. The tutorial pages for that language is always an official website for language. And look at the types, information, integers, floats, strings, and whatever it is. Make sure you're familiar with that so you don't run into trouble. Okay, so that's my word of warnings here. That's gonna save you years, years of debugging your code. 16. Strawberry to Banana - Conversions in Python: Let's try to convert some stuff. So let's create a new file in our projects, call it something like conversions dot PY. And now let's create a couple of variables. I'm just going to print some things look neat entirely for us. You don't have to do this bit totally up to you. I'm gonna create a variable, which is the name. I'm going to create another variable, age 37. So we've done stuff like this before. You should be used to it now. Height of 1.9 and then is male equal to true, and this is capital T. So if you come from a different language, Python uses capital t, capital F for true and false. Now of course we can see what types these were. So print the type of name. And if we run this, we have a string. Exactly what you expect. Age, I'm sure you can guess what this will be. An integer. Height, its decimal before I click it, what do you think it is? It's a float and is male is a Boolean or a bool for short. Okay, so that's pretty straightforward. You should understand that right now. I'd like to introduce you to another technical word, implicit. These variables all have implicit types. So we've let the compiler or Python system figure out what type of variables they are. They are implicit. Now if I gave something a type by converting it, that would be explicit. I'm saying no, no, I don't want an integer, i want to string. And so i would force it to change. And that is explicit conversion. Okay, so we can do that by coming over here and typing String age. Of course, this is just going to give us 37 as a CMS. But if I did something like this, so H equals 37. But if I did age string 37, and then I asked it for the type. Obviously, this is not an integer, right? This is going to be a String as our command line confirms. So what we've just done there is we've changed the number 37 from an integer into a string. We have converted the type. Now type conversion. You have to be quite careful with it. So what I'm gonna do is just undo some of this. And I'm going to start putting things in kind of an order here. So I'm not actually sure where this book goes. But let's see where the grant goes probably at the end. Right. If I try to change is mail into an integer, do you think that could happen true or false? Well, what you may not know is that true is a one and false is 0. So yes, you can change it to an integer. Can I change an integer into a float? Yes, it's just that float 0 or some weird era as we've seen before. Can I change any of these three into a string? Well, again, the answer is simple. Yes. But can I change string into a float? Well, I can't change this string into a float. Watch this. Float. My name. Run. There we go. Could not convert string to float grant because that's not a number, is it? If if my name was 1.9, like Elon Musk's kid. No problem. I can change that to a float. Okay, so you gotta be careful with the order of conversion generally going from the top down. Perfectly fine. Going this way. Be very careful. Okay, we're gonna show you another little thing that could cause an issue. So let's do a new line. And let's change my name back. Let's float whatever, 37, let's print. Now what do I want to? I want to integer a phi, the height. Now, as a person, if I said to you, take that height of 1.9 and change it into a whole number, your immediate reaction is to what? Give it a two. You would say this is to watch what happens when we do it in software. We get one. Because when you convert from a higher-order number, two lower order one, it just simply drops that off. It doesn't do any conversions for you or any calculations. It just says, Get rid of what's after the decimal. So again, you gotta be very, very careful. Now, let's see what happens if we print the conversion of the Boolean to the end. So int of is male. And we have a one. If we change this to false, we get a 0. Okay? Well, I'm, I'm definitely a male. So we'll put a back to true and save all of them. Okay, so that's just a way of converting between stuff. Now, I believe I mentioned this probably in the very first lesson. Be very, very careful when you do this. Because as you've seen, things get chopped off the end. Conversions are something you should avoid, like the plague because of those areas. So if you, if you control how data comes out of the server, make sure you fit the most appropriate type to that data before you send it to your end application like your client, your app, whatever it is. So if it's a whole number and it's guaranteed to always be a whole number, then by all means, make it an integer. But it has even the slightest chance that that is going to turn into a decimal number or a much larger number, make it a float. It takes a bit of extra memory, but it's worth it in the long run not to have to go through all this conversion. Pfaff. 17. Conversions in Python - Task: Let's tap into the power of messing things up. I'm going to give you a real-world example at this point because you're getting more advanced as we proceed through this, you can make an application that will calculate a tax bill for a company, right? Or maybe a freelancer, whatever it is. I'm gonna give you the following bits of information. You have an income of a $100, ok, and you send this information to your accountant. You have expenses of Flickr, my notes here, 9550. Okay. The tax rate is 20% or 0.2. I want you to calculate what my profit before tax is. And the profit after tax, as well as tax paid. Right? So this is going to be a basic sums. This is the first part of your task. So let me put this in here. Part one of task, calculate profits and taxes. And taxes. So that's the first part of your task. Calculate these three variables. The next part of your task is to do the following. After expenses, I wanted to change expenses into an integer, change expenses variable to an integer and repeated all, repeat the whole calculation. Okay? And then we're going to come back and we're gonna discuss what went wrong, what went right, and whether you'd be fired as the CEO of this company or not. Good luck. 18. Conversion Tasks in Python - Solution: How did you find it? Probably fairly difficult. We haven't done this kind of calculation before. Well, the first thing we need to do is the profit before tax. So that is simply income minus expenses. Pretty straight forward. And then I'm going to print that out, the profit before tax. And i'm going to perhaps add a little string, profit before tax. Plus this, which we need to convert it into a string. Okay, so we've got our basic template now. We can copy that. Put it below here, and put it below here. Just we have a nice looking piece of software. Then we have tax paid for this one equals string tax paid. So how do we calculate the tax paid? Well, we need the profit before tax times the tax rate. That will end up being the tax paid. Well, I've got an error here is probably due to this down at the bottom. Let me just double check out there's a bracket missing on that one. Undefined variable tax paid. If you save it, sometimes it goes away, not in this case. Let's try that again. Tax. It's just not there. Okay. Something weird happening in my program has tried to type that again. Let's do it up here. Tax paid equals that you've worked out yet. And it's probably because of this line. If I comment that out, still doesn't work. So I was trying to set up a problem for you guys to solve, but instead I've set up my own problem to solve. Unexpected token. Why, why did that bracket? There we go. Don't forget your brackets, ladies and gentlemen, don't forget to close them. That's always the answer to these. Always. So tax paid is the profit times the tax rate. So 20% of whatever's left. The government demands it from me. And then what's the profit after tax? Well, we say the profit before tax minus tax paid. And then we just change this to after-tax, profit after tax. Okay, so I can right-click that and run all of that in the terminal. So the profit before tax for $1.50, the tax paid is $0.90 and the profit after tax is $3.60, right? Everything is fine. Second part, change the expenses variable to an integer and then repeat this. So what I'm gonna do is just copy it. I know I said we shouldn't repeat things, but for the purposes of tutorials, I think it's good because I'm going to publish this. So you guys can see all of this in action, instead of changing stuff and making things overly complicated. So variables are the same except with expenses. We are going to say expenses is equal to integer of itself. So this is going to take the current expenses ten into an integer and then put it into the expenses box. Okay? Now, we can do this in Python because the variable can change its type. Other languages that's not common at all, you'll get an error. So you'd actually have to call this something like new expenses. Okay? In fact, we will leave it at that for now. So it's not overly confusing. I actually want to give you guys the tools you need to use any language and doing stuff like this will help you with that process. Ok, so actually I'm going to call this new income new expenses, because remember we already have these variables up here. New expenses int, and while it's not a new tax rate, In fact, the tax rate stays the same. So we can remove that. And we'll actually, we don't need any of this. This is what you realize as you're coding. You realize you've made a really silly mistake and say you can just delete stuff. The only variable we need is that new expenses. So all we have to do here is changed new expenses int. And that's pretty much it, right? We're just changing one variable. Watch what happens? So before we had those three values, but now is saying, oh, we've got more profit. So we're going to over pay the tax. And we've got more profit after tax. That may seem like a good thing apart from the overpayment of tax, I believe you have a moral duty to starve the government out of its position. Anyway, my politics aside, this may look good, but if you're running a company next year, if the figures are right, it'll look like you failed when actually you stayed on track. So that could be an error. And if you were the CEO of this company, you've overpaid tax, right? Some countries fine you for overpaying tax. Do you find your friends if they overpay debts to you? I know I wouldn't I'd encourage more of it. Anyway, if you were the CEO of a company and you've got things this fundamental incorrect, then you'd be fired and they bring in the next guy. So that's the power of conversions. And that's why you have to be really, really careful with converting your types. I don't admire the software developers at accountancy places like sage and what have you because they are going to have these problems in spades where they lose a single penny, a single cent. And all the calculations are wrong because of rounding errors or conversion errors. Anyway, I hope you've learned something onto the next one. 19. Mine is Bigger than Yours Comparisons - Explanation: Comparison operators are a subsection of operators. Sometimes in your code, you'll have a bunch of variables and you'll want to actually compare them to each other. Now where would this be useful? Let say a list of tickets and you want the earliest ticket first. So you want to show that to the user. As a user, that's kind of what you expect is the most relevant thing at the top. And usually you need to compare items. In order to do that, you compare items to sort a list, okay? So comparison operators are very important and you are going to use them. So, so often app probably every few lines of code, definitely every page of code you'll be using them. So let's say you have a variable x, okay? Actually let's not make it x, let's make it a variable date. Now there's a special kind of date called a Unix date, which is the number of seconds since midnight, January first 1970 until the current date. So your date here could be something like 1239678 for that could be totally wrong, but it's something along those lines. Okay, and then you have a second object. So this is date number one. And then you have date number two is equal to 12396783. It's literally 1 second sooner than the above date. Well, how do we compare these two items? Well, the secret is what you've already covered. Probably when you were like six or ten or whatever age they teach kids these days. You said something like I'm just going to name the short D1, D2. So if D1 is, you guessed it greater than D2, then this is going to be true, right? If d1 is less than d2, then obviously this will turn out to be false. And that's the basics of comparison. Greater than or less than. Okay, there's a couple more. So if I said d1 less than d2, and this came out as true. That means that date one is less than T2, which means it's the earlier date, right? I know it's not actually that in our example, but if we were writing this and it came out is true, then we would know, and this is the basis of sorting lists by values. Okay? Sorting lists is something you'll do fairly often. In fact, you do it so often that modern languages actually have it built into them that you can sort them pretty quickly and easily. So what are the operators do we have? Or condition conditional? What are the comparison as the word? Well, sometimes you want to check if they're equals. What if we had a bunch of tickets for the same day and he wants to group them. And the way we grouped them is to say. If there were bought at the same time, say let's just say these are purchase dates. If they were bought at the same time, then grouped them into the same folder. So we would say here, date one, date two, and the magic operator is equals, equals. So 2x equals means compare these to a single equals means put D2 into the variable of d1. So nevertheless, those up, never mix them up. We want a double equals to compare. And if they are the same, then we would have some code over here saying, put these in the same folder. Straightforward. We can also do kind of the negative comparison of this. So I could say D1, D2, and I can say not, which is exclamation equals. So exclamation means not if the opposite, This says d1 is not equal to d T, right? Finally, come back to our little d1, d2. We can also mix in the.equals with the less than or equals, or D1 greater than or equals d2. Is that pretty obvious? What that is? In the first case, d1 is less than or exactly equal to d2. In the second case, d1 is greater than or exactly equal to d t2. And there's some things to be careful of here, right? And it's kind of language specific. So it comes with experience. And I'll just give you one example of the pitfall because I think it's enough to illustrate how careful you should be with these. Javascript is notorious for what I'm about to show you, but all languages kind of have this problem. Let say I have a number 123, and over here I have a number 123 and I compare them. Sometimes your answer comes out as false. Why, why is the come out as false? Well, if your first one is an integer and the next one is a float, what the computer is actually saying is 123123, something like that, that may not be exactly true. So now you look at this and the computer says, These aren't actually the same thing. Even though we, as the artificially intelligent species on this planet, know that, yes, they are actually the same thing. The computer will report a false. But then some languages will say, hey, that's true. So that's big pitfall. When you learn multiple languages, these are things you have to watch out for. So every time you are starting to code in a new language, you should check these things as you're going through your code. It's a bit slow at first, but it pays dividends in the end. Ok, now, one final pitfall related to this, one, t3 equals, equals one T3. String integer. Some languages will say these are the same and it will be true. Others will say, is a totally not the same. And probably others will say, you can't compare these because it's like apples to oranges. You can't compare these two. Stop being an idiot is what they'll say. Okay, so that's again, something you have to watch out for. But let's crack on with some comparison exercises. 20. Mine is Bigger than Yours If Else Comparisons in Python: Let's look at how we compare things in Python or in any language in general. So let's create a new file and call it something like comparisons to PY. And let's start out by having two basic numbers. A is equal to eight and b is equal to ten. And what if we wanted to compare these? Well, first of all, let's think about when we might compare things. Let's say you have the most common feature these days in apps, which is a scrolling list of items. How can you tell if the item you want to put in the list is the same or different to the previous or next one? Well, you'd have to perform some kind of comparison. And usually you would do that comparison with two variables, which should be called something like ID underscore ID as just kind of the convention we've come up with over the decades as developers of, of how we identify things using the identifier, which is ID for short. So a and B could represent a couple of ideas. Or a and B could represent the ages of kids in your class. And let's say you want to sort a list of ages of kids in the class by their ages going from top to bottom or from the youngest to oldest, depends what you wanna do. So comparisons, strangely enough, as something we do very, very often in software. And the magic word, you need four comparisons is if. And so what you're going to feed if is a statement. And it's going to evaluate the statement and say, well, if it's true, I'm going to do this. If it's not true, it won't do anything. Okay? So if b is greater than a, so you probably remember this symbol from school. The Greater than, if B can eat a I think is how most teachers describe it, then we can do something. So in Python, the syntax is to put this colon. And when you press Enter, it's going to put a tab spacing, which is that highlighted area. It'll do it automatically. If it doesn't do it, your code's probably wrong, or you can press Tab and it will tap you in. And this is how we make our code readable. So we know in this statement if what gets executed below it. So we're going to print something. What are we gonna print? Let's just say b is bigger than a. Now if I right-click and I run this, there we have it. B is bigger than a. And I'm gonna do my usual trick, which is to put these prints spaces in here. Not prompt, but print. Okay, everything runs fine. Yep, B is bigger than a. Now, what if we discover that B is not bigger than a? Well, we can give it another function. We can say e l i f, f, L, F. That is short for else if, okay. So else if. Is saying, hey, if you don't get past this, then what we're gonna do is go into this line. And if everything matches in this line, then we are going to perform that. So we're gonna say a is greater than b, or if you want to make it more readable, b is less than a k. So when you're writing this stuff out, it's actually a top tip to keep the order of your variables like that and just change the sign because I think this is much more readable than a is greater than b. If you start switching stuff around, it can get confusing. So let's leave it as that. Let's copy this print line. Dump it in here. And let's put a is bigger than B. Right-click run. So obviously at this point we're still going into this bit because B is not less than a, this never gets cold, right? So we're doing a comparison. Technically the comparison operator is this less than, greater than. There are some others we're going to get into. I'm also introducing a concept of if, which is conditionals. So a conditionals if something, then do this. It's as a condition before you're allowed to execute the code. It's kind of difficult to separate comparisons and conditionals because they rely on each other in most ways. Hence, why I'm doing them all in the same lesson, which is a rule I wouldn't normally break, but for this kind of half too, for everything to make sense. So what if none of these are true? Well, we can have a general statement. That's else. Now else doesn't take any statement inside it. It doesn't need it. Because it says if you haven't got this and you haven't got that, then I'm going to do this as a last resort. So we could have print. They are. And can you guess what they are? Well, if it's not bigger and it's not smaller, then it must be the same. They are the same. So save that. Let's make both of these into ten. Let's right-click and run. And there they are, they are the same. Now what happens again, if I mess with the types? Change that to a string. It says, I can't compare integers and strings, which is fair enough. Some languages you can actually do that. They're smart enough to do that comparison, but they can be bugs around doing that, so I would definitely recommend against it. And again, the previous lesson when we talked about converting stuff, remember you lose some accuracy in numbers. If you convert from, say, a float to an integer. So again, these comparisons might be a little off. And the reason why is that conversion inaccuracy, right? So what else are we gonna do here? Let's have an else. Lf. So else-if and you'll notice we can stack the Else. If so, we can have more than one. We can have infinite if we like. Although you'll never finish writing it because it's infinite. Else if b is equal to a, you will notice that I have put two equals signs. When you put two signs, that is the comparison operator, right? Remember the variable operator is this equals or the variable assignment, IE, we're putting ten into the variable of a, but when you have double equals, all it does is compare them. So if a equals, there'll be the same. Let's right-click and run that. And they are indeed the same. So you will also notice we don't need an else statement because we actually covered every possibility here. Okay, there are a couple more possibilities that I want to show you, but I'm going to leave those as they are. And let's have C equals nine, d equals nine. So we're going to leave the equals one because we've done that. If c is less than or equal to d, then we will print c is less than or equal to d. And if we run that, we get what we expect. So we can combine the less than, greater than or equals, less than or greater than width equals to do a different kind of comparison to say, if I have a number, if the other number is that I'm comparing it to, is the same or less than print this out or do whatever you're going to do. And of course, LFO that's in the wrong section. Then we go l, f, c is less than D prints. I'll just do shorthand. Less than, okay? No, it should be greater than my battle. Because this one covers less than. Now. Sometimes people make a mistake here. They'll do greater than or equals because it looks the same as this. But now both of these can fire. So when these numbers above nine, this is true and this is true. But if statements only cover the first one, it comes across as true. Okay, so if we ran this, we would still get only the first line executed. Even though this is true, it's not executed because it's finished assessing it. Okay, let me look at my notes here one more. Now, what if c is not equal to d and we want that condition, or we put exclamation equals and then we type whatever. So if I change this to 9.1, I right-click and run it. We get NOT equal because c is not equal to d. Anywhere you look in software, the exclamation is used as not, it's the opposite. And so we now come to, What if we have a whole bunch of variables that we need to compare? So I'm going to start again. I'm going to override these variables. A equals one, B equals one, C equals two, d equals three. What if I wanted to compare a and B? I also want to compare c and d. If both of those are equal, then I want to do something. So we can start to stack these. If a equals b and c equals d, then print whatever all equal. So this is going to look at this. If that's true, it'll say, OK, let's do this. If that's true, then it prints them all. If that's false, it stops there and stops executing. If that's false, again, it stops there and doesn't execute that. So this all equal should not play. Yeah, we've only got the old stuff there. This doesn't do it. But if I change this d 22 and we run that, we get the o equal. The same thing of course, can be applied to the not equals using the exclamation. And you can of course have any combination of these. The final thing. So we say all not equal here. The final thing would be to say if a equals b or c equals d prints one set is equal. Ok, so if I change this d backed with three, now a and B are clearly equals c and d. And so this shouldn't call, but this should call because we said either or using B or special word. They're not equal. One set is equal. Not equal actually comes from up here. You can ignore that for now. So one set is equal is the only condition that satisfied in this. Of course, I'm not going to do this now, but you can cover all of these with the LF And with the else's, et cetera, et cetera. And of course we're gonna do a little bit of that in the task I'm about to set U. 21. Comparisons If Else in Python - Task: Let's have a slight change of pace here. As we get further and further into these courses, I like to challenge you more and more. So what we've done at the top of our program is we've just dealt with integers, maybe a float here in there. What we're gonna do now is turn this comparison to strings, IE words. So here's your task. Create a program that consists of four separate string variables and assign random names to those, but make two of those the same name, so the same string case and everything. Now I want you to compare all of the strings to the first one and then print out statements letting the end user know if there are any that are the same and which ones they are. Now being a string. I've put a little guidance in here. You obviously can't use less than or greater than symbols. You can only use equals, equals or not equals k. So that's your task. Good luck, and I'll see you in the next one. 22. Comparisons If Else in Python Task - Solution: So how did you find that task? Well, surprisingly, what sounds simple at the beginning can actually be quite complex if you try to be too clever about it. And I'll show you what I mean in a little bit. But festive call, I'm going to create all of my strings, like is. So string two. You'd never actually call your strings these in real life, this is just tutorial language. So it makes it easier for you guys to understand what's going on. You would never ever call it string for or string one for that matter, or string. That's a no-no. You'd give it a much more descriptive name of what it does. Nano See, that's a good day, nancy, right? So now we have to compare these and tell the user if one is the same or not. So if string one is equal to string two, then we are going to print something. And you know what if you only have one line of code in your if statement, you can actually leave that print on. Oh, you can leave that next bit of code on the same line. You can't, if you have more than one line of code is just a way of compressing it down. So we can say to our end-user, string 12 are the same, k. And then I can copy all of that. And down here I can just type EL paste if string one equals string three. And you get the idea here. El string for others saying, what's the other condition? Nothing's the same. So we're going to have a general catch all statement which is print. None are the same. Okay, let's go ahead and run that. String 12 are the same. Okay? Now if I run ground there and I put NCA or Nicea, why not? String 14 are the same, right? So we just ran a comparison through all of these. Can we shorten this down? Well, yes and no, because it depends on the next step of the process. So what I would do is I could say if string one is equal to string two, or string one is equal to string three, you get the idea. Or string one is equal to string. For print. A string one is equal to another. So you see the problem here is we can't identify which one it is equal to because all we know is that one of these has fired with the oars. Okay? So if you're writing a piece of software and you want to see if something is the same or not. As long as you don't need which particular one it's the same as. Then you can write your code like this second example. And it looks much neater. Any takes two lines, including the print or is this, even by putting prints on the same line, takes a lot of space. If you loaded it all like this. Look how, look at the difference in space that these take. And let me just check. They run. They got it does run. But I mean, the lesson I'm trying to teach you here is this takes eight lines. This takes two lines. Always think about if you need access to the variable afterwards. Okay, that's it for that one. Of course. If you want to go off and do something on your own, you can try and figure out how to make all of this work in the same way. Using the not equals, sign up, see if you want to take on that extra task. I won't cover that here. So we'll move on to the next lesson. 23. A Merry Go Round - Loops - Explanation: Let's talk about loops going round and round and round as the POC Life song says, By blur, the joggers who go round and round and round. Anyway, sorry for them. Let's say that you have a list of stuff. 1234. So these square brackets at the ends represent an array. It's a collection of things. So in this array, we have four numbers, the numbers 1234, they're all separate objects, but they are bunched together like a bunch of grapes in an array. How do we access stuff in that array? And more importantly, how do we know when we finished everything in that array? So if we wanted to add up everything in this array, we would first have to know how long that arrays. And then we'd have to access each thing individually one by one until we've accessed the mole. So how we do that is by using loops. The magic word that you're looking for is 44 is the most common loop. And it's in pretty much every single language. If you see four, you know, you're in a loop. Now for take some options. First option is where do I start? Second option is where do I end the loop? You can't have a loop that goes on and on forever. And I'll show you why in a sec. And then as long as that loop is active, then it's going to execute whatever code you put in the loop. So the first time it goes round, it's going to execute, execute gets the bottom. And then it's going to say, is this stuff up top still true? If it is, then I'm going to add one to my counter. And I'm going to go backup here. And I'm going to execute again. Because execute, execute gets to the end, checks the counter. And it says is that true? Yes. Fine. We'll go back round and do it again. And this is just going to repeat and repeat, and repeat and repeat and repeat until this stuff at the top is correct. So you could go around a million times if you actually wanted to. Anyway. So that's what a for loop does. It goes round and round until the data is finished. So without giving you some actual code, which you will get in a subsequent lesson, what we would do in this case at the top here, is we would give it a for loop that says I want you to count from the first element. So stop there. I want you to extract that. And I want you to keep counting around in the for loop, keep going around and around until you get to the last element. And your program knows when it gets to the last element because it's just how arrays work once it tries to go pass that elements. So it looks for number five. In this case, it wouldn't actually find that number five. So this for loop would then end and we would move on to the next block of code. So that's what a for-loop does. Now there are a couple. Of other loops. There's one that I think you should avoid at all costs. And that loop has gotten many people phi it probably lost. Automatic trait is a lot of money because people get it wrong. That loop is called the while loop. And so it's kind of like the for loop. We say while something is true, then I wanted to execute these lines of code. But can you see the problem? Whereas the for loop, it's pretty obvious to use the programmer if it's going to execute 4 million cycles or two cycles, you can see it as you write it. While something here, whoops, I move my iPad screen there. While something is happening here is the key pot. So if you mess this up and this condition never actually returns false, then this loop is just going to keep running into infinity. On and on forever. It's literally infinite loop. So if you look at where Apple is headquartered, I believe it is Apple, they had caused at one Infinite Loop in San Francisco. And that's a joke referring to this. This is really how you mess up software. This just binds up the processor and nothing else can happen on the person's machine, they will not be happy. So while loops, you have to make sure that this little bit of code will always fire at some point, say you can escape this loop, right? So that's the for-loop, that's the while loop. There is one I should mention, which is in most languages. And that is the for each loop. Now for each just simply takes an array of stuff and then tells stuff to it. It's like a subset of the for loop. But it's just more convenient because you just give it the array and then it does it all automatically for you, the whole counting the wax. So I went to explain that here, but perhaps in the code at some point in the future. Now, what other ones do we have? I did actually pull up the C-sharp page. No, I pulled up the Katlyn page because why not Collins a good modern language. So we have foreign Katlyn. There we go. We have while. Now. The while loop, I'm just going to highlight this little bit here is similar to Python, but keep in mind that the condition must be an actual Boolean expression. Okay, that's slightly different warning that the one I just gave you. But look down here, see if I can mark this down here. Net keyboard appears. I can kind of market. I'm looking at the line. It says while x is less than ten. Now, imagine if you had a while, x is less than ten. But in the code below, you didn't actually add 12x. So X0 is remained at say, 0. Every time you went round, x is less than ten is always true. So you'd be stuck in that infinite loop. Okay? Column also has one called continue and break. We can skip that for now. We don't really need to worry about that. There was one other and I just can't put my finger on it. But if you look up any language that you're learning with its name like C-sharp, Katlyn swift, and then put loops on Google. You will find all the information you need for all the loops in that language. 24. Merry Go Round - Loops: Now we get to the section that's quite important, which is the section on loops. So again, let's create a new file and call it loops dot PY. Now, we've seen arrays before this, before, this, before this. I was preempting the next word which was list before this. Mylist is equal to, let's say 1234. So I've got four things in our array that's stored in there. How do we access all this stuff in that array? Well, it's quite simple. We could say, let's print my list, which would print the whole thing. But let's access the first element, which if you recall, is at position 0, because arrays or lists are 0 indexed, IE the first position starts at 0. Okay, so if we run that, we get one. This is pretty straightforward, right? You should know this by now. But there's a problem. Of course, there's always a problem. What if this list of stuff is something we get back from our server? And it's a list of the user's favorite music in the app. Right? How long is that list? Well, what if it's 20 things long? I would have to print 20 lines to access that data, which is really, really painful. So be nice if we could go through the list bit by bit and pull out each bit of data as we went and then stop going through it once we've reached the end. Well, the solution to that is the loop, and primarily it is the for loop. So we're gonna say for m in my list, put our semicolon in, and then we're going to print em. Right now. I don't want to take your survey. Thank you very much. What this does is it grabs the mylist, counts the number of things in it, and then presents them to you one at a time. So it goes round and round in its loop. And when it's finished, it stops executing this for loop. So if I run this and I'm actually just going to comment this out. Now we get 1234. Everything is listed. And of course, it doesn't matter how many things we have in the list is going to go through the whole lot until we're finished. So that's the power of loops. Instead of seven lines, we have two lines, actually would be 14 if we're printing stuff out. Okay? Sometimes you'll want to run a loop for a fixed number of revolutions, but you don't have an array or a list. So how do you do that? Well, the loop can count itself from some number to another number. And the way we do that is we say four, we give it a random variables. This could be called literally anything. Usually the convention for loops is to call it i or j in a range. So we're gonna give it a range of ten, like some sticky my notes here. That should be fine. And then let's see what happens when we print i. So say 0 to nine is fine. And why hasn't I printed? Because I think we have to set i which I haven't done in my notes. What am I doing wrong here? People I know have actually done it, is just because this is run out of space down here. So look, we've run from one to seven and then 0 to nine. So 0 to nine represents the list. So what I'm gonna do, of course, is just get rid of stuff this might not work yet, does, yet doesn't work because this up here is blocking it. Run in the terminal. Now we get, we're off to 0 to nine. So what this does, because zero-based indexing also applies to loops. The first time this runs, it gives ie the number 0, and then it repeats that loop ten times. So that's the first, second fed, et cetera, et cetera, until the tenth time, which is actually the number nine. Now that might be a little confusing as to why it starts at 0, but that fits in perfectly with the fact that lists and arrays are 0 based index iii, they started 0. So what we could actually do here is we could print my list at position i. Now this is going to run. We get up to seven on the list and then we get a crash list index out of range. That's because we try to access the next thing after seven, but we can't because it doesn't exist. And so the whole program crashes. So you gotta be careful with these. If you don't know the length of your lists, then don't do it this way. Always do it that way. In fact, for any list, I would say do it that way. Okay, so we've counted up, what we could do here is say seven, right-click and we shouldn't have any errors. So it all prints out perfectly fine. We're accessing the ith element of my list o K. Now how can we get past this problem? Let's see, let's see what happens if we do an else. And let's make sure it's indented correctly. Finished. Let's right-click and run that. Finished. So once it goes round and round, after that, it executes the else once it has finished. And in this case we've just said print finish. What happens if I take it out of bounds again? Run that. We get the finished, we still get the areas that doesn't do that, but Else is a good way of running something after you've finished the looping process. Well, what else is left here? Oh, it's the dangerous one. The dangerous one is called Y0. Ok. And caveat, never, ever use this. So if i is equal to one, okay? While i is less than, let's say 60, I would like you to print I okay. And we're just going to leave that for now. I don't want to run this, you know why? Because it's gonna get stuck running this and my computer's going to freeze because it's going to suck down all the processing cycles. Because i is always less than 60, which means this wild loop runs over and over and over and over again. So what you need in a while loop, break a way to tell it, hey, if you've reached this point, then quit it. Okay? So what we do is we give it an if statement which is buried in the loop. If, no, actually, we don't need to do that at this point. What we need to do is add one to i, so i plus equals one. You can also say i equals i plus one. But the shorthand that you'll see quite often is that that automatically adds one to I and puts it in the i variable. So now this is going to print out to 60. And then once it gets to 60, it's gonna quit at that point. So they get to 5960 is clearly not less than 60. So we only go up to 59. Just for fun. We can put equals, we can run that. And now we actually get to 60. Okay, so that works perfectly fine. The other way that we can exit out of these is we can say, if i is greater than ten, then break. Now break does what it sounds like it does a breaks the loop. Notice the indentation. This is all happening under the while loop. Okay, so that's what invitation does in Python or other languages, you're going to get stuff like the curly braces there cold that define the starting and stopping points. But Python is all about the tab character. So if you run this, it will now only go to ten. So this is overriding of firing before i is less than or equal to 60. But having told you all of that, please never, ever, ever use the while loop. It is a very, very dangerous pattern that can easily get stuck, especially if you don't control the variable i. You know, if it's coming from a server one day there'll be an error and that little era in a little number will crash your whole app, gives you one star reviews on the App Store and lose your customers. Trust me, it's happened to me, it's happened to every developer out there. So avoid the while loop like the plague. Always, always try and use the for-loop because it's much more specific about when it ends and how long it will go on full. Alright, time for you to do a little task. 25. Loops - Task: Time for your task. So at the top here we created our own list called myList. What I want you to do is create a list of names, any names you like. But one of the names should be Voldemort, spelt in that way, which is, I think the correct way. Then what I want your program to do is to loop through the list, printing each name until you come to the name Voldemort and make your loop break or exit at that point. And then I want you to print out a bunch of asterisks with the message that name must not be said in polite company. Good luck. 26. Loops Task - Solution: Right, so there was kind of a little hidden gotcha. In that task. And I'll show you what that is in a minute or 2. First, let's create our names lists, which is whatever it's going to be, Grants. Fred, and of course, folder mode. And we'll add another one just for fun chain. Right? How do we loop through this list of names? First to get rid of this indentation. We say for n in names. So that's gonna loop through it all. Remember we did the same thing up here. Then what do we want to do? Well, what we want to do is print out the name. If it's not equal to Voldemort. So if n is not equal to folder mode, then we will print n. Straightforward. Else we could have said else if it is equal to Voldemort, but in this case, else covers us for that condition. You got to think a little more advanced when you start to program stuff. In these, you gotta think, I don't know what the correct word is for this kind of thinking. But it's basically, you've gotta compress your thinking, your thoughts into a few lines of code as possible. Not to appear clever, right? Everything's short. Code means clever people. It might mean that, but that's not its purpose. The purpose of compressing code is to make it readable and understandable by some other developer. But most likely, you, when you come back to that app that's now taking off, you made it a year ago and you're looking at this code going what moron wrote all of this stuff. That's why we try to write neat code. I'm not saying we're a 100% successful all the time. I really know I'm not, but that's the Gulf. So else. What do we want to do with this else? Well, we would like to print that message I gave you, which is up here. Like cell. Then what do we wanna do? We want to quit the loop and remember the magic word is break. So let's run that. Oh, what have I done? I've misspelt Voldemort. Typical. Let's try it again. There we go. That is linked through grant, Fred, and our secret message. Now here's an extra little task. If you're feeling really adventurous, I'm not gonna cover it in this, but I thought it's a good challenge because it's just appeared in my own brain. How could you inform the user that that name must not be set in polite company, but also tell the user that there are more names in the list, especially if you're going to break here. So that's a little mind nama. And actually we can remove this break, just coming back to the first challenge and hit that. And we can still include Jane. But if we wanted to break it at this point, how would you tell the user? There's one more thing in here. I'll give you a clue. It has something to do with the length of the array. And how many times you've already gone through the array. And you know what, what the hell, I'm going to solve that right here. Let's have I equals naught. I know we've used I previously, but we can reassign a variable. Every time we loop round. When we get to the end, I am going to say i plus equals one, so it adds one to i. So when we get to this point, we now have a tracker of how many times we've gone round. We so we can print. There are. And what are we going to do? What we need the number of names that are left in the array. So first we need the length of names. And we're going to subtract how many times you've already gone round in AI. But we're going to make i, in this case, one to start with. That's because we're not using AI to access the array indexes. We just saying first time, second time, third time. So normal language to you and I. Hence why I've changed that. We're probably going to have to turn all of this to a string. So there's the key there, the string length names minus1. And then we're going to add a bit more text names left in the array. Now we can run that. And there we go, there or one names left in the array. And Of course, if we do Lenny and run that, there are two names left in the array. So we're doing some arithmetic on the lens of arrays and how many times we've actually used them. So I know I said I would give you the solution, but I currently if you guys on a cliffhanger like that, can I? There are other ways of achieving what we've achieved here, but this way is good enough. I like it because it's fairly readable. I've got an if and what it does. I've got an else and what that does. Simple enough. Right. See you guys in the next one. 27. Getting it Done Methods or Functions - Explanation: Methods or functions. What are they? Well, so far we've kind of introduced a few building blocks of software engineering. We festival had variables. We had stuff like arrays or lists. What else did we have? We had loops. You will come on to things like conditionals, all various bits and pieces. Now, when most people start their software career or learning to code, whatever they're learning to code. They think very linearly, and that's a mistake. It's a dreadful mistake. It's a mistake that I've made. A mistake I've seen many, many other people make. So what they'll do with this set of items here is go, Well, I have a variable a, which whatever equals ten. I want to do something to that to show it to the user. So first I'm gonna say, I'm just pulling these examples out of thin air. Let's make a new variable B equal to ten times a. Ok? So in that case, b will turn into a 100. And then they'll say, I want to go through my array a 100 times. So we've got n equals a 100 in this array. And I'm going to use a loop for that, right? So this loop will go round and round a 100 times. Then I'm going to show b. Now, you might think this is fairly straightforward upside from the stupidity of it, totally made up. But It's not straightforward why this is wrong. In fact, it is correct, right? You want to do these tasks. So that's exactly what you've just tried to dig. You've just done it, right? The problem comes later on when you have a variable x equals 11. And you want to do the same thing to all of these. You want to get through the exactly the same process. So eventually you get to show why. Now people's reaction to this is just to repeat the code. They think that's just what you have to do. There is a concept in software called dry, which stands for do not repeat yourself. Do not repeat yourself. So where you can, you try and whittle down your code into these special little blocks or functions so that you don't have to rewrite the code every time you want to call that function or you want to do something that's inside that function. So a much better way of doing this is like this. What we're going to do is create a function. And we're going to call it at no ad. And then we do some squiggly brackets. And we close the squiggly brackets. Now inside this function, we can say is a plus b. This is an exact code yet I'm just breaking it down simply see you understand the purpose of a function a plus b. Now later on, let's say I need to add a plus b. So somewhere in my code, I will just say, hey, I need you to go and find AD and run it. And that's what these little round brackets represent, a, represent a function or a method. And the round bracket say I want to run that right now. Laser on even later on in your code, you need to do the same thing again. So what do you do? You just say add, Right? And later on again, the same thing. So imagine if you had a scrolling list of items in a mobile app. Like it. So you obviously don't want to repeat the code for every single one of these scrolling items. Instead, what you want is a function that you just call every time you need to do something for each member of that scrolling list. So that's the power of functions. They allow us to take some functionality, hence their name, and put it together in a logical group. So that's fairly straightforward. The real power of functions comes when we start to add variables to them. So we had our function a plus b, which is fine. But a plus b, a and b need to be defined somewhere else. But what I want to have is ideally, I want to have a function called add. And what I'd like to do is give it two numbers, right? So you can open a bracket here. And you say, I'm going to give you number one and number two, or rather stick with our naming convention. I'm going to give you a and b, and you are going to add those together. So the function will go a plus b, right? So now when I call this function, I have basically a generic function. I can give it any numbers I like and it will add them together for me. Straightforward. But again, we add another layer of the power of functions. And that is, without just keep the answer contained inside this function, what we can do is we can actually return it. So I would say here, I want you to return a plus b. So what it'll do is it will add a and B and then it will return it. Now what does return mean? Will later on in my code, when I say, hey, I want you to call add one to, that is actually going to spit out one plus two, which is three. That is facilitated by that return word. This thing can be slightly different across languages, but return is pretty much a universal because we all understand it as software developers. Okay, so what else do we have? You can also assign this to a variable. So you could say var onset is equal to, add one to. And that would mean your answer is then three. So three is stored in your variable. So now you can see the power of functions. And important thing to note about functions is the following. Let's again type out a function called add. And what we usually specify function and we pass something into it. We specify what kind of thing we're passing into the function. So I might say, I'm going to give you an integer a and integer b. And then of course this is going to do the usual thing that we expect, which is return a plus b. Straightforward, right? Except you can do something very special here. You can say, I'm going to have another function called add. And this is going to take a float and a float B. And it's going to return a plus b. And you might wonder why we've separated these in such kind of an arbitrary way. But there are reasons for doing it and you'll come across these reasons as you start to make stuff. So in the first case, we have integer a and integer b. If I call that first function with the following, at 12, that would probably call this. If I sit at 1.02, our system would recognize this second one has floats in it. So it will recall this particular function because it recognizes it. And so what you've just doubled in our cold signatures or overloading, right? So we can have two functions that are named the same, which normally you are not allowed. But if the variables that they take in our different types or different lengths, different amounts of variables. You don't have to have two. You can have one, you can have 50 million, depends on how you construct things. You can have lists as well. Then what we've done is effectively create a signature for each function. And that signature is recognized depending on what we feed that particular function. So there's another power of functions that you will actually use, not that much of the time, but you will use it occasionally and it's something important to remember, right, with all that said, let's get on with the code. 28. Getting it Done Methods or Functions in Programming: Now let's move on to a fundamental building block, yet another fundamental building block of all software, no matter what language, framework, et cetera you're using. And this is called the function. So let's create a function's dot PY. It's also called methods in some languages, Technically, methods and functions are slightly different. I don't recollect the actual difference between them because for our purposes, including myself as a professional developer, they're the same thing. Really. It's only people who really picky. He will pick you up on that kind of thing. So what's that? Well, you know, by now that just prints out an empty line. But what you've just done is coal a function. Somewhere in Python. There's a function called print, which does all the necessary bits and pieces to show a piece of text on the command line. When you run this, we get, well, we get this blank and you can't see it because it printed nothing. But nonetheless, it prints nothing, which is still a task. So that is a function being cold, right? What if we want to make our own functions? Well, actually before we do that, we can drop a name variable into here and we can print that name. So again, we're calling a function, except this time we are passing over a piece of information in the form of a variable. And the print function is set up wherever it set up to take whatever it we give it, and then print that out. So obviously, you know what happens when I click that, we get my name printed. So let me just create a little bit of space at the bottom, a K. Now, what else can we do? Well, we can try a different function. Let's have a equals ten. How do we turn this into a string? Well, if you recall, it's this string a. What you just called. There is another function that turns something from itself into a string. Say he's starting to pick up a pattern here the function is usually surrounded with regular brackets, both in the definition and the calling of it. Speaking of definition, Let's do our own print function. So let's call this print something. Now we know this is a function because we start with the def keyword, right? And you know, it's a key word in any language because the program your type get into, usually puts it in a different color. So you know, we've got green here, we got blue here. All these things mean different things in the Python interpreter. Ok, so this is how we start defining a function. I assume this stands for Define, But I don't know for sure. Print something open and close brackets to tell it. This accepts nothing into this function. So that's supposed to hear the print accepts the name. This one doesn't accept anything. It's a bit of a nuanced area in Python, this particular bit will get onto them. And then we put our familiar colon. Then when you press Enter, you'll notice you get a tab automatically added. That tells you now that you are inside the function. Now before I carry on, I should say in other languages, you'll get functions defined as something like that. Or you write function, lots of different ways of defining them. But there's usually a keyword that precedes the name of the function. And these two brackets. Okay, so now we can print something. Let's call the function. Now be careful because you want to call the function below where it's declared. But you have to go back to the beginning. You have to get rid of that little tabbed space. So just press backspace and that will do it. Now we can call print something and you'll notice that Visual Studio picks that up automatically. And then to run it, you need to add these brackets at the end to run the function. So if I now run that, we get grant from the previous thing and something. So we've printed literally something. Now as little nuance in Python in that, if I try and coal, print something up here, Visual Studio seems to let me do it. But if I run that, we get a name error, name prints something is not defined. And that's because in Python, contrary to most languages, when you call a function, you have to call it after the function is declared as you read from top to bottom, right. So that's just a little gotcha to be aware of if you're new to Python. So let's remove that. We don't obviously need that. Ok, so simple enough, you've defined it and you've called it. Now let me check my notes here. Here we go. Define print argument. And I'm going to pass in my bag. And then print my. Okay, so what have we done here? While we've said making a new function that's going to take a piece of data into it. So when you call it, you have to, you should provide it with a piece of data in Python, you don't have to. And then you are going to print my argument. So of course we can call this print arguments. Let's just put the name from earlier. So we should get grants something different. So that's how we pass in arguments. Now, I'm going to talk about the difference between Python and other languages, okay? If i did print arguments and then just run Python while we do actually get an error. Because it says we're missing a required argument of said, You're going to pass something in, you haven't positon thing in. So there's a problem. I'm going to undo that. So that's the same as pretty much every language out there. But if we start to do things like this, so define. Print another thing. And then we say, I want you to print out a number, which is a type of integer, right? So that you're saying to Python, all I want you to accept is a number that's an integer. This is a perfectly normal thing to do in every language that I know of. And then we just print my number and that should turn it automatically to a string when it prints, it, would just printing it so we can see the result. What we're interested in is this little bit here. So if I go print another thing and I pass it the number nine, and then we run that. We, you know, the results, we're ready, it's printed the nine. But if I pass it my name and I run it, it still prints my name. Even our specified, this should be an integer. So this is where Python is a bit weird compared to other languages and other languages. I would guess an era here before I even tried to run anything or compile anything. Python uses these as kind of hints for the developer. Python is, how should we say like when you reach the age of 18 and all your mistakes become your own. You can't really blame your parents for letting you do X, Y, and Z, and then getting into trouble. Same as Python. If you pass this a string, when you've said, I want to pass in an integer, Python's like, Hey, not my problem Pro is your problem. Ok? So other languages, this is very strict. Python, not strict at all. Right, so I'm just gonna pass that back to whatever it was, doesn't matter. 909. So coming back to these things that we're passing in now you might wonder why I called it argument. That's because that's exactly what this is. It is an argument I don't know with that terminology comes from, but every language uses the same terminology. So once you've lent it, you'll be fine. This is an argument, IE, a piece of data that you pass in. K. What else have we got to print multiple, deaf, print multiple. So what can we do here? We can print multiple arguments first, second, and then we can print first plus second. Now we can call that print multiple. First. Note first we have to pass it stuff. Name is plus. So now I can right-click and coal that ways that era. Oh, I shouldn't have put plus they should, I, I should have put a coma. Okay? When you pass multiple variables, you split them with a comma. And when you give them over from when you call the function, you split them with a comma. Again. Run Python, name is ground. Ok, so what I want to actually impress on you in this particular session before we go on to the task in the next session is functions are a way of logically organizing code. Now the objection most people have at this point is to say, look, you're printing something, you're printing an argument. Why not just call this print down here? Instead of adding effectively an extra line and making your document seem more complex. Well, there are two major reasons and a whole bunch of minor ones. The major reason is that what if Python changes this at some point in the future, the print. So they might say print, LN, print, line. And print no longer exists. If you've used print everywhere in your code, you're going to have to change it everywhere. And if you don't change it some way, it could crash your entire code. And you obviously don't want that to happen if you're trying to work as a probe. So that's the first reason when you come back to your code. Because I've defined it here, I can just change it here to whatever the new Python version says. It should be, right. Because I control the name of this argument. Then I don't have to change that anywhere. If I don't change it myself in future versions. So I control essentially the naming of all of the functions, variables and things like that. If the naming of the functions of variables are outside of my control, IE, they belong to the Python foundation or whoever makes this stuff. Then I want to actually encapsulate that in my own argument. Now encapsulation is something else we'll get onto. But that's effectively what we're doing here. We're surrounding it with a wall and saying if I pass you sort of through the window, you pass me something out through the other window. End of story. Okay. So that's one reason why we do it. What's the other reason? Well, if I want to print something to the console each time, and you will see this as we progress through the rest of this course. Then I don't want to be repeating a bunch of codes. You can imagine if I had some code here. Do other things. Times five lines. Well, I don't want to do five lines plus print, do i each time. I'd rather just coal this function that will do all of those things for me. Okay? Now having said that, a golden rule when it comes to functions is to make them as short as possible. So what you're seeing here is the ideal function. It does one thing and only one thing. In reality, you'll never get to that point, but you can get pretty close as long as you've architected your app pretty well. Okay, so those are functions. That's why we have them. And those are the advantages of using them. 29. Methods or Functions - Task: Okay, so I think the homeworks are actually getting a fair bit more difficult for you guys. And I've actually planned it that way because being a software developer isn't about knowing code. It's about knowing how to solve problems in the shortest, most efficient way that will cause you the least pain in the future when you have to upgrade these things. So this task is going to be a little on the more difficult side, but I will give you a clue. So I've slightly changed this print multiple function to have a firstname, second name. What I've done is I've included a space in there. So if I pass it something, it will automatically add the space between Joe Bloggs, the FirstName, and the second name. So what I want you to do is to change this function to include a variable Boolean argument. Okay? So you're just gonna pass in an extra argument which is true or false. If that variable is true, then I want to include this space. If it's false, then I want you to leave out that space. Sounds simple enough. I'm gonna give you a clue. So I'm going to copy this. Print multiple and wash we call it, let's call it with space. So I'm just gonna give you the first line. Here. We are going to have insert space. Okay, now it's up to you to print the rest of it. You are going to need to use the if statement may be the else statement in combination with that. And then that will allow you to check that variable if it's true or false and add the space or not. And then I want you to print out the final name. Good luck. 30. Methods or Functions Task - Solution: So how was it? Was it tough? Well, I'm willing to bet 99% of you did it in the following way. If insert space is true. So with the if statement, you don't actually have to write the following. Because it automatically does. It automatically checks for Boolean. So you can leave it as such. You might have got stuck on that bit. I'm not sure of totally explained that. We are going to print firstname plus the space plus second name. Write simple enough. And then I'm willing to bet that most of you also did the following. Else. We're going to copy that. Paste it, and remove the base. Okay, so of course if you call this now false, I'm just gonna get grunt ground repeated with outer space. And if I call true, we get it with the space. Straightforward enough. But there's something redundant here. We have more lines of code, then we should actually have, we've repeated the print statement a couple times now I know I said in the previous couple of lessons that we should put the print in its own method. So we can actually do that. We can say def. Actually we already called that didn't weigh. So where at the top here we had print argument. So we can actually use that again down here. So we can just say print argument, right? So this is getting slightly better now. So when we come to upgrade our program, if Python upgrades, we only need to change that print statement if that changes up there at the top. Good. But still, this is too long. Let me show you how I did this. So if insert space, what I did was reassigned the variable first name is equal to the first name plus a space. So I'm concatenating that. Then I just totally remove the else because we don't need that. And I did that. Right. So if I run that, if it's true, we get grant ground. And obviously if it's not true, we're going to get eight mashed together. So all of that works fine. Now what I did here, I don't know if it's actually a technical name for doing this, but I've kind of half the workload. Let's assume you get an insert space 50% of the time. Well, 50% of the time, it's going to check this and go, it's false, so we don't need to run this. It will go straight to here. You have a 50%, it will actually run it. So I've just cut the workload of this function by Hough. It previously, it wasn't that bad, so over exaggerating about workload. But as your apps scale up in performance terms, especially with stuff like games, these are the things you need to be kind of aware of. Okay, I know that's kind of a more advanced topic, but it's good to put awareness into you at this point. Most importantly, though, I've saved a lot of space, a whole single line of code, right? That does save quite a bit of space. And you can imagine that over 20 thousand lines of code, it means that you only have to end up writing 15 thousand lines, which will save a few months of your life. And as we know, there are all things we'd rather be doing than doing work cell. You can thank me for saving a couple of months of your life later on. But I hope that you understood what I'm trying to do here. By passing in variables and then manipulating the variables as in here, in order to give the output that we want back. Now there are other things that we could do to this. You know, what, what I might do is actually return stuff. There are even shorter ways of writing if-else. So you can look up Elvis operators. If you really want to. We could have this returning the firstname, second name, and then putting that into the print argument, which would actually squash or decrease the size of the functions, which is always a good idea. But on the flip side of that, that's called premature optimization. And it's bad. It's as bad as the other kind of premature thing that I know the guys in the audience are thinking of right now. Optimizing too early is a downfall of all developers myself included. Don't optimize too soon. If you construct the architecture of an application correctly, then the optimization is pretty easy to do later on. So what I would say is, if you are going to make any kind of app on any platform, concentrate on how it's structured, which we can't really cover in this course apart from touch on it lightly because you're still learning. Concentrate on how it's structured. And then you can go from how it's structured to efficiency. Once, you know, people will pay for your application. So if you haven't already, you can get the software entrepreneur flowchart from That gives you all of these listed out in a flow chart telling you how to think about monetizing apps and things like that. I know this has gone quite far off topic of functions. But we're starting to get into the point where functions show you how to architect an app. They're the first fundamental stepping stone of architecture. And so I thought maybe prudent to mention to that, mentioned that to you guys at this point anyway, enough rambling on to the next section. 31. Sorting Things Out - Classes - Explanation: So far, I've given you two types of things. On the one hand, we have variables, on the other hand, we have functions. Now, I'd include the loops and stuff like that in the Functions area and variables. Well, those are by now, but basically a variable is something I function does. Something like, let's say you're writing a simple program, simple program that's going to contact the server. It's going to get some data from the server and then show it to the user. So everyone's first temptation when they start writing a program is to just shove that in same block of code, right? So let's say you even engineer at Wellesley or functions are correct. So let's say you have a function to get data. Let's do this properly. And I'm just going to put all this on one line to make it fit. You have a function to manipulate the data. I'll just call this manip. And then finally, what are we going to have a function to show the data? Everyone is always tempted just to shove these in the same file, literally the same text file that has all these other functions and they just run that when we need to show this. But that would be very, very bad architecture in software. Why? Because we are mixing up the functionality yet again, remembering functions. I said your function should do one thing, one thing only and one thing. Well, well, it's the same thing when we start to clump together variables and data. So if I actually adding variables to this, we might have a data variable. What else are we going to have? We're going to have, let's say, we would call this far window variable and the vowel window, which just takes care of displaying stuff on the display. In reality, we don't actually have a var window, but you get the idea. And then of course, up here, we have maybe the manipulated data is equal to whatever. So again, we have some variables we need to add. And you'll notice how these variables kind of sit with their parent functions in a logical order. So that's important to remember a logical order. So let's clear this out. The solution to organizing all of this is to create what's called a class. So a class is defined a little something like this. You'll usually see the class keyword, but not always. Sometimes. It's implicit that it's its own class if it is a separate file, for example, in PHP, you would just start a new file and that would be a class. So you have a class, we would call it something. We would say data getter. Actually that is a terrible name because Ghetto means something different in c-sharp class. Data fetch. Okay, and then we will open, close our curly brackets. And by organizing the stuff, we can start to think a bit more logically about how to lay it out. So in data fetch, what would we have? We would have a variable of data. We would also have perhaps a function to get data and maybe other bits and pieces around that. But you'll notice in this class, no way do I have any function that says manipulate data and nowhere do I have any function that says show data. Okay, so if I again clear this because you can remember what that looks like. Subclass data fetch. Then I want to manipulate that data, right? So I would create a separate class called while it wouldn't actually be called manip data, you'd give it a more meaningful name for what you're doing to the data. Again, this class would contain, let's say, the variable of manipulated data. The function, the function too, change data or whatever you're doing. It doesn't really matter, right? And then finally, we have yes, another class which would be called show data or store data or whatever you need to do. We would drop that in to its own little area. Okay, so do you get the idea here? We starting to split things up logically. So your basic building blocks up functions and variables. So variables, offerings, functions are things that do stuff to things. We need an overall encompassing thing over that, it says, I want to store all my variables and functions for showing the data. In that particular class. I want to store all my variables and functions for manipulating data in that class. And in the data fetched class, the same thing, all the variables and functions for that. So we're starting to organize our program. And actually if I click this once again, what your program will end up looking like is probably something like this. You will have data That's o STDs in different colors, keep it consistent. Manip, sharp. And what your actual program structure will look like. The file structure on the disk will be these are folders, right? It's not always like this is not a 100% true all the time because programming is subject to style of program has been more or less like this. And then in the data class, in the Data folder, you'd have another file that is a get data class. In the manipulate section. You'd have Manipulate data class, and of course, you can guess the rest in here. You'd have a show data. But because we're starting to organize these into classes, let's say for the get data class, you want to add a, another class that's to do with getting the data. But, but it doesn't sit under manipulate or show, of course, because it is get data. It doesn't sit under Get Data. Instead, you might create another class saying get cache data, IE the data that's kinda already stored on your device or on a database, whatever it is. And you'd put all your code into there. So now your software starts to get more organized. And I know I started this lesson by saying, this is just about explaining classes to you. But really what I'm trying to get at is classes or just a mechanism for organizing your program. Because you're going to end up with tens of thousands of lines of code. So you need to have organization. Why do we need organization? Well, this is the final point. Because look at this. Do not repeat yourself, right? In our app, we let say we have a scrolling list of tickets and we use the get data class to fetch the tickets from a server. The user can then see the tickets later on in a different screen of the app. The user wants to look at all of their expired tickets. Well now because we've separated everything out, including the manipulation and the showing, we can again get the data. We can manipulate it in a slightly different way, which is like perhaps a filter here. We'll filter for all the expired tickets. And then in show data, well, we don't really need to change anything, Dewey, because we've changed, we've, we've morphed the data in the manipulation layer. Ok. I have gotten a little bit complex on this one because I think it's important for you as a learner to get these concepts in your brain, even if you don't understand them. Just to understand these ideas behind code when you come across code in the wild. So a big problem I had when I was learning was I would look at, you know, the Google repositories or the apple repositories for code. I pull one of their repositories and say, or I am going to start with this basic music app. And it would look anything but basic to make that all these folders, classes, structures, everything seemed to be talking to everything else. But what I didn't know was that they were just applying good architectural principles. And if I understood that at the start, like I'm trying to show you that I would have been a lot of a lot further ahead in understanding these stuff these things. So I'm not trying to confuse you. I'm just trying to plant the seed that this is all about organization and not repeating yourself. Okay, that's enough of that. Let's create some classes. 32. Function Returns in Programming and Some Forbidden Fruit: The next fundamental part of functions is the return function. So let's make our new file. And let's call this function's return dot p, y, k, like my usual space at the top. Now before we had some basic functions like this, add numbers. We pass it two numbers, a and b. And what do we do? We add the numbers, may be print them or something like that. But if we did something like this, we would have a problem. Why? Well, because sometimes we want to add numbers in our code, but no actually print the result. We want to get the result back from running this function and do something with that answer. So how do we get a hold of it? Well, it's pretty simple. We use the magical return keyword. And this is the same in pretty much every language out there. So you're going to return a plus b. So now if I said Answer Is equal to at nums, and I said one and t, And then I print that answer. What's going to happen is this will return the answer. This will store it in the answer variable, and then we'll print the answer. There, we have it, the number three. I'm obsessed with the print lines, the start and end now, a k. So that's how we return stuff. And you can return anything from a function that you like. Kay? So that's what the real power functions lies apart from organizing your code, it's also in returning values that you can then use in a subsequent function. Now what if for some reason? Well, actually I'll tell you the reason why you do this. You have a function that's empty. Well, in other languages you can leave it empty, but in Python, you need to specify it. So you'll have to say empty function. Is this. If you try to run this, I'm pretty sure we'd get an error. There we go. We indentation Arab something, something. So what you have to do is under that, right pass for now. In other reason, you would do an empty function is when you first making an app, you would say, I need a function to go and get my color template. So we're gonna get the template. I need a function to get the data from the server. It'll go get the data. You don't actually want to write the internal bits of the function yet. You just want to have place holders. You want to define the structure so that then you can have paths in them. You actually come round to doing it. Ok. To be honest, I don't use it that often because I tend to write out my architecture for all my apps on my iPad. I just basically draw it. And I don't do it down to this level of detail. I do it to a higher overview of how I structured my apps. But if you're just learning code, totally advanced topic. Now, I reference some forbidden fruit in the title of this video and hear it. Let's have a new function called forbidden. And what we're gonna do in this function is print. No. And then what are we gonna do here? Well, the here is the forbidden fruit. You can actually call a function from inside itself. Okay? And then if we come down here, we can set this all going. So this is like doing time travel. You are really thinking about what's going to happen here. You're going to run this function. It's going to print no, and then it's gonna run itself. So it prints the runs itself. And that just continues forever. In theory. Let's run that. There we go. So if I scroll this up, I keep scrolling, keep scrolling. There is a lot of text in that console, right? Until we get to this point. Trace back in forbidden. Here we go, recursion error, max recursion depth exceeded while calling a Python object. So there's a built-in safety check for this in Python because this could go on forever and freezer computer. But at some point Python says, this is a bit stupid, so I'm just going to kill this, okay? There are times when you will use a recursive function call. It can be useful, but be very, very careful that you actually get out of it some way. You have an if statement, a break statement or whatever statement that gets you out of it eventually. So that's the forbidden fruit, not totally forbidden. You can eat it if you wish, but only eat very small chunks of it. Okay? I think that's that for now. So that's basically how we return stuff from functions and the forbidden fridge. Let's move on to a task. 33. Function Returns in Python - Task: So now I've given you the tools you need with arguments and return values to do the following task. I want you to create two functions and each one takes two numbers. The first function, we'll add the numbers, and the second function, we'll multiply numbers and both of them will return their respective answers. Then I want you to use those functions by calling them to solve this some 3.26 plus 4, there is, there is, there are nine times 56.9. And I've put this in brackets because I want you to do the addition before you do the multiplication part. So that's pretty straightforward, but it requires a little bit of thinking. Good luck. 34. Function Returns Task - Solution: So how was it? Was it fairly easy? I think this task is actually fairly easy. But I'm not any teaching you about functions. I'm teaching you a little bit here about architecture of apps. So we come into architecture in one or two lessons time when we talk about classes and then we've really hit the road. But what I'm trying to get to you across to you here is that you can have a function that adds two numbers, a and b, and returns the result of a plus b. And then you can have another function, which was, what was it? Multiply two numbers. And you can call these a and B as well. And you can return a times B. And you may be wondering how come I can call these the same thing. First of all, in fact, I don't think I've explained this to you yet. The reason why it's called scope. Scope means that when you have some variables, they stay in their little container, the deeper you go. So in a function, if you have a variable that you declare in that function, IE a and B here, that's where they stay. If I was outside here and I said a the icon access it. You'll see the interpreter says Dunaway is, if I set a is equal to 0. And then in the same section I asked for a. The interpreter can actually find that. So that's just a little extra tip for you, that's called scope. You can look up Scope in any language, and it's always pretty much the same, except JavaScript. So always except JavaScript. Okay, so there's the two functions. Now again, you might say, well, why can't I just do times and plus where they are? Well, admittedly times and plus aren't going to change. But if you have a calculator app, you don't want to keep doing this wherever you're doing it in your code, you'd actually have it. You prefer to have it fixed in its own function so that when you pass it two numbers from the user typing in numbers, you could just call this. And so basic calculator app just needs for functions. Add, subtract, multiply, divide. Simple. Okay, so it's a little bit of architecture. They're separate things out as best you can. Now we're going to first do the addition. So the addition result is equal to add two numbers, which is 3.264.09. And then we need the multiplication result, which is multiply two numbers. And which two numbers? Well, let's get the addition results and pass in that other number, 56.9. Now, we can print with a lowercase p. Onset is MLT. Whoops, not that one. We want moat raise. And we have to change that to a string and close all of that off. So now if we run that, we get our eventual answer. Now, whenever I see a whole bunch of 9s, I'm suspicious that there's a rounding error. We've discussed that. I'm not gonna go into that again, but that is my solution to that answer. How could we improve this? That's a question I'm gonna ask you over and over again. What I would do is have, yes again, def Print, String. Or perhaps print message is a better one. And then I would print that message. So what I can do here is change this to print message. So everything is contained neatly in its eigenfunctions. If Python ever changes, I can just come and change that in one place. And if we run this to check it, we get the same answer as you might expect. Okay, so that's my result, that's how I do it. I know I said two functions, but we kind of ended with a single with three functions rather. And I think that's pretty much all I have to say about that. Except for except you could go one further. I'm not sure it's a 100% necessary convert to string. And then you could return STR item. And then we'll call that down here, convert to string case. You can either call it here or you could call it somewhere else, but we'll leave it as it is. In day-to-day practice. I wouldn't actually bother with this because software systems are so well worked out at this point that this never really is an issue. I don't know a lot about Python. So I may have to eat my own words on that. One. Says the guy who's teaching you Python. Anyway, programming is programming. But if I was being a very strict, neat programmer, this is actually how I do it. And if you work in a team, this is how things would end up looking lots and lots of functions. So people don't get confused as to how your program is structured and how to use it. Anyway, let's end that one day. 35. Confusion Reigns Classes vs Objects - Explanation: I just want to add a second explainer video before we actually crack on with classes. And that is to explain what is a very confusing subject for people and it really shouldn't be. So let's say we have a class called get. No access. Make this real simple. A class called Dog. And we say var name and var read. Well, how does this actually get used in our program? Where we have to do is look at this in a slightly different way than a programmer would. And more in an everyday way, which is what I've created here, is actually a blueprint for dog. If I use the code in this class and I used it to make something, i have a blueprint that's been used to create an object, in this case, a dog. So what I would say is, I would like to have a new dog, right? So what this code does is it goes up here and says, I'm going to look at this. I'm gonna do all the stuff that I need to do in here in order to create a new dog. Where we store that new item is to say var. Whatever you can call your variable, anything you like is equal to mu, dog. And we don't always use the word new. We can actually in most languages just do that. But I'm going to leave New in there for us. So now we have a dog. If I wanted to create a, a name for that dog, I would come over here and say dog dot name equals Fido. We wouldn't do this in reality, we construct it in a slightly different way. But for this example, I think this is good enough. We would, we could also do the same for breed. What happens if I want another dog? Well, I could have var d2 is equal to, we'll construct this the different way dog. And then I would say D2 dot name is equal to Fred. Simple enough. So now I have two objects that are different from one another. I have doc1 and I have talked to both of those have been made from the class, which is acting as a blueprint for what a dog should be. Finally, the magic word you will see is instantiate. Instantiates simply means take this blueprints and create whatever you need to create from it. So when we instantiate a class, what we're doing is taking the blueprints and creating the object. 36. Sorting Stuff Out - Classes: We move on to the most fundamental concept in all software engineering, which is the class and all classes. Well, it's two things. It's a way of organizing your code. And secondly, probably more importantly, it's a way of creating new things in your code. And I'll explain what those mean in due course. But first, I'm looking at the code from a couple lessons ago, and this was our functions lesson. Look at this code. And all we have is what, 46 lines. Obviously, if you remove the whitespaces, we have fewer, but it already looks like a mess. Now if you're writing a piece of software, you know, 1000 lines of software is a tiny piece of software. 10 thousand lines ordinary, a 100 thousand lines, a comprehensive app. Some software goes into the millions of lines, I dunno what Windows has, but it'll be in the dozens of millions. I would have thought. Imagine if all those lines of code, which is strung out like this, right? And you couldn't rename any function where you can name any function the same as another function. You can technically, but we're not gonna go into that here. But you don't really want to. Let's say you have where you have Windows, you have some functions that take care of detecting new devices are the functions that take care of detecting keyboard input, camera input, Mike input like I'm using here. Well, now you have a problem because this is all mixed up. And the solution to that chaos is the class. So if we close functions, let's make a new file called classes dot p y. What is the class? Do? Well, it logically orders your variables and functions into a cohesive unit. Okay? So if we take a real life example and I know I explain this with the iPad drawings, but another example is, let's say you have a car, right? And you want to turn the lights on. Well, you flick little switch in the car. If you're in the house and you want to turn the lights on, you flip the switch and the house. Both items have a switch, but they are logically separate. They are self-contained. So if I say car lights, you know, that's to do with the object called car. If I say house lights, that's to do with the object called House, it just so happens that they are physically separated by the car body and by the construction of the house as separate objects. So you can imagine a world where the house is combined with the car. I'm not talking about a mobile home, but some weird Frankenstein monster. We have a house combined with a car and the light switch controls the lights on both. Well, things get very confusing at that point. Not least in my head, because that is a weird concept. But anyway. What's the shell of a car represents and the body of a house represents our classes. One is a class of house, one is a class of Car. Now it's going to be the same here. So let's put my little print spacer in here. What we're gonna do is create a class using the keyword class called Person. Now this doesn't take any brackets like the function because it isn't a function. It's just a way of storing things together. Inside of a class, we can put as many variables and functions as we like. So what does a person have? They have an age, maybe this one's nine. The name is crowns. And inside of the class, we can also call functions. So we can say print. And we can say, let's say new person created in quotes, of course, like set, right? So now we have a class. Now all the classes is a blueprint to make something. So if I want to make a person, all I do is called a class and then add the brackets. Okay? Now if I run this, we get new person created. I forgot to put my little obsession of the print down their new pests and created. So this creates a person from this blueprint of the class, okay? Now this person has all the properties and functions of the class. So if we make this into a variable, we say my person is equal to that. And then we say, I would like you to print my person dot h. Run that. You pass and created and we have the number nine because that's how old this person is. So we can access all of these things. So that's pretty simple. But there's a, some, some caveats, some things that can actually catch you out in all languages. So let's make a class of better person. Now, what does this better person have? Well, we, we would actually like to pass in the age and the name of the person. So we don't want every person to be nine and everyone's name to be ground, because that's a useless class, right? I don't want to write a class for each person. That's just stupid. So what I'm gonna do, instead, I'm going to tap in to what we call the lifecycle. So when you create a class in Python, there is this thing called init that gets fired up. And if you select it like I just did there, so I'm typing it. If you press Enter when it suggests something which isn't doing right now in it. If you press Enter here, it's going to do this stuff for you. Okay? Don't worry about super dot init. All that means is that it's going to do all the stuff that this was going to do anyway before we tapped into it. So just leave that line. What we can do is pass in an age and a name into the init. So whenever you make a class into an object, this init gets cold. It also gets called with self. Self refers to the object that you're just about to make, all that you've made already. So every function in the class is going to have self inside it. Ok? Ignore all of that for now we have self. Now I want to pass in an age and a name. Okay? So now if I ask for a better person, so let's say better person is equal to better person. And I open the bracket, look what it asks before. It asks me for an H and a name. So I can say tenth and Fred. Okay, so now the age and name get passed into the class. And it's worth noting that in other languages, this parsing over variables usually gets done up here. It's a slightly different syntax, same idea that now how do we make sure that these persist, they stay in the class? Well, we can say self dot h is equal to h and is equal to name. Now when you add self inside it, it's the same as saying this. Age and name is the same as adding the variables into the class. You will also see self represented as this in other programming languages. All it refers to, again, is the object that's made by this Class Blueprint. Okay, so now that we've set these up, we can access them. So we can say, hey, can you print the better person, dot name? And there they are accessible. And of course we'll run that. And there it prints Fred for us. So now you can see we have a class that allows us to define the age and the name or the properties of the person that we're creating from the class. So think about this in a real-world example. You have a register of school kids, got 30 kids in the software that you're running for the register, you have a list of 30 kids. Each one of them is created by the class. And of course, each one has an age or a name. So we can have, in fact, another better person is equal to better person. And this one is 11. And cold Nancy. And then of course we can print another better person, alphabetic person, dot name. And if we run that, we get Fred and Nancy. So the class is just a blueprints. And every time we create a new object from that blueprint, it is a different object. So this object has nothing to do with this object. They are totally separate. The only thing they share in common is that they came from the same blueprint. I'll cover this more in the next section. Okay, but in the meantime, what are we going to do? Well, classes can also have functions that we define. So in this class, let's have another function called Deaf, print name. Open. We always start with self in the functions in a class. And we don't need anything else. And what do we have to do? Well, let's print So now down here, we don't actually have to call print. We can just say a person dot print name as you call it like any other function. And another better person, dot print name. Now you'll notice, I don't have to pass in this self thing. That's just an internal Python thing. Other programming languages, you don't have this. Other programming languages. It would just look like this. And you'd still have access to cell phones. This. Don't worry about that for now. If it's pretty confusing at this point, then I'm sorry. But classes and objects tend to be the most confusing for people. Hence why I've added another section in this course about that. Ok, but you've got the basic idea. If you don't understand it fully at this point, it doesn't matter. You understand by doing. So, what we're going to move on to now is the task that I want you to complete. 37. Classes - Task: Now onto the task, I want you to make a class called maths that does four basic things, which is add, subtract, multiply, and divide two numbers in each case. Then I want you to use that class to do the following. Sum. Nine plus nine plus 18 times 39 minus three divided by two. So do the bracketed SMS first, like we have before and other tasks. Now this is pretty tough. You'll need to create variables to store the intermediate answers as well as use return values in the functions in the class. So you can put these anyway you like, but try to limit the number of lines of code. I'm actually going to give you a clear, I'm not going to show you how to make a class because that is the main task. What I'm gonna do is give you the end of the task. So you can feel free to copy this. I've created a maths class, and that's your task. You have to create that maths class I referenced at the beginning. Let's give some space here. I get an ad answer and multiply answer, divide answer, and then our final answer. And then I print that none of these things exist yet. So that's your job to create all of these under the heading of a maths class. So feel free to pause it at this point. Leave this on screen to give you a clue how to do this. And I'll see you in the solution. 38. Classes Task - Solution: Okay, so how was it only had to do? Was create a class fairly straightforward on how you create the class. And I asked you for, for functions. So deaf ad, and don't forget we always have self. And then the variables that we pass in. And then what do we do? We return a plus b. You don't actually have to put a space between them totally up to you on how you like to code. Okay, so that's the first function. The rest are pretty simple. I'm just going to copy them from my answer into here. Self-explanatory subtract does the same thing with subtraction times and divide. There might actually be a way, a shorter way of doing this, but that's by the, by we'll leave that out for now. What I wanted you guys to get mostly was this create your own class. And then from that class, you create the maths object. Then you get the answer for the addition of that sum I gave you nine plus nine. You get the answer for multiply, divide. And then finally, you follow the logic of the sum I gave you. So if we now run this, we get 16.518. Now here's an interesting question for you. And this is an architecture question. If I have a class called maths, should I be storing these answers inside of the class? Or should I be storing them outside of the class? So that's a tricky one and it requires a little bit of thought. The way I would approach this and this is off the cuff because I didn't think about this before I started recording this answer. Or, or indeed planning this whole course, is that if the variables are required to perform a different action elsewhere, I would have them outside of the class. So I would calculate them all as we have done here. If the variables were to do with something inside the class, I would do something like cumulative result is equal to 0. Now this would remain inside the Maths class. And every time I perform a function, I could add it to this. There are dangers in doing that, of course, but there were also bonuses in that everything is neatly stored away in the class to which it belongs. Okay, so that's just an interesting question for you to ponder. And actually it is a question you should think about every time you're making a class for your particular application. So I hope that wasn't too difficult. We can move on. 39. Confusion Reigns - Classes vs Objects: So whenever I teach people in real life and online, they get very confused as to what a class versus an object is. And we've just, I've kind of touched on it in the previous section. But what I'm gonna do here is expand on it a little more because it's kind of a fundamental concept that you need to get down. So let's say you have a class called maths. And just for expediency surfaces purposes, surfaces, they simply adds two numbers and returns the result. Okay. Now here's my question to you. Does this exist? You're probably going to say yes because it is a text file. But when you're running a program, this doesn't actually exist yet. This is stored away to use later. Now how is a class used? Well, it's used to make something because a class is a blueprint. So class here doesn't exist yet until I do the following math object is equal to mass. And what this command does is go to the Math class and say, I'd like to make something that abides by your rules in this program. And the mass classes. Here you go. Here's an object. Okay? So now this is an object. It does all the things that you defined in class. Here is another math object, which is equal to maths. This object is completely different and separate from this object. Just because they share the same class, doesn't mean they are the same objects. And I can prove that here. Print the math object and print the, another math object. Now watch this. First of all, we have this number. This is the ID of that object, so that Python can go into memory and retrieve it whenever we want to do something with it. And this is the ID of the second object in hexadecimal format. Hence why you have a to F? I'm going crazy. A to F, I think. Anyway, you have letters and numbers, but not all the letters. These are different. We have seventy one, forty eight, and seventy one, D8 here. So they are different, object distinct in and of them selves. So just to reiterate, class is the blueprint. It doesn't exist until you do this when you make an object. And you will sometimes see this referred to as instantiation. You are making an instance of a class that's just fancy words for making an object from a blueprint. That's all instantiation means, don't worry about it. Now I'll just show you one further thing. We can actually make a whole list of objects. So we're going to have myList equal to a blank list. And we're going to have for i in range ten. So this is a loop that's gonna go round ten times. And we're going to go my list dot append a new maths object. So now we have ten math things. Now this little snippet of code is going to be very useful in the class project, which is right at the end of this course. So you make a note to come back to here because this will help you out a lot. K Now we can print, what can we print? We can print the length of my list. And what else can we do? We can say for m in my list, we can also print M. Okay, so I'm just going to go ahead and run that. And then we have the Identifies of all ten items. And there are of course ten items because we printed the length out at the top, then all those identifies are the same up until a point because it's counting up its ID. I don't know where Python draws the IDs from. If they are random, they don't look random to me. They might be Time-based, they might be actually time-based. Maybe not. They might be. What's the word I'm looking for? Based on where they are located in memory knows. I'm not a Python proud. So it's something like that. Okay, so that's what I wanted to get across to you. A class is not an object, but an object is made from a class, and an object is a stand-alone item. 40. Classes and Variables - A Warning: So I was just doing actually the final project of this class. And because I'm not a Python Pro, I was actually coding Python in the way that I would code Java, Swift, C-sharp, all languages that I know very well. I don't know Python that well. And I made it dreadful, dreadful mistake. Not, not really a mistake, but something I should tell you about. C. You don't get caught out. So in our classes, we made this class called a person and we set an age and a name. Now what I should have said and should have researched before is that these variables in the class belong to the class. So I can come down here and I can say person without making a new object. And I have access to name and age. So I can set this person's age to ten. And then if I ran this, it would actually change it to ten, even though we set it before we created a new person. Okay, so this is the concept of a class variable. If you change the class variable, then any subsequent objects that you create will have that changed value. Now what's the way around that? The way around that is to chain is to create an instance variable, which is what we've done down here when we in it. Okay, so when we say self.age, this belongs to the instance. So this belongs to this. Do you see what I mean here? So if I change this and then I made a new better person somewhere else, it wouldn't know anything about these variables. Okay, so I know I said we just had the whole rant about classes versus objects. But unfortunately, Python smashes the two together a little bit. In other languages, you have to explicitly say that they're mixed up. And that avoids this coupling of code that can happen or this, this spaghetti code, for example here, where you change the class variable and that gets transmitted all the way through all the class objects that you create after that. So that's just something to watch out for now in the rest of this course. Because as I said, I discovered this recording the end of the course. Or I realized it after much searching and I went up, maybe I should look up variables. And there it was in a few people's blogposts. I'm not the only one that has this issue. So what you'll see in the next bunches of lessons is sometimes I will use this notation which isn't a 100% correct, where you see that it has another task for you. Change it into this notation where we include all the variables inside the init function. So it belongs to the object and not the class. Ok, I was debating whether I should put this in or not because a tutorial guy, the people watching think you're a pro. But I can guarantee most people you're watching her writing code are not professional in the way that you think. I'm professional in that people pay me money for correct code. But software engineers don't just sit there type out code. That's perfect. The first time we get bugs, things go wrong. And that's the reason I started my website. I am because I want people to see the whole process. I've also got a range of series coming out called Build it, where I build things in real time. And I sit there most of the time like this. I'm wondering what the problem is. But then together, you and I will solve that problem. So you can see the methods are used to solve the problem. It's the equivalent of feeding amount for a day or teach him how to fish. I'm trying to teach you how to fish and not how to just copy the code that I've already made. I'm teaching you how to solve problems, how to design solutions for those problems. So that's a long rent. To end this video where I showed you the mistake that I made long and short of it is try not to use this. Do try to use this. 41. You Are Rich - Inheritance - Explanation: So a rich relative has died and pass you a huge inheritance. Unfortunately, that's not true. It's just a little bad joke. What we're going to talk about now are inheritances in programming. What do I mean by that? Well, very, very often you're going to find that when you create a class. And let's call this class, I don't know that we're not going to call it that, not going to call it calculator. Let's do a class called Dog. Now this class is going to contain a whole bunch of code that says, for example, let's have a function called wolf. Let's have a variable called Name. And that would contain Fido, Fred, whatever you call your dog. When you call the function with it makes a noise. When you request the variable name, then it will give you the dog's name. Straightforward, right? What if we have one more variable? Say this variable is going to be called, let's call it number of legs. Simple enough. It'll return four for dog. Clearly. What if we now have a second-class called cat? And this has meow, it has the cat's name and it has the cat's number of legs. So far, name, VAR numb legs. And of course it has the function. Yeah. What do you notice here? I'll give you a couple of seconds to think about it. I'll give you a clue to. You remember this phrase. Don't repeat yourself. What have we just done? We've repeated ourselves. What if you are creating a zoo app that had the characteristics of thousands of species of animal. Do you really want to type out the name and the number of legs in each and every class. While clearly you don't. Luckily, there is a solution for all of that. So let's create a class called animal or mammal if you're being more specific. Now in this class, you'd have var name and you'd have. Number of legs. Okay, now everything that I create from that, so if I had a class of dog, a class of cat, I want those two classes to be able to use whatever comes out of here. That way, I only have to write these ones. And the answer to that solution, or the answer to that solution. The solution to that question or the answer to that question is to use inheritance. So what we say to the dog class is, I want you to inherit from Animal. And the same with Kat. That means that both dogs and cats can use everything in the animal class. They inherit all those properties, all the functionality that a basic animal can do. Okay, now, as a matter of practicality, we don't, I, I, I'm not sure about other developers. I don't tend to use inheritance that often. A bit of a strange warm for me I guess. But you will see it used absolutely everywhere. So I'm going to give you a very basic example. In the Android system or iOS. Even in Android or iOS, when you open up a screen, what you get is a view, right? View is the basic class. View is also seen in something like a TextView, which shows you some text on screen. View is also seen in what other things do we have? An edit text. It's just a basically a box that allows you to edit text on the screen. A view is seen in an image view. So all of these inherit the view, which means all of them can use the functions and properties inside of you. And this is one of the most common places you'll see this programming for Windows, Mac, iOS, Android, the web. It doesn't actually matter. When you know something inherits from something else, then you can use all the functionality of the view. So for example, having done Android engineering for years and years, I know that the textView has a way for me to tap into when it's touched. Same thing with edit text, same thing with image view. So I can use the same basic code, which is something like set click listener or set touch listener. So I can listen out for when it's touched and then perform an action when the retouched and all of that comes from the view and not from the individual things. So that's how we avoid repeating ourselves in classes by using inheritance. 42. You Are Rich - Inheritance: One of the more fundamental concepts you've just learned, classes. But classes have a danger to repeat information. So I've pulled up this lesson from a couple lectures ago where I told you about classes. In this person we have an age and a name and a better person. We have an age and a name. What if we had a female person and a male person? But then we'd have ages, both would have names. Do you think it's a good idea to repeat code? And you know the answer already, you know the acronym dry. Do not repeat yourself. Well, that's what we would end up doing there. So inheritance is the answer to that problem. So let's create a new file, inheritance dot p y. And let's start with something basic, like a class called dog. And the dog has legs equal to four, and the Boolean has tail equal to true, right? So we've just described a basic dog. Now to show you the nature of the problem, we can have a camps legs equal to four, has tail equal to true? Unless it's one of those Wade tail is cats or dogs. Anyway, it's not one of those. Those are two basic classes. And of course we can access them in the same way. Dog dot legs. And of course, print our cat dot legs. And if we save and run all that, surprise, surprise, I've made a mistake. Somebody. What have I missed out? Closing bracket. What have I missed out again? I am asked to press to enter on the wrong bed. There we go. So forelegs and four legs. So we've repeated ourselves, which is a bit silly, isn't it? So inheritance is the way around this problem. So what you need to think of when you're making objects is, what is this, what's a fundamental set of parameters that's related to this object that is also applicable to all the other objects of this kind. So for an animal, you might say quadrupeds mammal, as in a mammal that has four legs. So let's create that class. Quadrupeds. Mammal. You could just call it animal to be short, sharp and to the point, legs equal to four and has a tail equal to true. So you've described a general animal. Now let's say we want to describe a dog, a particular breed of dog, let's say a boxer. We can say class boxer. Now if open some brackets here, which I said you don't normally do in classes within Python. But in this case you do because what you'd like the boxes to have, it's all the properties and methods that are available to quadrupeds mammals. So that's what you pass in. Quadrupeds mammal. And you don't have to open and close any brackets or anything like that. Just simply give it the name in the brackets and then create your class as you would normally. Well, we don't want to create anything else, so we're just going to pass to indicate that this class is empty. But of course, it's not empty because if I say print a boxer dot legs and I run that, It's printed four legs for that boxer. So this inherits everything in the quadrupeds Mammal class. That's Inheritance. Now it's, it can be a controversial subjects which I never thought it was until I started seeing people saying that they tended to avoid inheritance, but it is everywhere. Not quite sure their reasons for doing so. If someone knows, maybe they can tell me via comments, that would be great. Okay, so what else we got on the list? You can also access the properties as you've seen, but you can also change those properties if you so wish. So Let's say new box is equal to boxer and then new Boxer dot legs is equal to three. He's had an unfortunate accident chasing a lady boxes down the road like dogs day. And then of course, if we print the new boxes legs, that value should have stuck in there. So it should show three at the end of our list here. Okay, so that's how we access the values and how we change them, right? I think we'll leave it there. I will say before we. And this particular lesson, accessing properties directly in a class is generally not a very good idea, but perhaps that's something I'll get to in this course, perhaps not, we'll see if it fits with the current curriculum. Okay, on, with the task for inheritance. 43. Inheritance in Python - Task: Right, so your task for this particular section is to follow basically the same idea here, but there's a slight twist at the end. So your task is to create a class that describes general fish. And I want you to give that fish two properties, just like we gave the dog and the cat legs and has tail. But in this case, you're going to just have two properties that are Booleans. One of them is, has gills equal to true and eats fish equal to false because fish don't generally eat other fish. That I want you to subclass that particular class to make a more specific fish. The shock. Sharks eat other fish, right? So clearly eats fish is now needing to be set to true. Otherwise your shock is incorrect. It's not a vegetarian shark, is it? So you have to modify that property in the base class. And how would you go about doing that every time you create a new fish so that you are always reminded to it. Now that second part is fairly difficult. And I think I've covered part of this with you. But I want you to go and think about how you would force the user to give the class and eats fish boolean property every time. So the user remembers to put that in. Good luck. 44. Inheritance Task - Solution: Ok, so the first part of this task was to create a class that describes a general fish. So class fish, pretty simple and straightforward, has gills equal to true because most fish have gills. Iit's. Not East eats fish equal to false because most fish, I think most fish don't eat fish. Now what happens if we want to create a shock? Shock inherits from fish, right? Fair enough. Now remember I told you when you create a class, there is a function called INET. Deaf underscore, underscore in it. Whoops, underscore, underscore in it. Like so. So you remember seeing this before? This always gets cold when we create a class. And all the Super does is make sure that all the code that sits behind this actually happens before you add your custom code. This is called hooking into the lifecycle. So every time you make an object from a class, it initializes it, which means it has to go to a whole bunch of stuff that we don't really care about. But at each point along that journey of creating itself, you have the little hooks that we can grab onto, like the initialization hook. And we can put custom code in there according to what our needs are. You have to be a bit careful about those hooks, about how many times they get cold, where they get cold, when they get cold, et cetera. And it's something you need to get used to if you do mobile apps, Android, iOS, Swift, things like that. Because life cycle hooks are very, very important there. Okay, having gone on and on about that, what can we do with the shock? Well, because shock inherits from fish. We have access to eats fish. And we have access to that right from the start. So we can say self dot EatsFish is equal to true. And that's it. We've now set up our shock. So if I came down here and I printed out a new shock and asked it, does it eat fish? Let's find out. True. So whenever the shock initializes, it sets eat fish equal to true. Now the second part of this puzzle I gave you was, how would you ensure that the user doesn't get this wrong? Well, what we've just done here is it's correct. You know, you can't really point at a particular problem except I can, because these problems have caused me problems. You making a shock. Sets eat fish equal to true. What if missed? The other developer comes up to fish and says, we should give this fish more properties. We should say under one KG. Equals true. Well, clearly that's row. Okay? But if you're the guy that's making the shock and not the fish class you don't know is change that. In fact, you don't particularly want to dig through someone else's code. Do you? See You never know that's happened. Unfortunately, later on, the guy who's made the fence user interface and really sold this application to your boss. Says, Here we go is the shock under one Qila. What's this? Oh yeah, a shock always weighs less than one kilo clearly. Okay. So what we would do to get around this problem is I'm going to just remove the key level requirement here because it confuses things a little. We're going to set, eats fish in a different way. We're going to pass it into the init constructor. Eats fish. And then we set self equals self dot EatsFish equals the EatsFish we just passed in. Now the class knows the difference, right? It knows this is local. So reference this one at the top. Okay? It knows this has self before it. So it's referencing the eats fish that's part of this class, which is actually part of the fish inherited class. Now if we run this, we should get an error. There's our error, a type error in it's missing one required additional argument, eats fish. So it's saying you tried to make a shock, but you didn't tell me if it eats fish or not and you have to so shock. And there you go. It asks you for it. So we can drop in true. Then it's gonna make it, and then it's going to print it out so we can fit all those in the same line. So now the shock eats fish. Now got a final question. My final question is, what could go wrong here? Is, is there anything that's obvious or not obvious to you? Well, what could go wrong is what I already said could go wrong. Mr. Tommy, developer comes down here and it says on the one key equals true, we still have the same problem that we don't know what is required of us when we make a shock. So these things are actually going to carry through. You can argue that under one kilos should not be set as true because that is not true for fish. So whenever you create what's called a base class, which is what this is, make sure you put in properties that are always true for that base class or that you explicitly set. So the base class you can actually initialize with other properties. We're not gonna get into that right now because I'm trying to keep this relatively simple for you guys. But these are all things just to think about in the future. With software development. The more accurate you are at describing classes, the less trouble you'll have later on when you inherit from those classes. Okay. That's that one done. 45. Shh Its a Secret - Encapsulation - Explanation: Let's talk encapsulation. So far we've looked at classes, functions, variables, stuff like that. Let's say we have a class which is to do with getting data from a server. And inside that class we have a variable which stands for the actual data. Okay? So this is quite common. Ignore all the other stuff that we have in there like, you know, the actual server code. It's just the variable we are interested in. For now. Then you have a different class. Well, that's awful writing class called manipulate the data. And inside this manipulate data class, you have a function to change the data. Right? Now, you already know that the data are contained up here. The immediate temptation for people is to use that data directly linked between the two classes, like he said. Right? So that's what, that is. We are changing the data in the get data class using the manipulate data class. Can you see why this is a problem? Well, hypothetical scenario. Here's one class and you're running app. Here's another one. Here's another one. Here's another one. Here's another one. Here's another one, another one. And this is going on, you know, thousands, maybe even millions of times. You have a variable over here. And everything is changing that variable according to its own schedule, according to its own needs. The problem is, you're never quite aware of what that variable is because it could change anytime. And this gives way to what we call spaghetti code. So we've got so much stuff interacting with other stuff that we need some way to tame it or and the solution for that is encapsulation. So what is encapsulation? Well, it can be summed up using a single word, say class. Data. We had our variable of data. That single word that you need is private. Ok? It's not the same in every language. Every language has its own idiosyncrasies around private. But basically what private means or the equivalent in the language you're studying is that no class outside of the get data class can access this variable. It's private to this class. Now we can be sure that nothing is coming along and just changing this to whatever it wants to change it to, it's consistent. So without software engineering, we want to aim for consistency across the board. You have a private here. The opposite of private. Might be public Far. Let's have public data. So this implies that this is accessible across everything. Okay? So any other class can come along and say, hey, this is public data. I want to do stuff to it. I want to read it, I want to write to it, I want to change it. So on and so on. The other side of this is the following. So let's have, again, let's have a class. I'm just gonna do short names now, get data. And in this class of get data, what are we going to have? We're going to have a variable data. And actually, you know what we're gonna do, we're going to make this variable private data. But we can split that up into two sections. So what we can say is private data concerning write access, but we can say public data concerning read access. What does that mean? Well, if there is a bit of data in the class, any other classes that are accessing it. If they just want to read it, they will get approved. If they try to write it, they will get disqualified from doing that. Now, if you've ever used C-sharp, which I've said before was my favorite language. These are called guesses or successes. So if we get something, we can read it. If we set something, we can write it. In many languages. These ways of doing your getters and setters are quite different across the whole board. But it's important concept to know. And it's important because you might work with a team. Now you can imagine a team. He has team member, one is team member to his team member three. Team member one writes some code. Team member to write some of his code and see Member three rights some of his code. How does team team member to know what he can and can't do with team number 1's code. What he's going to look at the code and say, I can't access this to write it, but I can read it. Same thing with three. It'll look at number twos code and say, well, I can write, I can write it and I can read it. So I'm implicitly allowed to do that. You still wouldn't actually want to do that. I'm just giving you a regular example if you'd like. So that's the power of encapsulation. We are hiding away functionality variables. Actually, I haven't told you about the functionality bit. Have I say we've got our class, whatever, whatever. We can do the same private functionality to functions. So we can add the private keyword to these. We can also add the public keyword, usually though, functions. If they don't have private in front of them, they are automatically public. Ok, so functions are really the way that you interact with the outside world. Other classes. There is another way of doing that, which is using an interface. I'm not actually going to get into that right now. I think this is enough for you to understand now and practice. So the two basic words you need to know, our private or public for encapsulation. 46. Hide and Seek - Encapsulation: The last time we talked, I talked about inheritance. So essentially this little task of setting a fish class and then making a sharp class that inherits from the base fish class. In this phase class, we said eats fish equal to True or whatever value we passed in. And I said to you that's not a generally very good idea. Because if you start changing things in a class whilst this looks simple. Later on, if you want to use the same object that you've created from the class and you're changing it from over here, from over here, from behind you, from in front of you. You can't actually keep proper track of the state of the things in the class. So it's quite dangerous to do. The solution to that problem is encapsulation. It's the art of hiding things or hiding implementations or hiding variables that shouldn't be accessible from outside of the class. So let's create a new file and see what this is all about. Right? Print and prints. What do we have on the prints? Let's have a class called Dog. And let's define a function in this class called Wolf. And what does this do? Well, simply enough, it'll print the word with. Okay, so now if I want the dog to, well, first I need to well it into existence. And then I need to call Wolf. Right-click run. I've made a mistake. Clearly. Deaf Wolf has no arguments. Yes, because I should put self run that our dog is alive and well, and whipping end has four legs. And this time, what if I don't want people to access self in here? Well, what we can do is double underscore at the beginning of Woof. Now let's try to run that. We get an error. And if I put double underscore here, we can run it. The dog doesn't work. It says, dog has no attribute on the school. Woof. Now, as I said in the little iPad tutorial, when I was drawing this stuff, many languages use the following keywords, private or public. Python is one of the languages that does not use that. In fact, Python leaves it up to you how you design all of the code, which is probably why it's quite a popular language because there are no really hard rules like the other languages have. The thing is, there's hard rules, are there for a reason? They've evolved over time to make sure we don't make silly developer mistakes, which were all liable to do. So Python. Has said, there's kind of pseudo standards that people have come up with. They said, hey, if I put double underscore in front of something, then I definitely don't want you to access that whoever is using that yourself included. In this case, we can't access it. But in the background, all Python is doing is saying, this is a hint, please don't use this. Okay? This particular interpreter is banning us from using it. But I think there are others that don't ban you from using it. All you need to know is that if the thing that you're defining, either a variable or a function needs to be private and not accessible outside the class, I E naught accessible here, put a double underscore in the front. Okay? So then it is private. Now you have seen this somewhere else, double underscore in it. Remember, whenever you create a class, this is always cold. So you have seen that passing before. Two underscores at the end means an additional thing. Don't worry about that for now. So that's effectively how we make this private. So that's inaccessible. But I can have wolf here, like we had before. And I can print again. Here, I can print internal Wolf. And I can run them both onto different dogs. Run them. So we get a wolf. And then the second one, of course, gives us an error as it well should. But if I comment this out by putting a hash in front of it, everything will run fine this time. But notice inside here, if I'm inside the class, then I can call self dot. If I can right-click and run that. Now we have an internal woof. So externally, I've said de Wolf, the dog goes, okay, I'm gonna whiff, and then it calls its own method in here. Now there are times when you might want to do this. It's kind of beyond the scope of this for B to explain when, because you need a very specific example, we might bump into one along the way. I'm not so sure at the simple level will currently Tolkien. But there are times when you definitely want to do that. Okay, so just think carefully. Remember how I said, you arrange a class according to the variables and the functions fits in that theme of the class. Well, it's the same thing with making things public or private in a class. You make things private that you don't want accessed outside. So a classic example is something like that, right? An update function that gets more data or whatever it is. Update is probably only related to the class internally. So you would probably make that private. But again, it's not a hard and fast rule, depends on your application. Okay, so we've dealt with dogs. How about cats? So class cat. Cats have four legs and they scratch you with all of them. And let's make a Cat object. And let's say the cat has now seen a lady cat. It's run after it and it lost a leg on the road. And just to prove it to ourselves, tell me how many legs this cat has. Its lets run it. With cat ran away, go run over in the route. Not only has three legs, pull can, can still scratch the dog lab. You find that weird how cats always have the mental upper hand on talks. Anyway. Right? Let's make a better version of this class. Because remember what I said a couple lessons ago is that if I have lots of different objects or I have rather, let me rephrase that. If I have an object called cat somewhere and I'm allowed to modify the variable inside it. To my heart's content. What we start to get is spaghetti code. Lots of things, changing other things all, every which way. And so you can't really keep track of your state. And if you get a bug, you don't know, really know where the bug comes from. Say, you know, you might expect a cat has four legs and somehow spitting out three because it would change somewhere else. So it's a bad design to modify these things directly. Ok, so let's make a class of better cat, or rather a class of private cat, which we're not gonna do inheritance in this one, we're gonna put the double underscore in front of legs equal to four. And then we're gonna make a private camp like is. So we're going to try and sets the private cans dot underscore legs. And you'll notice it's not coming up in my auto complete. And if I run this, we actually get nothing away. I should really print it. Print private cat dot. Nothing there, underscore legs. And you'll notice it's actually done it. Right? So what I said before, where we couldn't access the dog and the wolf. In this case, the Python interpreter is acting like I said it would, it's taking this as a hint, right? But if you set legs here, it's going to ignore you and just do it anyway. Because it assumes that you are a responsible adult and you wouldn't access something that is not available under autocomplete, right? Okay. So other languages will enforce private variables rigidly. You can't compile your program if you've made the variable private. And it would be something like that with private spelt correctly. Python on the other hand, says if you mark it as private, I'm going to leave the choice to you, whether you modify it or not. But as programme is usually, if we start typing something and it's not, it doesn't appear, we tend to leave it alone. So use the underscore as a warning to yourself not to access that thing publicly. But Grant you say, I want to change the number of legs of the cat. How can I do it safely? Well, let's have a class called best cat. And let's set private legs equal to four. Now the way that we're going to access this legs variable and change it is by making a function. And we make it clear that this function changes the number of legs. So set numb legs. Because we are in a class, we need self and we need the variable, we're going to pass it. And then we say self dot numb legs. Self.age underscore. Legs is equal to numb legs. Now we can go ahead and create best cat. We can say BC dot set numb legs. And you'll notice this appears for us as five, we're lucky Ken. So now we can actually print best cat dot underscore. Legs. Leg still doesn't appear. But, but why are we not bothered about accessing this variable? If we just want to read it? Well, if we just read it, nothing changes, right? We know messing with the state of the program. So reading variables is a fairly okay exercise. If you want to be really strict with yourself, and I wouldn't recommend it in this case. You can have get numb legs. And then of course you would return self dot legs. So that is one way you could do that, or you can just access it directly. So reading is okay. There are a couple of very edge cases when reading something might be an issue, but we'll leave that out for now. It's really edge cases. You never really run into them. Okay, so if we save that and run it, ah, I was wrong. So that you find this weird. That you can actually write the underscore legs, but you can't read it. It just won't let you. So as it seems, get numb legs is what I need to run here. So now we have five legs in this best camps. Looking at my notes here, I know what it is. Okay. What we have here is a Python interpreting our private code, not as a way of preventing us from getting it. What Python does is it obfuscates the name. That simply means it changes the name of legs. So if you explicitly want to access these legs variable, what you can say is BC, and we are looking at my notes, Yep. Dot single underscore, best cat, underscore, underscore legs. So now that five should get printed twice, and it does. So what does the Python thingy do here? Well, it adds the name of the class before the name of the variable, so changes the name of the variable y. It does like this. Does it like this? I just don't know. We don't do this in any other language that I know of. But Python is the most popular language in the world right now. So let's leave it be Shall we? Okay, so that's it for encapsulation. What I want you to remember because I know people don't remember the exact codes and things. So what I tried to do at the end of each lesson is give you a concept to remember. Encapsulation involves the hiding away of unnecessary data and unnecessary functions that shouldn't be exposed to the public, the public being your program. Now, I'm not going to give you any tasks for encapsulation because it's something you need to know about and it's something that comes naturally. We're going to skip the tasks because there are couple of sections left and you're coming up to the very big task, which will be at the end of this entire course when you are going to make a fully featured, as in it's got three features. Actually four features, accounting app for a coffee shop. Believe it or not, you have all the skills to do that. But before we get there, there are a couple more concepts I need to show you. 47. Tell Me What to Do - User Input: You are missing one final concept before you're ready to take on the world with your Python software. And that is the concept of input. What do we mean by input? Well, allowing the user to interact with your application. It's all very well printing out messages to the command line. But eventually you're going to have to ship your software to and end user who needs to interact with it. So you have to give them a way to interact with it. Imagine if you had to reprogram your Android or iOS phone every time you wanted it to do something. I think Steve Jobs would be would have been seen as a genius if he'd allowed that to happen. So what we're gonna do is give our user that ability to interact with our app just via text on the command line. For now. I know it's just text entry, but there are ways of detecting what the user enters in the text entry. And actually text entry can actually be faster than a graphical user interface. Have you ever seen people, accountants tallying stuff up, which is a hint as to the project that's coming your way. So they're really, really quick on the number pad is like to enter, to enter. Much, much quicker to use text entry sometimes. So how do we input stuff? Well, it's real simple. We simply say input a vats it. If I run this, I'm gonna put my print at the end. As usual. As usual, the one I always forget. Run it. We've got nothing but you'll notice it hasn't exited the program. It has run everything, but we haven't exited. If I type something, press enter. Now we've exited. So what the Python program does is wait for the user to put some input in. So what are we going to have? Let's have enter your name. And of course I should be putting quotes around that. And I've put a space after the colon. And that will be obvious why in a second. There we go. It is just receives some input. How do we get a hold of the input in the program? Well, again, just set a variable simple as that. And then of course we can print that name as the last thing we do. So it's clicked down here, ground into very GO simple as that. Now with this Python file, if you have it outside and you pass it to someone, they can just click it to run it. And they will get a terminal that appears like a Windows PowerShell or something similar. And they'll be able to run this program nice and simple. Okay, let's make a function. So we're not doing a class right now. We'll, we'll do that later on, maybe in the task. So what does this function do? Let's prompt for number. And what's this gonna do? It's gonna ask for some input. It's going to return the input received from a user after we say to them enter a number. Brilliant. Then once the user has entered the number, we are going to add the numbers. So let's make a function to add those numbers a and b. Let's return a plus b. Okay, now we need a way to start the program. We need to run the number adding program. So let's have R1 add numbers. Whoops, I forgot to put deaf in front of that. Run at numbers that needs no inputs. But this is going to control the flow, is going to manage the flow of our application. So we need two numbers to add them, right? So a equals prompt for number, b equals prompt for number. What's the answer of adding them? Is ADS nums a comma b. And then I want to show the output of answer. Now we haven't created show output yet halfway. But this is what you'll find yourself doing very often when you're making software, you will call a function that doesn't exist yet. Because you say, well, I know what I'm going to name it, so I'll just type it here whilst my cursor's here. And then sometime down the road, you'll say, alright, let's make that show output. And it will pick it up for us as an a so we can add it. As long as we're not trying to run the software, then nothing bad will happen. This takes a message and this will print the message. Now forgetting to run at numbers, we should perhaps at the start, have a print. Let's add two numbers. Okay, what's the final thing we have to do? Well, we need to run add numbers. So this is going to run it, it's going to print something. It's going to prompt for two things. Do a calculation and then show the output. But you'll notice how I've divided application up into relevant functions. And all that flow of the program is controlled by R1 add numbers. Okay, now I, I could split a little bit of this up and architected in a different way. But we're going to leave it as it is for now. So run python file in terminal. Enter your name. Well, just whatever doesn't matter. We're going to have number one. Number two, the answer should be three, right? Those of you who said the answer is 12, your correct. And you're going, Ha, what's happened here? Well, when we input text to the terminal, guess what? It returns a string. So these are returned, a and B are returned as strings. What happens if we add strings? They just smashed together. They don't add like a sum. So we have a little issue here. We need to do some integer or maybe float conversions. So what I'm gonna do is add the numbers here. Float a, float b. We could do this elsewhere. We could do it in add numbers. It depends why float and not integer. Well, I'm, I'm sizing it for the worst-case scenario. They might have a decimal number in there or a very large number. So I wanted to be sure that I can capture it. Now, there are other issues with this, but let's not cover that right now. Let's just do whatever. Add two numbers, 12. The answer is 33, because this is adding a float, so it always adds a 0 to the end. Now here's a little question. What could go wrong here? Well, I'll show you what can go wrong. Stupid name thing. Number one. What if I make a mistake and I slipped my finger and I put the lesser w1 into DIA. Could not convert string to float w. That's clear. You can't change the lesser w two a number no matter how hard you wish. So what you need and what we're not going to do at this point is something to check the input. So you need to what we call validate the input. This is a very basic example of that, but it's something you will need to do throughout your career. The most commonplace you do it is when you get data from a server or give data to a server from your app, you need to validate the types of data that you're getting back. And then you need to decide what to do if the types don't match what you're expecting? Do you try to convert them? Do you give an era? What do you do? All of these things matter, and they matter much more than you can imagine, but you will come across those issues as you progress. Anyway. Enough of that, I sought to teach you inputs and I think that is what we have done. 48. Input in Python - Task: Ooh, I've got a good one for you this time. Your task, should you choose to accept? And I assume you except because you want to become a god like developer, is to create a program that controls the lights in your house. Allow the user to query the status of their lights. Then ask the user if they'd like to toggle the lights, IE switch them on or off. I want you to package all of this in a class. And here are the first few lines of code to get you started. A case. We have a class called light control, and the lights are currently on. We have a function that queries, are the lights on. If the lights are on, IE true, then we're going to return the lights around. Otherwise, we're going to return the lights are off. Simple as that. Now, I've just thought there is one other thing you need to know. Here we go. This is a line of code that you need to use in order to run this program. So you're going to have inputs is equal to inputs. What do you want? And of course, I always forget those, right? If the input dot contains light, then do something. Now this don't copy this code like in this section. This is just a little snippet that you are going to chop and change and move around and maybe repeat. So you can give the user a float to the program. So what this does, it asks the user for input. If that input contains the word light, then your program will say, okay, I'm gonna check if the lights are on. I'm going to tell the user. Then I'm going to ask the user if they want to turn the lights off. Your program will then check for the user's response yes or no, and perform the according action. Ok. I hope that is fairly clear. You know what I'm gonna do actually. In hindsight, I think this is fairly difficult. I'm going to copy the first bit. Okay. Yeah, there we go, that little bit there. And I'm going to drop this in. So we gotta run program. This is going to start everything. You'll call this. We get some input. What would you like to do today? If the input contains light, then we're going to print this, our lights on. So it will print either one of these depending on the status of the lights. And then it will go ahead and say, if the lights are on, give them the input. Should I turn them off? Yes or no? The user will enter yes or no. If the answer is yes, it'll set the lights on as false idol, switch them off and confirm that to the user. Of course, for this, you can say, now, I'm going to leave you there actually, I think I've given you enough. Your job is to write the next 12345678910 lines of code, including the execution line to start it all off. So nine lines of code below this section. So I want the ability to turn the lights on or off depending on what status they're currently in. This is kind of difficult, right? So I'd advise you to just make empty statements first say else. That put a little asterisk. So this is a comment, it doesn't get evaluated. And then type what needs to happen. So don't type directly in the code. Think first in English, as in the comments. Once you've got the English of what needs to happen, then type the code below it. It's a much better way to type code if you think logically in your native language, in my language, English, then once you go beyond that, you can translate it to code. And that makes it much easier to code. You will get to the point where you can just whip out some code. But even now I find that typing the English makes my code much cleaner and more readable. Ok. Good luck and don't start the next video until you've had a good go at this. 49. User Input Task - Solution: So how did you find it? You didn't just skip to this video, did you? Because being a developer is all about sitting there and frustration and tearing your hair out, wandering what today, you've chosen the right career. Now I'm kidding, you really have chosen the right career because that's where the whole world's going. And you're gonna make off like abandoned when people are paying you a $100 and our easy maybe 200 if you're a specialist. Right? Let's run through this little section, this bit I explained. So we're not gonna go through that. First, we ask the user, what would you like to do if the user has something with the word lighten it. So this is kind of a trick the user might type. I need to turn off the lights. And this is going to detect, Oh, it's got, lighten it, something to fix his options, right? So this is AI, but really, really, really cheap version of AI that just detects a word and says, what I'm going to give you two options based on that word, no matter what you write. I could write a whole bunch of French in Japanese, the word light, and I'd get the same responses from the computer. So if it asks for light, we're going to print the status of the light so the user can see it. If the lights are on. We're going to say, shall I turn them off? And then we're going to hint at what they should do. If the answer they give back is Yes. We're going to set the lights on variable to false, hence, self dot lights on, which will flip that. And then we're going to tell them, hey, the lights are now off. What else needs to happen below this? Well, let me look at my little answer here. So if the lights are on, we're saying, Shall I turn them off or else the lights are already off. So we should say, shall I turn them on so we can copy this line of code. Now I know I said about copying code for the purposes of tutorials. It's sometimes handy just to break the rules. Shall I turn them on? Yes or no? And then if the answer again is equal to yes, what do we do? Self dot lights on is equal to true because we flipped the switch for them. And then of course we print the lights are now on. So they get some confirmation. Okay, so what we've done here is we started to nest our if statements. If contains light. So we know in the light subroutine. And then we've dealt with turning them off or on. What do we need to do? Let's go back over here. At this point, L, if let me just check, I've got this indentation, right? The inputs dot contains. That's something else. You know what we'll do first? We'll do else. So if there's no input for light, well, we can't do anything because that's not our program, right? So we got a print. I don't know what you one man. Try again foo. Okay. And then we're going to use that very dangerous property called recursion, where we call the function from inside itself. So self.age run program. Okay, it's a kick this off. Let's make a new lights control dot run program. Here we go, right-click run. Okay, we've still got the name thing from before. We can ignore that. We can ignore this two. What would you like to do today, sir? Wu? I'd like to turn on lights. Now, light is still contained in lights cell. It'll pick that up. The lights around. Answer shall I turn them off? Yes. The lights and our program ends. We can try that again. So skip this first bit from the tutorials. What would you like to do today? Gobbledygook into, I don't know what you want, men, try again. Foo, What would you like to do today? Lie. Why still doesn't know what we want? Set? That is your very first basic program. Now I should say, the program will keep running until you find the break point. It's not good design to keep running it until the user does what you want. You want to give the user the option to close your program. One way you can close programs in terminal is by pressing Control C or Command C on Mac or something like that. Same thing on Linux, I believe. And it will kick you out with a keyboard interrupt, ok, so you can control c. But we don't want to do that to use it, Dewey. So what we're gonna do here was the bit I hinted at earlier. L, If the input, it contains the word exits. What are we going to do? Well, if you think about it, if we don't call this and we do coal exits, our program will end automatically. If we just leave this empty, it'll flip out to the end. And that's it, finished. So Festival, I'm gonna get rid of this very annoying input here because it is bugging me. All right, and now we can run our program. What would you like to do today? Blah, blah, blah. To know what you mean, exit, done, we are out. So optionally to make this better, under the exit command, we could actually print CIA. Run that. Exits. See, yep. Okay. So we have a you just created with me a little application. This is a fully featured application because it turns lights on and off. Lights. The lights are on. Should I turn them off? Yes. The lights and above? Of course, if the lights were flipped to false, then we could answer. Well, this would say the lights are off. Shall I turn them on? And we could answer yes. So what you could do as just the final addendum says, we won't do in this one. You could leave this program to loop on itself all the time. So after you've turned the lights on, again, you can self doctrine program. And if you've turned them on self.age run program. Okay. What the hell? Let's just go for it. What would you like to do today? Light lights range like turn them off? Yes. The lights and our off. What would you like to do today? Light. The lights are off. Should I turn them on? Yes. Enter. And of course, if I want to exit, just type exit. So you've created a piece of software. I'm not kidding. This is the basic construction of software. Variables, functions, conditional statements. We don't have loops and this particular software, but we could, you could have a loop of all the lights in the house. We've done some input. Now in reality, text-based applications where you input text, not that popular, but they do exist and they do have a place because they are simple and quick to make. We've made this in what, 20 minutes, 30 minutes. Pretty simple. Once you figure out the concepts in your mind, where this is going to come into play is when you are using Python or whatever language to make an application that allows you to click buttons, type things into textboxes, and interact with apps as you know them. For example, on your phone or on Windows or on your Mac. It's the same concepts, except we don't have these loops that run round and round, which is effectively what we create when we say run program over and over again instead with other software, because we're not running this loop around and around asking for input. We're actually waiting until someone clicks something or performs an action, and then our program responds to it. But all of these principles are still the same. And you will see them in every piece of software, on every page of software, and every couple of lines of software. It's just a question of learning what all the different lines mean. So now you have all the tools that you need to create basic EPS. 50. Class Project - Setting Requirements: Okay, we have reached the end of this particular course. Now obviously there is a lot more to learn when it comes to programming. But I think here is a good place to stop because my goal with this entire course was to teach you how to become a software engineer. So at the moment, you are still a budding prototype of an engineer, but you do have all the tools that you need to make software, some software with fairly complex features to prove that I'm gonna set to a project that's well within your capability at this point, assuming Hugh did all the tasks throughout the course. So let's make a new file. And let's call this project coffee dot p pi k. And I'm just going to paste in your task brief. So it's got a lot of tasks within this project that I want you to do. And the project itself is a Python app that does the following. You run a coffee shop. Software is needed to do a few things over the course of a day. First, record all the tail purchase amounts. Second, record all the ingredient and labor costs, IE the expenses. And third, get the app to show the user the income or the purchase totals, the expenses, materials and labor, and the profit income minus expenses. So there's a bit of maths in there as well. Finally, allow the user, now this is the difficult part of this task. Allow the user to save the income, expense and profit figures as that day's totals. Once that's done, the software should automatically start a fresh, new day without losing the previous data. Okay, so you're going to have to make use of classes. That's for sure because you have things like expenses, you have incomes, you have daily tallies, stuff like that. You're going to have to use functions obviously to do stuff, variables to store things. You're going to have to use lists to store daily values, daily expenses, daily profits. And you're going to have to do all of that was asking the user for input in a sensible way. Saying something to them like, hey, would you like to enter an expense and income? Or would you like to end the day or would you like to show the entire weeks tally? And then you give them some texts, they'll enter the text and you'll do what you need to do in the background of your project. Now, this sounds really difficult if you're new to software development, which I assume you are if you're taking this course. But this is not difficult at all. If you break it down logically like I've shown you throughout the course. So things like classes. So remember a class just does a specific set of things, stores a specific set of objects. Functions do one thing and one thing, well. And when you start to logically grouped things and order them wherever they need to be. And the rest of this just kind of comes out of the woodwork. And in the end you have a functioning app. So that's your task. What I'm gonna do is, first of all, I am going to maybe give you a clue. So let me look at my little answer sheet here. Here we go. So I'm going to start you on part one of the solution, which is this is a class called tally. Tally. If you're not a native English speaker, just means to add things up. You tally stuff up. We have a list for incomes and a list for expenses. And then, uh, currently we have a blank function which you need to fill in to add the income to this list of incomes. So tally just records incomes and expenses for the day. The other two methods you'll need here are at an expense. You might need to get the total income where you add everything in the incomes list, et cetera, et cetera. So what I'm gonna do with the solutions is break them down into pieces. Okay, so the next video will be the solution. So what I want you to do as this first task is just make a tally class thinking, what functions does this need to do? And then implementing those functions? And what things does it need to store, which have basically given you here incomes and expenses? So I'll see you in the next video for the solution to this first part. 51. Class Project - Solution Part 1: So where I left you off in a task setting was to create a class called Telling the keeps track of incomes and expenses using primarily these two variables. So the first thing we need to have here is how we add the income. And the way we do that is how we treated our lists way, way back when in this course we append some income. So this is just adding whatever the user has entered into the tally. Now notice we're not concerned about how this number comes across here. All we know is that it does at some point, and this is the class that takes care of the number. So that's an important thing to do in software engineering, which is to tease apart the responsibilities of various files of code that you have or classes of functions, and completely separate them. Okay? What you'll see reference quite often if you read about code or see other people's coding tutorials mind sometimes for more advanced people is separation of concerns. And all that means is what I've just said, which is to have only the relevant items in the relevant class. So you must separate things and have them talk to each other as infrequently as possible or, or have a defined way of talking to each other, IE and interface. So this is an interface when you make a new tally object and you call the function add income, what you're doing is saying, I'm going to communicate with the tally class in the way the tally class expects me to. Okay, what else do we need? We need a deaf to add an expense. Self expense, self.age expenses dot and it's the same function, right? Expense, so that adds it into the expenses array. Now what else do we need? Well, in the task I set you the third task. It was to show the income, all the totals, expenses, all the expenses and the profit. So we need something that tallies up that incomes array. So deaf gets total income. Now this doesn't need to be passed anything because it just works on the array that is inside of the tally class. So actually what you could do here, as we realized that these incomes becoming private is add these underscores in front of them. So which kind of hints that these are private and shouldn't be modified from outside the class. So get total income. Well, for i in income, we're going to do something with AI. We're going to add it up. So what we're going to do is first create a total variable which equals naught because the income is 0 when we start. And then we say income plus equals i. So that's going to add that income as we go. I should actually put, whoops, that I should put self dot incomes. And that should be total. I don't know what I'm thinking right now. Now, once we finish that loop, we are going to return the total. And that way we can get the total income from the day. Now just to be sure, I'm going to put 0, which makes total afloat because I don't want any confusion between integers and floats. And I'm going to copy the total income. Just like I said, you should never do. Software developers are all liars. They say don't do this, but they actually do it quite often. Get total expenses. Same total, but we need to use this on the expenses array and then we return the total. Now, I suspect there's a way of actually getting these two functions down to three functions, but shorter over all. And we can experiment with that because this is a project and this is all about making your code efficient. So you know, what I'm gonna do is down here, I'm going to have def, this is going to be private. So I'm putting to underscore so it can't be accessed outside of this class. And I'm going to say gets list, total self list. And this is going to be again, the total for i in list, as in for each item in list. Now you see what we've run into here. List is green, which means it's a reserved keyword. So what we need to do is change this to something like my list. And then we don't have that green problem. And then we add the totals. Like I said, and we do the usual Return of the total. Now, how do we modify these two? Well, that's pretty simple. We delete everything in here. Return underscore, get less total, self. List total. And this will be for the incomes self. I always forget the self pot. And of course, same here. Return, self dot, get total expenses. Self.age expenses, case. Just make sure these are all expenses. Expenses. Correct. So now we have one function that does the tallying and we have other functions that call out, they work out source, they work to this private function. Ok, now you can imagine if we expanded this program to have get's coffee income, get cake income, will all we'd have to do is pass over the kay caret or the coffee array. And this would do all the heavy lifting for us without having to copy all this code. So what you've just done there, what we've done is re-factor the code. We've looked at the code and said, this isn't exactly short and succinct. There's lots of repeats. So we're going to fix it as we go. So my advice to you is, if you start writing a program, don't aim for perfect at this dot. Just stop writing it. Ok, just think logically. Start writing it. You will refactor things like I just did as you go along. So what else do we need here? Def, let's get the profit because what? Because the coffee shop, if I can't get the Prophet, How do we get the profit? Or we're going to return something, obviously. And what is profit? It's income minus expenses. So self.delegate total income minus self.delegate total expenses, which of course I'll methods minus equals. There we go. Okay? So if I just run that, we get no output because we haven't specified any output yet, but we also get no errors, which is good. So that's the solution to part one hour tally class that adds up and records incomes, expenses, and spits out get profit, and Jolanta bonus lesson that refactoring tends to happen as you are coding. And stop the press. This is ground from the future. I'd already recorded this video that you're watching wearing the same T-shirt. I do wash them honest. And I discover it because I'm not a Python program that this is a class variable. Now, I did go back and add video when in the classes section of this course to explain all of this. Basically the short of it is, instead of what we have here, in order to avoid a later bug, the I-beam tearing my hair house about. You need to do the following. In the init. You need to set self dot incomes equal to that and self dot expenses equal to that, and then remove these variables. Now everything will be actually accessible in the tally class, self incomes and self expenses. So all of this should still work. So that's my little change from the future in the rest of this video, if you see the old version of this at the top, then by all means ignore that. Just change your version. Two what I have here, and if you're still wondering why, maybe you missed that video way back when when I said this is a class warning, say go back to the video with title and you'll see why we do this. All right, on with the show. Now the next part of this project is the user input part of the project. So I'm just going to type what the brief is here pot to create another class that manages the whole program. And this class will make objects from the tally class we just created. Maybe the new class can be called profit manager. And in the profit manager objects you can create one tally object for each day of accounts. So this whole tally we just created will be in charge of tallying a day of accounts. Also put the input into the profit manager class. Now you could actually separate this out, but I don't think it's necessary at this point. And then once you've done that, you've got the inputs from the user, modify the code to store the tally object for each day. Okay, so here's a little hint. Put that tally object into a list C, you can add new tallies for each subsequent day. A k. So what do I mean by that? Well, let me just do a little bit of the following four. You copy the solution code. So gotta classical profit manager. We've got a list that keeps track of all the daily tallies we've done. And we have a variable that says where we are in that list. Now this variable starts at minus one, because every time we set up a new day, we're going to add one to this variable, which means we'll actually start at 0 the first time. And if you recall, arrays and lists are 0. Index iii, the first item is at position 0. So that's the meaning of those two variables. Then I'm only going to give you the next line, which is to set up a new day. You will need to increment that by one. And you'll need to make a new tally that you deposit into that array or list. From there, you will work with that element you just put in the list with that tally. Now this is fairly difficult. So what I would say is work on setting up the new day first. And I'll come back to you in the next section with the new day setup and a way to check if that's actually correct. 52. Class Project - Solution Part 2: Right, so you have the tally with that little changed bits, the underscore incomes with Self. Remember this is an instance variable instead of the class variables that we had up here before. And then I gave you a little hint with the Prophet manager. Now again, I'm gonna do the same thing here in the init. I'm going to do the following. So it initializes the daily tallies and this self.age, yada, yada, yada, and self.age ARE areola. Ok. Now these are instance variables for the profit manager class. It's not as important because we only run the profit manager once as it's the interface to our application. Interfaces tend to have one instance of the class because they're the only thing that you interact with. You can imagine when you're playing the game, you don't have two versions of the game on two separate screens, do you just have one? And that's effectively what the Prophet manager is. It's the interface. So in that case it didn't really matter. And which is why I didn't find that bug earlier. Bug that mistake by myself earlier. Okay, so that's all sorted. Now we have to set up a new day. First of all, I've printed new day. What do we have to do whenever we create a new day of accounts? Well, we need a new tally. Where do we store the tally? Which is stored in our list of daily tallies? So, daily tallies dot because it's a list we can append. Append or what? A tally opening clouds. So now we've created a tally object for that day which is stored in the list. What else do we have to do while we've moved on by one day? So what we have to do is up the current tally position plus equals one. So now the current tally position, the first time we run this will be 0. And so it knows when I need to find today's tally, I look in the list at position 0. Okay, what else do we need to do? I am just looking at my solution code. My solution code includes the debugging printing that I added later. And Australia find this problem. Anyway. So it takes a bit of combing through, right? I've got a, another function here. I'm just going to copy paste these, save a bit of time. We request income expense information. Okay, so this is going to be the entry point of our app. What we could actually do though, is what could we do here? Let me just look at my code. Today's tally. Get input yada, yada, yada. Okay, well this is the entry point. I don't personally know the Python way of guessing the entry point to the app in a program, in a program in a language like C sharp, rather, you would go into the main function. Okay? But I don't know what Python is. Leave that as a task for you. Find out the main function equivalent in Python, jump to google, do some reading and you should be able to find that. But what this class, this function is gonna do is kick the proceedings of and how did the proceedings work? Well, first of all, we need to get some input from the user. So what I'm going to do up here is create a function that gets input from the user. So what this function will do is show a message and gets the user's response to that message. So return input message. So we can show the message to the user that saves us rewriting input everywhere I went. This is a classic example of why we separate these out into functions. Input is the Python three ways of getting input. Python two was different to that. I don't recall what it was. It's been so long since I've used that. Ok. So that's how get inputs. So what do we want? Well, let's ask the user for a command which is equal to get input or self dot get input. And what are we going to give the user? Well, what message have I pulled up on my one? I have the following bit cryptic, but it'll do for us. What would you like to record? An expense and income? Show the daily tally, Give me a overall report or end the program. So we're giving the use of five options. You can rename these. These aren't perfect names for the user, but in terms of entering them quickly, three letters is quite quick to Antescofo EXP, NTU number, done. Right? What's the first thing that we need to get here? Well, I'll just copy the code if the command contains. So we've done this before. Expense. We need to get an input where we ask the user to enter an expense. Then what we do is we get today's tally. We haven't set this up yet, but we will. And we get the expenses variable and we append to that. Okay, now what is the expenses variable? It's actually this double score income. And we shouldn't have that. What we should use actually is the ad expense. Get today's tally dot. Then you just love when people do coding on the fly. Okay, so we're going to add an expense and we're going to make sure that our variable is a float. Because it could be a decimal, as in pounds and pens, $0.$1. Okay. So what we need to get here is get today's tally. So let's make another function. We'll come back to this request income def, get today's tally. Now what does this do? This is going to return the current day's tally. All the tallies are stored in the list of tallies. Daily. Tallies. Of course, stop forgetting self. Bad habits, bad habits, well, good habits and other languages, regular habits. So which one of the lists do we want? Well, remember, we're keeping track of that. So we have the current tally position that keeps track of which one we are currently on. So that should work and it should allow us to enter an expense. At this point, we can test this. Okay, so that runs. And of course it doesn't ask for an input because I haven't made an instance of this class and I haven't called this. Neither have I set up a new day. Let me just check my structure of how I did it here. Okay. You know, what we could do is come up here and we can just call setup New Day. Right in here. Cross our fingers. Hope that works even though it's defined below it. Ok, so let's make our objects. Let's call the following copy paste. Remove that one, we don't need it. So we're making any profit manager program. And then we're saying, stop the whole thing of so we're going to run that new day. What would you like to record where we only have expenses at the moment, so I'll press enter and to the expense 9.9, enter. Done. Okay. So that works. It appears to work at least. And what we can do is check that. So we can say print self.delegate. Today's tally dot gets total expenses. So right-click. Run python file. Let's record the EXP enter. Let's put 89 this time and we should get 89 spat out. Get total expenses. It's because I change something up here. So get total expenses. Something very strange going on here. That's because of being an idiot. You probably saw me do this. I've put the wrong thing and here I should get the list HOTPO. Run python file. Let's try this again. Exp, you're getting real bonus information for your cassia, ladies and gentlemen, because because you're watching me debug an app life, this was working fine yesterday. You change a couple of things. And this is what happens. So 89, enter. There we go. We have the total expenses as 89. Okay. Close that, fixed it. Maybe. Okay. So now we're able to enter an expense. So let's follow our own logic. Let's enter an income. So what we can do is basically copy this. We can refactor the code later on if we so wish. Else if the command contains income, we're going to ask the user to enter the income. I'm going to change what these words are, just so we don't confuse ourselves. And then we get self gets days tally. We are going to add an income, which is the float, Inc. a. K. And then let's, Let's do get total income as a sanity check. Save that, run it. Let's record an income of 900 and there it is printed out, confirmed to us. So that works. I'm just going to remove this print stuff because we don't need those anymore. Now what's next? We've got show. What is show? Let me just check out my notes here. A k. Let me copy this over. So if the command contains show, the idea behind this is to show the user the summary of just today's money. So I'm going to create a function called show daily amounts. Now what do we have to do? Or we'd like to show the user the expenses, the income, And then the profit, because that's what you're interested in as a business owner. And to save the hassle, I'm just going to drop in a whole bunch of prints. Now, yes, in reality, we could squirrel away these prints into their own function, right? So that is worth doing. What I'm doing here. I'm not gonna do it now though, to be honest, because I'm just trying to teach you guys and I want to keep it relatively simple. So what we're doing here is getting stays tally, getting the total expenses, total income, and then get today's tally get profit. So the get profits we've done here, income minus expenses. Okay? So that's show daily amounts for show. Now, what's the next thing we have? End. So up here, I specified end. That's because we want to end the day and set up a new day. Ending days tally, starting a new day, ready. So that's just some output to tell the user when setting everything up again. So we call setup New Day, which is up here. So that Adds another tally to the array and increases the tally position to tell us is the end of the array. We can actually just access to the end of the array if we want. So this variable, Now that I think about it is kind of redundant, I'm pretty sure that enlists There is a way to access the final item in the list. And because they have a strict order, is always the same order, that should be no issue. So we don't technically need this. So I'm going to open a browser here, and I'm going to show you the kind of things that I do at ifdef. Run the web. Let's have Python access end of list. So StackOverflow is where you'll spend most of your life. There. We got some list minus1. I had actually read that before. Okay. So in order to get today's tally, we can actually remove all this. Let's see, I'm just going to copy that control f, control V to see where else it is. It's only at one position. So we're good. So what we can do is just drop in minus1 here. So we've whittled down our code to just append something. Here. You've got to have a bit of fun. What? You do have to have a bit of funding. Okay? But the point of that was to remove that redundant line of code. And again, you're just refactoring as you get going. Actually, I don't need that. I can do this. You can always add it back later if it turns out that you do need it, but we don't. Okay. So we've set up a new date. Now. This currently only allows us to run a single expense income show end. It's kind of useless because I have hundreds of customers at my coffee shop. And so I'd like to enter a hundreds of transactions hopefully. So what do we do? Well, remember that evil thing I told you about called recursion. We're gonna run it here. Request Oh, no, no, no. Self.age request, income expense information. So once we've run through these ifs and else ifs, we're just gonna run through it again. Keep asking the user what they want. So right-click, run Python file. New day, ready to rock and roll. Make them dollars. What would you like to record? So let us give an expense of 90. What would you like to record an income of a 110? So let's show o bang, we get an error. Tally object has no attribute, gets total expense. So where is this? Line 87. Where is that? A k that c gets total expense says get total income. That's correct. And get profit is correct. Ok, let's restart this. And expense of 90 and income of a hundred and ten hundred, one hundred and ten, and expense of 500. Let's show what happened. We have expenses, we have income. We have a total profit excellent program. Just what I need to know as a business user. And I've got 500 bucks to blow on an iMac display stand, which costs $1000. Apple, what were you thinking? Anyway? What else have we got? Well, we've got end. So let's try that end. What would you like to record? Well, let's click Show, because this end should have started a new day, which means we'll have 0 of everything and we do. So that's good. So here we can have an income of 12 at an expense of three. And then we can show that we have a profit of $9 in this new day. So we can then end that, start a new day. And each time we're adding a new day to that array. The final part that we're going to do is the report where we tally up this entire array and give the user a report for all of the days that they've got stored in there. But we'll do that in the next video. Right after I've made myself a nice coffee. 53. Class Project - Solution Part 3: Now part three of this app is to fix up this report. This is going to be the report that tallies up every day that we have in our array of daily tallies. And allows us to show the user all the profits they've made each day throughout the month. Okay, so let's make a function to do that called Show or daily, perhaps profits in this case. So what do we have to do? Well, we have an array, we have to loop through that array. So what I'm gonna do is actually separate this outer bits. I'm going to have a nice neat display for the end-user HER2 prints. And I'm going to print all daily profits or losses because they might have made a loss. Oh, there we go. Just to make it clear, that is the figure that's about to be displayed. And then I'm going to print self dot, get profit totals. Now let's make that function. Def, get profit totals. Now in here we're going to loop through that array cell. That's pretty easy. First of all, we're going to have a profits array, which is going to store all the daily profits. And then we're going to say for what is it? Let me look at my code's T in self.age, daily tallies. We're gonna do something. We're going to have profits. Dot append. And now how do we get the daily profit? Well, that's really easy. T dot, get profit. Really that simple. And what you're starting to see here is how applications come together. If you start from a logical point. So you can just pick something really small, like a class Vitale. And eventually, when you get these big grander ideas, the grander ideas aren't more complicated. There are just more parts, okay? So you'll end up in a situation where you go affordable access to that, because I've constructed my app in the correct way. Now it does take a bit of time before that actually gets through to yourself as you're learning. But don't give up. And the best way to learn is to make things more and more manifest apps, awful, awful, awful, awful. But one of the apps I made for a guy after two years of learning. No, no, that guy, I started after five months of learning. His app had 2.7 stars in the App Store. I can't tell you which one. But it was earning him over a 100 thousand pounds, which is like a $130 thousand every year, just in advertising. And I learned that a low start app isn't the end of the world. People will still use it depending on the content of it. So that's just my message to you to not give up hope when things like this look difficult and confusing. Just keep trying. That's the task. So once we've got all the profits array, we can return the profits. Simple. Now we need to add in that section up here in the request to income. Actually, you know what, I'm going to rename this. Yeah, I'm going to rename this. Can I refactoring VS Code? Lets try that to refactor, which we know refactorings available. We'll see deaf stopped program. Okay, that in other software like Android Studio, When you click Refactor h changes that word wherever it's found, which is very useful anyway. Okay, so that stops everything. So down here we need another LF for the report. And then what do we want for the report? Well, let me see what I wrote in my code to do Aaliyah, what we've done that haven't we? It's pretty easy. Self.age show old daily profits. Now we can right-click and run this. So let's drop an expensive one. That doesn't work. Well, they go approves that it works and I dropped in an incorrect thing. So it just skipped what I said and ask me again. So an expense of one and income of five. Show the daily $4 profit. Let's end the day. We got a new day and expense of ten and an income of 20. Now we can end that day. So we've got a new day, but with nothing in the new day. And this report will show the profit over three days, which it hasn't. What have I missed out? That should be working? Show will daily profits. What have I missed here? Self.delegate profit totals. Am I going nuts? What have I missed here? A k report. And that definitely works. Report, nothing. Well, let's control see that and explode it. Let's just try that again. Let's just type, whoops. Let's just type. Reports are not works. Maybe I didn't save it, whatever. Anyway, before we started, as you'd expect, profits, losses, 0's. So let's record an income of ten bucks and expense of five. And then let's end the data. Then let's record an expense of ten, an income of five, and that day. So all the profits in total. Let's have a look at report. We made $5 profit minus $5 profit and 0 profits so far today. So that's that, it's really that simple. Now, I'm gonna give you the most shocking news of this course. Someone out there would actually pay you to write a program like this. Something simple that they need to use are being paid for really simple stuff. What's even more amazing is that this program is nearly finished. Because I talking about functionality. Because what you would do is hear what you would have is a function. Now we're not gonna do this to save permanent. So this would save two database or save to server, or in the simplest case, save to something like a text file. And then to really finish the program off, you'd have definition load data where you load DB or you load server, et cetera, et cetera. Now there is some nuance to this. You don't want to load all the data into memory for obvious reasons. You might want to load a little bit by little bit. And to do that, you just change due to do something like no, not that you would change this. No. No, you can't change that. You'd get today's tally wherever I define that. Set up new day daily amounts here. So huge. You'd use your database or your text file or your server access here. So it pulls that data down when it's needed. And once you've done that, you've more or less got the workings of a proper application. Now I'm just going to remove that so I don't confuse you. But I think you can congratulate yourself if you've got even 50% of this. I know that when I started this stuff was extremely confusing and there was a lot of new information to think about. Whenever you are taking any new course in the future, I would advise you to come back to this course, especially that little explainer videos I did at the start on the iPad before each section. Because those are the fundamental building blocks. Given a few exceptions of every programming language that's object-oriented, even to some extent, a functional programming language, or to most extent, not that I've played with those and I don't really want to at this point. Anyway. So the final thing I'm going to leave you with here is, how could this be improved and how could you improve it? And I'm not gonna give you the answer for this task, but I am going to set u this task. When I get an input here, I get some text back, right? So I get my x ink show report and straightforward, if I run this program and I enter a word instead of a number. So expense, grant is an expense, I'm expensive. Enter bank, everything crashes. I want you to think about how you would sanitize that input. I have mentioned this before in the course. Just think, how would I change that input to make sure that it's a number? And if it's not a number, inform the user that they're big in Idiot, and that they need to put a number in to an accounting program. So good luck with that task. There'll be no solutions for it. Do let me know via the comments or whatever platform you're watching this on. If you manage to do this successfully. And don't forget to go to for more stuff like this live code sessions. I include all the mistakes. So beginner's, which I remember being one of, can see what coding life is actually like and how slow the whole process really is. But fun nonetheless. So all that's remaining is for me to thank you, which I'll do in the next video. When I convince you even more to come to because it really is the world's best place to learn code. Honest. You know, it is really is. That's why I made it. Anyway. I hope you enjoyed the technical part of this course and I'll see you in a second.