Coding 101: Python for Beginners | Alvin Wan | Skillshare
Drawer
Search

Playback Speed


  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x

Coding 101: Python for Beginners

teacher avatar Alvin Wan, Research Scientist

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

    • 1.

      Introduction

      1:52

    • 2.

      About the Course

      3:02

    • 3.

      Expressions

      9:37

    • 4.

      Variables

      7:54

    • 5.

      (Bonus) Guided Exercises for Variables etc.

      9:25

    • 6.

      Calling Functions

      10:58

    • 7.

      Project: Currency Converter

      5:53

    • 8.

      Calling Methods

      9:02

    • 9.

      Project: Email Reformatter

      3:05

    • 10.

      Lists

      8:36

    • 11.

      Project: Name Picker

      3:54

    • 12.

      Dictionaries

      4:56

    • 13.

      Project: Location Checker

      3:08

    • 14.

      (Bonus) Guided Exercises for Collections

      9:48

    • 15.

      (Bonus) Guided Exercises for Using Functions

      10:32

    • 16.

      If-Else Statement

      7:27

    • 17.

      Project: Birthday Countdown

      8:00

    • 18.

      While Loops

      4:28

    • 19.

      Project: Bacon Ipsum

      4:18

    • 20.

      For Loops

      5:17

    • 21.

      Project: Generate Password

      3:12

    • 22.

      Define Functions

      4:39

    • 23.

      Project: Secret Messages

      4:05

    • 24.

      (Bonus) Guided Exercises for Defining Functions

      9:15

    • 25.

      (Bonus) Guided Exercises for If, While

      11:24

    • 26.

      (Bonus) Guided Exercises for For Loops

      7:07

    • 27.

      Coding101 Conclusion

      1:57

  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels

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.

34,278

Students

152

Projects

About This Class

What You Need

The class is designed for anyone with little to no knowledge of coding. No prerequisite knowledge is required. Unlike other courses, you won't need to install anything on your computer either: All you need is a desktop, internet, and an hour of time.

To avoid installation, we use a website called pytwiddle.com -- it's free, doesn't require an account to use, and allows you to share code easily (by clicking on the "Share" button).

What You’ll Learn

You’ll learn the fundamentals of code using Python. However, unlike most coding courses, this class doesn’t give you an exhaustive list of minutiae; instead, you learn just enough to start using code. The goal is for you to finish the class with (a) a set of nifty tools, (b) the ability to write more nifty tools, and (c) the recognition of code’s value in automating day-to-day functions. You’ll cover the following concepts throughout the course:

  • Data types, expressions, variables
  • How to use functions
  • How to define functions
  • How to use methods and attributes
  • If-else statements
  • While loops
  • For loops

What You'll Build

Along the way, you’ll create a set of tools to demonstrate these concepts -- a wide set of tools that you can use out-of-the-box or with a small enhancements, to improve your day-to-day:

  • Currency Converter
  • Email Reformatter
  • Name Picker
  • Location Checker
  • Birthday Countdown
  • Bacon Ipsum
  • Password Generator
  • Secret Messages

Exclusive Resources

The class will include links to exclusive resources including the following:

  • All 8 completed nifty tools
  • 70 practice problems with solution walkthroughs (an hour of bonus content!)
  • Extra 27 practice problems with full working solutions
  • Downloadable slides, with access to all updated versions in the future
  • Links for further reading

Want to learn more?

Interested in creative coding? Check out my VR 101 (AFrame Nature Scenes) class.

Interested in data science or machine learning? Check out my SQL 101 (Database Design), Data 101 (Analytics), or Computer Vision 101 (Applied ML) classes.

Follow me on Skillshare to be the first to hear about more courses in these areas!

Acknowledgements: This course roughly follows UC Berkeley’s introductory computer science textbook: composingprograms.com. B-roll used in introductory video CC-0 licensed by Pexels (Karolina Grabowska, Pavel Danilyuk, Nino Souza, Oila Danilevich, Joao Adao, Distill, Mikhail Nilov, Steve Johnson).

Meet Your Teacher

Teacher Profile Image

Alvin Wan

Research Scientist

Top Teacher

Hi, I'm Alvin. I was formerly a computer science lecturer at UC Berkeley, where I served on various course staffs for 5 years. I'm now a research scientist at a large tech company, working on cutting edge AI. I've got courses to get you started -- not just to teach the basics, but also to get you excited to learn more. For more, see my Guide to Coding or YouTube.

Welcoming Guest Teacher Derek! I was formerly an instructor for the largest computer science course at UC Berkeley, where I taught for several years and won the Distinguished GSI (graduate student instructor) award. I am now a software engineer working on experimentation platforms at a large tech company. 4.45 / 5.00 average rating (943 reviews) at UC Berkeley. For more, see my Skillshare or Webs... See full profile

Level: Beginner

Class Ratings

Expectations Met?
    Exceeded!
  • 0%
  • Yes
  • 0%
  • Somewhat
  • 0%
  • Not really
  • 0%

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.

Transcripts

1. Introduction: A hard time getting started with programming. Lingo I didn't understand, theory I didn't need and set up that required installing random programs on my computer. I just wanted a simple, easy way to build. Building an awesome game, a studying website. I only wanted to learn the necessary parts of code, not memorize the whole coding encyclopedia. If you feel the same way, this course is for you. My name is Alvin. Today, I'm a research scientist at a large tech company, and I was formerly a lecture at UC Berkeley, where I taught over 5,000 computer science students on campus. This class is for any beginner to take. You could be a painter, a designer, a product manager, anyone. You won't need to install anything on your computer. To make it easy for you to get started, we'll use a free online tool at pi total.com. No accounts, no installation, just code. In this course, we're going to use a coding language called Python. Python is my language of choice for software engineering, cutting edge I research, web development. I want you to see how even simple tools, short coat snippets can benefit you today. Once you finish this class, you'll have the power to automate parts of your daily life with Python. There are two goals of this class. Goal Number one. I want you to get excited. Show you what's possible with just an hour of code. If you're already excited, you know what you want to build, even better. You're a step ahead. Goal Number two, give you just what you need to start learning. We won't go over laundry lists of coding utilities. I'll give you what you can't Google here so that you can ask Google for more examples. I'll give you the framework so you can ask Chat TBT for the details. I'm excited to share with you the power cove to share the same excitement and thrill. It's not some distant, hard to reach mouth. All you need is a computer, Internet, and an hour time. Let's give coding a try. 2. About the Course: Welcome to coding one oh one, Python for beginners. Throughout this course, you will learn not just how to write code, but also how to talk about code. We will emphasize specific lingo that coders like you use all the time. We will also go over ways that code can go wrong and what certain errors mean. First is our course website. All of our finished code and additional resources can be found at this URL. Note that I highly recommend viewing course resources and coding along on a desktop. Coding isn't very mobile friendly because of all the punctuation you need to write. Let's start with a few tips for this course. Tip number one, copy my code exactly. Many parts of code such as spaces and punctuations are critical for code to work. I will emphasize which parts of code are needed and which parts aren't. But to err on the side of caution, copy my code exactly. Tip number two, pause the video when needed. These aren't live lectures. So if you need time to process what I just said, don't hesitate to pause. Likewise, if I'm talking too slowly, then of course, you can speed the video up. The third tip is to please code along with me. You learn code by going through the motions and practicing. So if you also practice writing code in our interactive lessons, you'll take away a lot more from this course. To write code, you will use a website called pi Twitle com. I suggest placing your skill share videos and Pi Twittle editor side by side like this so that you can still see the video when minimized, I intentionally designed all the slides to have much larger fonts. I also zoom in 200% on my editor. My last tip is to ask Chat TBT, if you're stuck, simply copy and paste code into Chat TBT and include the error. You can also use any other AI service like Bing's copilot, Google's Gemini, or Anthropics Cloud. So you may be wondering, though, if AI can already write basic code, why am I learning basic code? Well, even though AI can generate code, someone needs to be able to read, understand, and pick between different options that AI provides. As a result, your emphasis is actually on reading, and understanding code. It just happens to be that learning how to write and speak a new language like coding forces you to understand deeply. This is why you're writing code that AI can also write, so you can double check and assemble the code that AI generates. And that's it for our brief introduction. One last note is that you should feel free to post questions and tips in the discussion section in Skillshare. I've seen the post there and you are all an insane community helping and propping each other up when something goes wrong. I am really, really grateful and simultaneously, very proud of the community here, including you now. So in honor of that, I've marked slides throughout this course that have incorporated student feedback. Feedraf from Coders just like you. So definitely post some discussions to help each other to ask questions and to be a part of this course's future. Welcome to the family. 3. Expressions: This lesson, you'll write your very first lines of code. Start by navigating to pi total.com. There's no need to create an account and it's completely free to use. We need to start with the types of data you can represent. Let's do this by jumping straight into the code. Just copy the code I have so you can see firsthand what your code does. First, here is the interpreter on the bottom half of the editor. The interpreter will read your input, evaluate that code, and return the resulting value. This blinking cursor means Python is waiting for our input. Let's add some code. Start with five. Hit Enter, Python evaluated, and then returned five. We can also have negative numbers like negative ten. Hit Enter, Python evaluated, and then returned negative ten. These numbers are called integers, just like in math class. We can also have decimal values like 3.14. Hit Enter, Python evaluated, and then returned 3.14. We can have an arbitrarily precise number like 3.14 926365, 6535. Hit Enter, Python evaluated and return the same number. These decimal values like 3.14 are called floats. You don't need to remember the distinction between integers and floats for now. But if you hear either term, just note that it means number broadly. So far, we've covered two data types that represent numbers. There are two more data types. One data type is text, which we call strings. To write a string, we need start and end. For example, here's hello. Between these quotes, you can also add punctuation. For example, I love watermelon. You can also include numbers. So I love 3.14. You can add whatever characters you want besides the quotes that you used to denote the string. So, for example, in this string, I cannot include double quotes anywhere inside of my string. Note that you can also denote strings using single quotes instead of double quotes like this. These are all valid strings. Now, remember, quotes always indicate a string. For example, 123 is not an integer. It's a string. To help distinguish between this and an integer, you might hear this called a string of fied integer. Likewise, 3.14 is not a float. It's a string. We might call this a string of fied float. Our final datatype is just true or false, which we call Booleans. For example, here's true. Notice the capital T, and here's false. Again, notice the capital F. If you forget to capitalize the first letter, you'll get a name error like this. We'll explain what this name error means in the next lesson. These are the four data types in Python. Let's now see how to manipulate these data types. To combine and manipulate data in Python, we need operators. For completeness, I'll cover several categories of operators. However, there's no need to memorize the categorizations or even the operators I show you. This is really just to get you familiar with writing and reading code. Combinations of data types and operators, then make what we call expressions. Expressions can take the form data, operator data. Let's see a few examples. Here's a simple expression, five plus two. The spaces I'm adding are optional. They aren't needed for Python to work, but the spaces make your code more readable. I would recommend you also add spaces to build good habits. We input five plus two, and Python returns seven. We can also subtract five minus two. Like before, Python will evaluate five minus two and return the result. I'm being deliberate about the use of the word input and return. We input five minus two and Python returns the resulting value three. We'll see in a later lesson why returning is such an important concept. We can also divide and multiply. Weirdly enough, you can also apply math operations to strings. For example, you can concatenate strings together using addition. Hello, plus world. As you can see, the strings are simply concatenated, making one big string hello world. However, note that you can't concatenate strings with other data types. For example, hello, plus one is invalid. Here, Python complains. You can only concatenate strings, not integers with other strings. We saw different math operations add subtract divide and multiply. These are arithmetic operators. We can also compare data with each other. For example, we can check if one value is greater than another, like five is greater than two. Like before, Python reads the input, evaluates the expression, and this time returns true. This true, as we discussed before, is a Boolean data type. We can also check if two values are equal, using two equal signs like five is equal equal to five. Notice that we use two equal signs to check if two values are equal. Don't forget there are two. We can also compare other types of data. For example, we can compare floats. We can also compare strings, or we can compare booleans. These operators, which compare two values are comparison operators. We can also combine bullions for our third category of operators. For example, we can check if both bullions are true using and. Or check if either bullion is true using or. We can also flip a ban from true to false or vice versa, using t to turn into false. Let's combine these new operators with the comparisons we made above. For example, we can check if a number is within a certain range. Let's say we have the number three, and we want to check if three lies in the range two to ten. We would check first if two is less than three and compare if three is less than ten. Python evaluates this expression, two is less than three is true, three is less than ten is true. Since both are true, the entire expression evaluates to true. The interpreter then returns true. These operators, which allow us to combine Booleans are called Boolean operators. Those are the key operators in Python to be aware of. Using operators and expressions, we can now perform arithmetic, compare data, and combine Booleans. Before ending the lesson, here's a quick tip. Quotes always denote a string. This is a common misconception and an easy piece of code to confuse. Let me show you why that's confusing. What does the following code output, do you think? Remember from above, if there are quotes, the data type is always string. When we add strings, we concatenate them. Once we enter, this gives us the combined string one, two, three, one, two, three. Now, if I drop the quotes, then we get the expected behavior. This gives us two six. Remember that, always mean the string data type. Okay. Let's recap what we've learned so far. There are four data types. Integers and floats are both numbers. A string is text. A boon is true or false with capital T and F. We can combine data and operators to get expressions like five minus two or five less than ten. And finally, there are three types of operators that we covered, arithmetic operators like add and subtract, comparison operators like less than or equal to, Boolean operators like A or O. I know this is a lot of information at once. However, there's absolutely no need to memorize. For example, I will likely never say comparison operator ever again. I'll just say less than. I introduce these terms just to stay organized and familiarize you with what code looks like and what talking about code sounds like. When you hear words like bullion, float or operator, the words aren't new to you. We'll practice some more in future lessons, so we'll build familiarity together lesson by lesson. If you'd like to access and download these slides, visit this URL and good work. That's your very first pieces of code. We looked at the building blocks of code called expressions. In the next interactive lesson, we'll talk about what to do if we want to store data. In the next interactive lesson, specifically, we'll solve this with variables. 4. Variables: Let's talk about variables. If you remember variables from math class, they're basically the same thing. A variable stores data, and we'll see what that means by actually creating some variables. Specifically here's how to define a variable. Notice that define is an italics and color turquoise. This is intentional. Throughout this class, any text that is italicized and color turquoise like this is a special term that has a special meaning. In coder speak, we specifically say we define variables and assign them values. Let's now define the variable x and assign it the value five. X and blue is the variable name. Equals in black is the assignment operator. Five in orange is the value. Let's try this now. Okay. In your editor in the bottom half, we have the interpreter. In the interpreter, we'll define the variable x and assign it the value five. Like before, the spaces here are optional. I've added them just to make the code more readable. Just like before, however, I would suggest you copy these spaces two to practice writing readable code. Hit Enter. Notice, there's no return value when you assign a variable. This is normal. Now, you can confirm the value of the variable x by simply typing an x. This gives me five. Python read the input, evaluated the variable x, found its value, and returned the variables value, which is five. Now, let's try customizing this variable name. Here's how to pick a valid variable name. Your variable name could be an A. It could be a Z. It could even be Nyan Cat. There are many possibilities. In fact, your variable name can contain any number of letters, numbers, and underscores. No other characters are allowed. No periods, no spaces, and no dashes. Additionally, your variable name can't start with a number, but it can contain a number. Non CT is an invalid variable name, but NNT is valid. Nyan Doc CT is invalid, but Nyan underscore CT is valid. Let's try this now. Ny cat three is a valid variable name. No news is good news here. The code executed without errors since the variable name is valid. However, three Nyan Cat is an invalid variable name. Notice we get a syntax error. Three on CT is an invalid variable name because it starts with a number. Let's see another variable name, N. Again, this is an invalid variable name. We get a different error this time, but for now, ignore those details. We'll see later why and what this error means. In this case, Nyan dot CT contained a dot, which is an illegal character. The only punctuation we can use in variable names is the underscore, like Nan underscore cat is equal to five. And again, no news is good news. So far, we've assigned every variable to the value five though. Let's see what other values our variable can take on. Let's now see how to change the variables value. A value can be any of the numbers we saw before, like seven. The value can also be an expression like the orange three plus six here. To reiterate, we can change the variable name, the blue part, and we can change the value, the orange part. Anything colored black in these visualizations is fixed, like the equal sign here. Let's try this now. Let's now define the variable x and assign it to an expression x equals to three plus six, hit enter. Like in our slide, the expression is three plus six. If we now check the value of x, hit x hit enter, we can see the value is nine as expected. We can also assign to any other data types, such as a float, x equals to 3.14 or a string, like hello or a bulon like false. These are all valid values for a variable. Now, how do we use variables? Let's say we wrote six plus two. We know Python will return eight. However, this time, since x equals to six, we can replace six with x. Just like before, this expression will return eight. Let's try it. Let's assign a variable x to six. Notice the terminology. Assign x to six, assign it to ten, assign to false, we always say assign a variable name two of value. You should use this terminology two. Now, double check x is equal to six. Type in x, hit Enter looks good. Let's now use the variable x in an expression. Following our slide on the left, rewrite x plus two, and this returns eight as we expected. Now, here's a tip. If you get a name error, this means you have a typo in the variable name. For example, we have not yet defined the variable U. If I input, the interpreter evaluates, can't find the variable, and raises a name error. Again, I'm using the word raises an error deliberately. So far, we've learned that the interpreter can either return a value or raise an error. Now that we've defined variables, let's actually see one tip that I have for you. What do you think this line of code does x equals to x plus one. Don't hit enter yet. Here's the expression we saw in our interpreter on the right. Since we know x is now six, let's plug that in. This gives us six plus one, and the right hand side is now equal to seven. Notice that x's previous value was six. Now, x's value is seven. In other words, the expression x equals to x plus one increments variable value by one. Now let's see what this value does. This expression does, hit Enter, and now we can check the value of x. Indeed, x is seven. Long story short, the line x equals to x plus one incremented the value of x by one. Let's see the same concept applied to strings. Let's assign a new variable to a string value. Text equals to hello. Now, let's add a string. Text equals to text plus world. If we now check the value of the variable text, we'll see hello world. In this way, we can continuously add text to this variable. As a recap, you've covered how to define variables. You've also covered what makes a valid variable name. Variable names can only contain numbers, letters, and underscores. You've also seen different examples of variable definitions throughout the lesson. If you'd like to access and download these slides, visit this URL, and good work. This was again, a lot of concepts, and it's okay to feel overwhelmed at this point. You don't need to memorize everything. We're going to repeatedly use these concepts, and by coding repeatedly in the next few lessons, you'll incrementally get an intuition for right and wrong code. We now know how to assign a single expression to a variable. What if we want to modify this value somehow? The next lesson, we'll cover a concept called functions, which will enable us to modify values. 5. (Bonus) Guided Exercises for Variables etc.: Welcome to bonus content for lesson 3, guided exercises. In this video, we'll walk through exercises covering concepts from the last lesson. There are three steps. Number 1, I will present an exercise. Number 2, you should pause the video and try the exercise on your own. Number 3, after you've made an attempt, play the video, and I will walk you through the solution. The goal is to make you comfortable with using these coding concepts and hearing the terminology. Some exercises will start with practice, which means we're covering a concept that previous exercises have not yet covered. All concepts will come from the previous video. The next few exercises after practice will then be prefixed with quiz. This means the previous exercise already covered the same concepts. You should try these quiz exercises as a test of your knowledge. Let's hop right in. Just like before, start by navigating to repl.it/languages/python3. Let's start with question number 1, this is a practice question. Output 9 in the interpreter using only the number 3 and any math operations you want. Give it a minute to try. Here's the solution or here's one solution, I'm going to type in 3 times 3. Question number 2, this is now a quiz question. Output number 5 in the interpreter using only the number 3 and any math operations that you want. Give it a try. Now, here is a possible solution, I'm going to type in 3 plus 3 minus 3 divided by 3. This will give us one, this will give us six and we have 6 minus 1 is equal to 5. Question number 3, we now have a practice question. Define a variable called x with the value eight. Give it a try. Here we have the solution x is equal to eight. Question number 4, define a variable called y with the value of three. Give it a try. The solution here is y is equal to three. Again, these spaces are optional and these are just the convention that I've been following. Question number 5. Practice: Define a variable called z with the value five using the variables x and y instead of the number 5. Remember here x is eight, y is three. Give it a try. Here's the solution and we're going to now type in z is equal to x minus y. We are going to double-check that z has the value five, and indeed it does. Question number 6, this is now a quiz question. Define a variable called a with the value 11 using the variables x and y instead of number 11. Again, x is eight, y is three, give it a shot. Now we have the solution a is equal to x plus y, double-check that a has the value 11. Question number 7. Practice: Define a variable sound containing the string cluck. Give it a try. Now we have sound is equal to "cluck". Here I'm using double quotes, you can also use single quotes for your string. In this particular question, it doesn't really matter which one you use. Let's go ahead and move on to question number 8. This is now a quiz question, define the variable sound containing the string moo. I'm going to type in sound is equal to "moo", and hit "Enter". It's going to move on to the next question, question number 9. This is now a practice question, define a variable containing the exact string denoted here in red. Remember, you can use double quotes or single quotes to denote a string, and this case the string contains a double quote. Give it a try. Here's the solution, because this string contains a double quote, you'll have to denote the string using single quotes. Let's go ahead and define the string using single quotes. Again, this doesn't say what the variable names should be, so I'm going to call the variable name quote is equal to, 'and she said, "Yum!"', add a single quote at the very, very end. Go ahead and hit "Enter", and there is our quote string. Now, here I'm going to click on ''Clear'' in the top right, you don't have to do the same, but if you do, make sure you click back into the window and hit "Enter" so that you see the orange color to once more. Question number 10, this is now a quiz question. Define a variable containing the exact text denoted here in red. Give it a try. Here's the solution, I'm going to type in now, a variable quote is equal to, and because this string contains double quotes, I will use single quotes to denote my string, 'and I said, "Ew!"'. Perfect, hit "Enter" and there is our string. Question number 11. Let's go ahead and define a variable containing the exact text denoted here in red. Here's a curveball though, the string contains a single quote now. Give it a shot. Here's the solution, because the string contains a single quote, we actually need to denote the string using a double quote now, the reverse of what we did before, type in quote is equal to, "Euh, and then 'merrpppp' ", and there is our variable. Question number 12, here's another practice question. Define a variable b that is true if x is eight. Give it a shot. Here's now the solution, b is equal to x is equal, equal to eight. Recall that to check equality, we use two equal signs. Go ahead and type in or hit "Enter". To double-check that this worked, we're going to check that b has the value true because x is eight and is indeed true. Question number 13, define a variable c, that is true if x is greater than five. Give it a shot. Now here's a solution, c is equal to x is greater than five, hit "Enter". Because x is eight, x is indeed greater than five, double-check that c is actually equal to true, and indeed it is. Question number 14. Practice: Define a variable d that is true if the variable sound is "moo". Give it a shot. Here's the solution, d is equal to sound is equal, equal to "moo", and hit "Enter". We're going to double-check that d has the value true because sound is indeed equal to moo, there we go. Question number 15, here is now a quiz question. Define a variable e that is true if the variable sound is "yuck". Give it a shot. Now we have e is equal to sound, is equal, equal to "yuck". Because we know that sound is equal to "moo", e should be false. Type in e and hit "Enter", and that is now false. Question number 16, this is now a practice question, define a variable f that is true if x is eight and if sound is "yuck". Give it a shot. Here's now the solution, we have f is equal to x is eight and sound is "yuck". Hit ''Enter''. Because we know that x is eight, this first part of the statement it's true. However, sound is "moo", so the second part of the statement is not true, therefore, this entire statement should be false. Go ahead and type in f, and it is indeed false. Question number 17, this is now a quiz question. Define a variable g that is true if x is five and the sound is "moo". Give it a try. Here's now the solution. You don't have to do the same, but I've clicked ''Clear'' in the top right. If you do the same, make sure to click into the window, hit "Enter", and there we go. Let's go in and type out, now the solution g is equal to x is equal, equal to five and sound is equal, equal to "moo". Here we know that x is in fact eight and not five, so this first part will be false, making the entire statement false, go in and type in g "Enter", and it is indeed false. Now for a quick temperature check, how are you doing? If this was doable, that's great. If this was barely doable, as in you got half the questions correct or more than a third, that's also great. As we progress, you'll hear more of these terms and concepts repeated again and again and again. That's how you'll build familiarity. We're looking for familiarity, not an A-plus. Number 3, it wasn't doable as in you only got one or two correct for the 17, no worries. Believe me, I know what's that's like. I suggest during this walkthrough again or rewatching the previous video, you can do it. Regardless of where you are, mastery is when you can come up with your own questions. If you feel you've mastered this lesson, try to come up with a few extra questions and solutions. Leave them in the discussion section of the class, and your fellow students will thank you for the extra practice. That's it for lesson 3's guided exercises. 6. Calling Functions: In this lesson, you'll work with the coding concept called functions. This will pave the way for us to start our first nifty tools. Start by navigating to Pi total.com. First, what is a function? Think of the functions you learned in math class from grade school. At a very high level a function turns input into output. This isn't completely precise, but for our purposes in this class, this definition is correct enough. Here's the definition illustrated. Functions accept some input value and return some output value. For example, consider the square function, take in a number, and return the square of that number. Here we take three as an input and return three squared or nine. Here's another example, the absolute value function. It takes in the value of negative five and returns the absolute value positive five. Let's see one more. Here's a round function. It takes in a single float argument 4.35 and returns the rounded version of that number four, an integer. You now have a rough idea of what a function is by example. A function is a piece of code that takes an input and somehow transforms it into output. Now that we know what a function is, let's now see how do we use a function. To be specific, how do we call a function? Again, call is a special word. In Coder speak, we generally say that well, not use functions. Consider the absolute value function again. In Python, the function's name is just abs. Use parentheses to call the function. As a side note, calling the function means we execute the function. In between the parentheses, add any inputs that the function needs. We also refer to the input as an input argument or just the argument. In summary, we call the function abs with one argument five. Let's try this. Again, the bottom half of your editor is an interpreter. In that interpreter, we now call the function abs with the argument negative five. Parton evaluates then returns the absolute value of negative five, which is positive five. Let's try this on one more value. We can also pass in floats. For example, abs of negative 3.14 also gives us positive 3.14. Let's see more examples of functions to build familiarity with this format and terminology. Here's the round function. This function takes one argument and outputs the rounded number. To call the function, add parentheses and the argument. There we go. We call the function round with one argument 1.2. Let's try this two. Let's call the function round with the argument of 1.2. We input round of 1.2 Python evaluates, then returns the rounded value, which is one. We can also call round on our favorite number, 3.14. As expected, Python returns the rounded integer of three. Let's see one or the function as an example. Again, there's no need to memorize these functions. This is just the practice reading, writing, and talking about code. Consider the function max. This function accepts two input arguments and returns the larger of the two. To call the function max, again, add parentheses and arguments. When there are multiple arguments, we separate arguments using commas like this. And that's it. We call the function max with two arguments five and seven. Let's try this code now. Let's call the function max with the arguments five and seven. We input max of five and seven, and like usual, the space after the commas for readability. Python evaluates, then returns the larger of the two values, which is seven. Speaking of multiple arguments, some functions have optional arguments like round. Round optionally takes in a second argument, which corresponds to the number of digits to round two. For example, we can write the following to round Pi to two digits. To reiterate, the first argument is the number to round, and the second argument is the number of digits to round two. This gives us 3.14, which is rounded to two digits. Let's now expand the set of possible functions by learning how to import functions that other coders have written. There are two ways to import functions in Python. For simplicity, I'm just going to teach you one. Simply write from library import function. A library is a collection of Python code that someone else has written that we can use. And the function that's imported is just like any other function you've been using. Let's see what that looks like and how to use one of these functions. Let's import a function that can report the current time from time import time. The first time is a library. The second time is the function name. Hit Enter, and let's now call our time function. Notice this gives us a fairly large number. This is actually a number of seconds since January 1, 1970. We can call time again, and again, you can see that each time we call it, the returned value keeps increasing, although by small amounts. Let's use the code we've learned so far to compute the number of years since January 1, 1970. First, note that calling a function is a valid expression too. It's just different from the other expressions we've seen before. As a result, just like any other expression, we can assign the returned value to a variable. Let's define a variable called seconds and we'll assign it to the value returned by the function time. Remember, we use one equal sign for defining variables. This is a lot to unpack. On the right hand side of the equal sign, we call the function time just like we did above. On the left hand side, we have the variable name, and the equal sign tells us that this is a variable assignment. Hit Enter, and now the seconds variable contains the number of seconds since January 1, 1970. Let's see its value, type in seconds and hit Enter. Now we can see a very large number just like the large numbers we saw before. Now, we can use this seconds variable to compute the number of years since January 1, 1970. First, we know that there are 60 seconds in a minute. To get the number of minutes, we can just divide seconds by 60. In the same vein, we know there are 60 minutes in an hour. To get the number of hours, we can divide minutes by 60 as well. We can then divide hours by 24 to get the number of days and we can divide days by 3605 to get the number of years. Okay. Finally, let's check how many years it's been type in years, hit Enter, and 54 years. This makes sense. It's currently 2024, so 1970 was indeed 54 years ago. Okay. To recap, we learned how to call a function to call a function, use the function name, parentheses and arguments. If there are multiple arguments, we separate arguments using commas. We can also import functions to expand the number of functions at our disposal. If you like to access and download these slides or view completed code for example in this lesson, visit this URL. You can now modify data in more interesting ways, and even more importantly, you can now use what we've learned, calling functions to make programs that ask the user for their input, which we'll see shortly. To close our lesson will now cover a few bonus topics. I suggest skipping bonus sections for your first time through the course, or if this is your first exposure to code. Not because the concepts are particularly advanced, but because I'm going to go through extra content pretty quickly, and you don't need these concepts to grasp core coding fundamentals. If the lesson is feeling a little slow, or if this is your second time through the course, this bonus section is for you. So far, we've called functions using positional arguments. Positional just means that the meaning of the argument depends on its position. For example, the first argument to round is the value to round. However, we can also identify this argument explicitly using its name. According to Python documentation, this first argument is called number, so we can equivalently write round of number is equal to 3.14. When your function has many arguments, keyword arguments can be very helpful in making code more readable. For example, as we said before, round has a second optional argument that tells us how many digits to round two. So we can also write round 3.14 1592, two. This rounds our number to the nearest two digits. To make this code clearer, we can also write round number equals to 3.1 592 and n digits equals to two. And this now tells us what the meaning of each of these values is. We can mix positional and keyword arguments as well. For example, we can write round of 3.14 15n digits equals to two. However, note that keyword arguments, meaning n digits equals to two can only come after positional arguments. So let's see what happens if we switch that around, round of n digits equals to two, 3.1 415. Hit Enter, and this gives us a syntax error. It tells us exactly what's wrong. Positional argument, which was 3.1 415 follows keyword argument, which is n digits equals to two. So let's see what happens though, if all of your arguments are keyword arguments. If that's true, you can mix and match ordering for keyword arguments, Willy Nilly. So round n digits equals to two number equals to 3.1 415. And this is also true if you have more keyword arguments, you can simply interchange the order however you see fit. And that's it for keyword arguments in Python. This wraps up calling functions onto the next lesson. 7. Project: Currency Converter: In this lesson, we'll write a nifty tool that converts between currencies. Just like before, navigate to Pi total.com. In the bottom half of Pi Total, you'll see an interpreter. Let's start by writing code in this interpreter. Call the input function with one string argument. We haven't seen the input function before, so we'll see now what it does. Here my string argument we'll ask for the amount of Japanese yen followed by colon. Don't hit enter yet. Assign the returned value to variable named response, and now hit enter. You will now see JPY colon text, which is exactly what we input it for the argument here. Notice as well that the interpreters three arrows are now missing. This means your program is asking for input, not the interpreter. Type in 1,000 and hit Enter. Nothing much interesting happens, it seems. However, your program is finished and the interpreters three arrows have returned. Well, where did the text go? Quite simply the input function returned the 1,000 text that we inputed and we assigned that string to the variable response. As we mentioned before, variable assignment has no return value, which is why we don't see additional output. Let's now see what the value of response is, type in response and hit Enter. We see the 1,000 we input it earlier. Now our variable contains user input information. This is great. We can now write programs that ask the user for input. However, do you see the single quotes around our 1,000? Remember that quotes always mean a string. However, we want an integer so that we can do math to convert currencies. We have a string, but we need an integer. Notice that running some quick test in the interpreter, by the way, for some explanation first. I suggest that you always do the same when you're building programs. You can run quick tests in the interpreter to check if some code is valid. To start, let's see how to convert this stringified integer into an integer. We can use the built in function t to extract the number from that string. Let's try that now. It of response. Hit enter and that gives us the number 1,000 out. There's no quote here, so this is truly an integer and not a string offied integer. Now we can perform arithmetic on that number. In response, plus one. This now gives us 1001 as expected. Make sure that your plus one is outside of the parentheses if you hit an error. Up to this point, we've been working in the Python interpreter. We type one line of code and the interpreter immediately evaluates that line of code and returns the results. This is the interpreter on the bottom half the screen that we've been using. Now, we're instead going to write code in a file. This is the top half of the editor. We use this file editor slightly differently. We won't run code line by line anymore. Instead, after writing all code, we'll then run the file by clicking on the run button in the top left. Here in this file, we will write a program that converts Japanese Yen into US dollars. Let's ask for the users input, just like before. Input, we'll ask for JPY Colon. Then assign the returned value to a variable called text. Now, since we're writing code in the file editor, we need to tell Python when to output and what to output. To do so, we'll use the print function. Any argument we provide to the print function will be output. Let's call print on the variable text. Now, click Run in the top left to make sure the program so far works. Our program is now asking for input. Input, any number of your choice, I'll type in 1,000 and hit Enter. If you enter in a decimal value, your program will result in an error. Make sure to input an integer. Let's now update our program to convert the stringified integer into a proper integer. Delete print of text, and now we can write GPI of text. When writing programs generally, check your program as you build it incrementally. Don't build the entire program and run it once at the end. Let's practice this now. Output the variable JPY to make sure it's converted into an integer successfully. Print of JPY. Hit run in the top left. Your program prompts, I input 1,000 to test, and your program should print the same number you input it with no quotes. Perfect. Your program works. Now we can divide by the conversion from Japanese Yen to US dollars. According to Google, $1 is equivalent to 155.68 yen as of the time of this video. So we divide by that. Delete print, and now USD is equal to JPY divided by 15568. Next, we need to round to two decimal values, since we can't have fractional pennies in US currency. Luckily, for us, as we discussed earlier, the round function actually takes a second argument, which tells us how many decimal values to round two. USD is equal to round USD two. Now, we output the amount in US dollars. Click on the run button in the top left to run your program. Once your program prompts you for the amount in Yen, type in an integer, I see a delicious nogdon for 3,000 yen. Let's see how much that is in US dollars. Type 3,000, hit Enter, and $19. That's pretty good. Now, you're set for your next trip to Japan. Naturally, you could use any existing calculator for this or do quick mental math you're into that. However, what if we had a program that could do more? Maybe it could show you conversions in multiple currencies, for example, then that's a program that's saving you time. That's it for our tool onto the next lesson. 8. Calling Methods: In this lesson, you'll learn about a concept very similar to functions called methods. This will expand the set of tools we can build. Start by navigating to pi total.com. What is a method? At a very high level, a method is an object specific function. Here's an example. Conceptually, let's say we have a car object. Don't worry about what the code looks like for now. This car may have a few controls you'd expect like accelerate or break. Or maybe you have a dog object. This dog may have a bark or rollover feature. A file may have a read or write feature. These are all examples of methods because they're object specific functions. So how do I call a method? First, you need an object. Here we have a string object. Next, add a dot. This dot means we're about to access a method for this string object. Add the method name. In this case, the name is count. We'll explain what count does in a second. To call this method just like you call functions, add parentheses. Then add your single argument, A. All in all, the count method will tell us how many times the substring A appears in the original string A B. Let's summarize the parts. From left to right, we need the object, which is a string in this case, a period, the method name and the input arguments. Since we use a dot to call a method, we call this dot notation. Let's try this code now. Again, in our interpreter on the bottom half of the editor, we'll now use the exact example from the slides. We'll count the number of as there are in the string A B. To do this, use the method called count on the string A B. And give it a single argument, A. This is slightly less interesting. A obviously only occurs once. Let's do a more interesting example. How many Ss are there in Mississippi Mississippi count of S. Looks like there are four. We can now use the count method to count the number of characters in a string. Let's see another example. To build familiarity with this format and terminology, we're going to now talk about a different method. This method upper uppercases all the characters in a string. It takes no arguments. Let's try it. We'll uppercase a string by calling the upper method on ABC. We can also use upper on longer strings too at the top of my lungs. Upper. Strings have other methods too. For example, we can do the opposite and lower case all letters using the lower method. We can also check if a string contains a valid integer using the digit method. ABC dot is digit. Since this is not a valid number, they should give us false as expected. Let's try this on a real stringified integer. One, for example, I digit now gives us true as expected. Now, let's see a more practical example where where we read a web page. From requests port G. Requests is the library name. G is the function name. Let's try a page that I set up just for you. Hit Enter, and now type in G on the following web page, HTTPS coding 11 don't forget that trailing slash right here, and also don't forget HTTPS. Don't hit Enter yet. This in theory, we call This get call will open the web page and load its contents. Let's assign the fetched contents to a variable named response. Hit Enter now. Here we may see a warning, but you can ignore this warning about unverified HTPS request for now. Now let's see what was fetched. Type in response and hit enter. Now, this is a data type we haven't seen before. It's a response object. If you look at any Hello World tutorial for using the requests library, you'll find that we need to access an attribute of the response object. To access the attribute for any object, U dot notation as well. Write the object, which is here in orange, at a.in black, then write the attribute name, which is here in blue. Notice that there are no parentheses. Let's try this. Let's see what the text attribute contains response dot text. And this doesn't look like a whole lot. However, notice that there are line breaks here, this backslash n. So we need to print this text for these lines to render correctly. Type in print of response dot text, and hit Enter. There you go. There is a pick. Okay. Here's a quick recap of what we covered. We now know how to call methods on any object using the method name, parentheses, and arguments if needed. Let's recap both functions and methods since they're so similar. We call functions just using the function name. Call using parentheses without the dot like abs of negative five. When we call methods, we do need dot notation like variable dot upper. If you'd like to access and download these slides or view completed code for the example in this lesson, visit this OL. And you can now perform advanced data modifications by calling methods. Time for some bonus content. As usual, I suggest skipping these on your first time to the course. In this bonus section, we'll talk about how to read and write files. The reason why this exists as a bonus section is because there's a caveat. If you're using an online editor like Pi Total replet, your files aren't guaranteed to persist. Any file you create today may not exist tomorrow. However, if you're running code locally on your own computer, those files will of course persist until you delete them. That's the covet. Fortunately, the code itself doesn't require any new concepts. Let's hop right in. With this bonus lesson, we'll create write two and read from a file. We won't actually read and write files in this course, so this is just for practice. Let's create a new file. To do this, we need to open a file in mode. Type in open. The first argument here is going to be the path to the file. For us, it's going to be test text. The second argument is the mode. In this case, we're going to open this file in right mode. If the file does not yet exist, this function call open with the right mode will create the file. Let's assign this open to Let's assign this open functions return value to a variable called file. Let's see what the variable file contains. It's some gibberish. This return value is a datatype we again haven't seen before. This is called a file handler. Since we opened the file in write mode, we can write content to the file handler. To write, we'll use at method using dot notation. We takes one argument, which is the content to write to the file. In this case, hello, world. This returns 11, which is the number of bytes that have been written to the file. Now, since we didn't open and read mode, we can't read from the file, though. Let's try anyways by calling the read method. Notice the error. The file is not readable. This is because we open the file in the wrong mode if we want to read. As a result, let's close the current file handler. This will ensure that our right command earlier takes effect. File close. Next, we need to create a new file handler for reading. File is equal to open test dot text. Again, the first argument is the path. The second argument is the mode. In this case, we're using r for the read mode. Okay. Now, let's try reading from the file by calling its read method, just like the other methods, we'll use dot notation. Hit Enter. Notice we get the string that we wrote Hello World, and that's it for a brief introduction to reading and writing files. We won't use these methods in this course. This was really again just to practice calling and using methods. That's it onto the next lesson. 9. Project: Email Reformatter: In this lesson, we'll build another NIFT tool. This tool will reformat a list of comma separated e mails for us into one e mail per line. It will also count the number of e mail addresses. Just like in the previous lesson for NII tools, we're instead going to write code in a file. This is the top half of the editor. Remember that after writing all code in the file editor, then we run the file by clicking on the run button in the top left. Call the input function again. This time, you'll prompt the user for a list of comma separated e mails. Assign the return value to a variable named text. Now our variable text contains user input data. Now, we want to replace all commas with line breaks. Fortunately, there's a method for the string object called replace. In Coder speak, we would equivalently say there is a string method called replace. You'll hear me say this inadvertently every so often. There's a string method called upper, a file method called, a string method called replace. Let's now write text dot replace. Replace takes two arguments. The first argument is the character to replace the coma. And the second argument is the argument to replace it with. Sorry, the string to replace it with, which is backslash n line break. Replace performs the replacement on all comma, then returns the new modified string. Let's assign that returned modified string to the same variable text. In this way, our variable text now contains the new string where we have one email per line. Let's see what our new string looks like. Call print on the variable text. Click run in the top left to run your program, and now type in several emails. Here we'll type in a at at and at co hit Enter, and you should now see each email address on its own line. Our file works. We're going to add one more line of code, counting the number of email addresses there are. To do this, we use a string method called count. Count takes one string argument, and count returns the number of times that argument shows up. For example, we can count the number of email addresses by counting the number of times the at symbol occurs. Here we'll write te count at. Assign this to a variable called count. This will give us the number of e mail addresses in our string. Now, make sure to output this count by calling print on it. Hit run in the top left to run the program, and you should now see the count at the bottom after the e mails. B com again at. There we go. We have all of our e mails and the count three. That's it for this nifty tool onto the neck lesson. 10. Lists: In this lesson, you'll create your first collections of data. In particular, we'll create a list of data. Start by navigating to pi tittle.com. A list is what the name implies, a collection of ordered items like one, two, three. Let's start by defining a list. Like earlier, define as a special word. Previously, we define variables. Now we're going to define a list. To define a list, we always use square brackets, one to start the list and one to end the list. We also use commas to separate each item in the list. In this case, our items are numbers. Our items can also be strings. Our items can also be booleans. Or some combination of all those data types. Let's try out these examples in code now. Let's start from the interpreter again in the bottom half of your Pi Title editor in the interpreter, create a list of numbers, as usual, spaces after the commas are for readability. Hit Enter. We can also make a list of strings, or a list of bullions. We can also mix data types in a single list. Okay. Notice in each of these examples, I used square brackets and commas to separate each of the items. We can now define a variable names and assign it to our list of strings above names equals to the list of strings Jane John Alex. On the right hand side of the equal sign, we have the list from before, square brackets to define a list and commas to separate items. On the left, we have the variable name and the equal sign is what tells us this is a variable assignment. Let's check the contents of this variable names. Hit Enter. Perfect. This was the list we defined. However, what if we wanted to access different items in our list? How would we access the first item on our list of names, for example. Okay. Let's get an item from our list. Again, G is a special word. Generally, get means to access some part of a collection of data. So let's get an item. Look at the list of names we have. We assigned the variable names to a list. That list contains a few names, and we want the first name. To get this item, know which position this item is in. This item is in the first position. Next, find the index for the item you want. In most coding languages, the first item is actually at index zero. The second item is at index one. The third item is at index two, and so on and so forth. We call this zero indexing, meaning we start counting from zero. To summarize, we use index zero to get the first item. Next, use the index and square brackets to get the item. This code returns the value at index zero, meaning the first value. Our first value is Jane. This code returns Jane. Let's try this now. Follow the code on the left side exactly. Write the variable name for the list, which is names, add square brackets and the index zero. Hit Enter. There we go, we have Jane, which we can confirm the first item. Let's also see the second name. Use the variable name names, square brackets and Index one. Hit Enter. Again, we can confirm John is the second item from our list. Finally, let's get the last name here. Our third name. Names square brackets of two. Okay. And there we go, we have Alex. We know there are only three names in the list. What if we tried to get the fourth name at Index two names of three. Sorry, the fourth name at Index three. Hit Enter. And see this index error right here. As you might guess, this means that our index three is invalid. After all, the list only has three items in it, so Python raises an error if we try to access the fourth. Right here in the interpreter, let's now explore a few methods that lists have that we can use to modify lists. The append method will add an item to the end of the list. Let's see it in action. Names dot append. Append takes one argument, which is the value to add. In this case, we'll add a string, Amy. Append also does not return a value. Instead, it operates in place, meaning it modifies the list names and does not return a modified list. Let's now see what happened to names. Tara, names now has four values. As we said, the list names was modified in place. We can also use the pop method to remove an item from the end of the list names dot pop. If we don't pass any arguments here, pop by default, we'll remove the last item. Hit Enter. This time, names pop does two things. First, is it modifies the list in place by shortening it. Second, it actually returns the value it removed, which in this case is Amy. Let's now see what our list names looks like, as promised, names now only has three items. Let's quickly recap what we learned. First, lists are ordered collections of items. Use square brackets to define a list. Use square brackets and the index to get an item from the list. And finally, indices start from zero. So the first item in the list is at index zero. As a brief addendum, we also covered two methods for lists, a pen which adds items to the end of the list and pop, which can remove items from the end of the list. If you'd like to access and download these slides, visit this URL. In this lesson, we created our first collections of data. In the next lesson, you'll learn about a different kind of data structure in Python. Let's discuss some bonus concepts. These are common ways of using lists that you'd see in the wild. Like before, I recommend skipping bonus content if it's your first time to the course. Let's hop right in. Just like we can assign variables, you can also set items in the list to a value. For example, we can change the first item in the list to Gen. Names of zero is equal to Gen. It looks like a lot to unpack. Let's work through it from left to right. Here, names of zero means the first item in the list, and the equals operator assigns the first item in the list to the value on the right. Our value is a string, en. Okay. Hit Enter. To double check that our assignment was successful, type names of zero. There we go. We have Gen. As a recap, assignment operators don't have the return value, which is why we don't see any output here. You can also check which names are in the list by using the in operator. For example, to check if Jen is in the list, we can write en in names. This gives us true as expected. We can also check other values, Jane in names, and this gives us false as expected. Remember, we replaced Jane with Jen, Jane is no longer in the list. We can double check that by checking what the variable list variable names contains. There we go. It has Jen, John, and Alex, no Jane. And that's it for this lessons Vons content onto the next lesson. 11. Project: Name Picker: This lesson, we'll build a NIFT tool that samples two names at random from a list of names. You could use this program to randomly pair up friends for a secret Santa, for example. For this nifty tool, we'll start immediately in the file editor in the top half of Pi twiddle. From the library called random, import a function called choice. The choice function picks a random item from a list that we provided. Like before, call the input function with one string argument. This argument will prompt the user to input a list of names. Assign the return value to a variable named response. Next, call a string method called split. Split takes one string argument, which is the character to split on. We want to split the input string response on every com. Our string argument is just a. This now gives us a list of all the names, assigned list to a variable called Names. Then we'll finally call the choice function that we saw before. Specifically, call the choice function on the list names. This will sample a random name from the list of names and return that name. Assign the returned name to a variable called name. Finally, call the print function on the variable name to display the sampled name. To make sure that the program works so far, we're going to now hit run the top left to see the program in action. The program will prompt you for names. We'll type in three here. And it Enter. And there we go. We get one of the names sampled. We can also try running it again. John Jane Alex. And we get John again. Let's try this one more time and see if we can get a different name. John Jane Alex. There we go. We now know that this program is sampling randomly. Now we need to sample a second name without replacement. Without replacement just means that we can't sample two of the same name, so we can't sample Jane twice, for example. One way to do this is to simply remove the first name we sampled from the pool of names, then sample. To remove an item from a list by value, use a list method called remove. Remove takes in a single argument, which is the value to remove from the list. This value can have any data type. So as long as the data type matches the value in the list, we're good to go. Let's now type in in our file editor names dot remove, and we should give it one argument name. This line break right here is optional. It's just for readability. Just like before, remove is for once a method that operates in place. This means that it removes an item from the list and it does not return a new list. As a result, there's no return value and we don't need to assign it to a variable. Now that we've removed the previously sampled value, we can now re sample a new name. Follow the same convention as above and called a choice function, storing the return value in a variable called name. Okay. Finally, we'll call that print function on the variable name to display the second sampled name. Click run in the top right to run your program, type in a list of names. I will do John Jane Alex and Amy. Hit Enter. Here we have two names sampled from my list. This now completes our Nifty tool for sampling random names from a list. Onto the next lesson. 12. Dictionaries: In this lesson, you'll learn about another collection called a dictionary. Start by navigating to pi twitle.com, which I've already done on the right hand side here. A dictionary is a mapping from keys to values. Think of it like your dictionary at home, which maps words to definitions. Let's make this more concrete by seeing some code. Let's define a dictionary. To define a dictionary, we always use curly braces, one to start the dictionary and one to end the dictionary. We use a colon to separate the key from the value. Here, the key is a string denoted using purple. The value is a number denoted using pink. This dictionary maps the key jain to the value three. We use commas to separate entries in the dictionary. We're separating Jane witch maps to three from John which maps to two. Let's code this up. Again, inside of your interpreter in the bottom half of Pi twiddle, define a dictionary, just like what we have shown on the left. This is a dictionary, mapping names to numbers. Hit Enter. Now, let's assign a variable to our dictionary. Let's say the dictionary maps names to number of cookies. I'll name the variable name to cookies. To make sure we define this variable correctly, we'll now type in name to cookies, and we get the same dictionary that we input it. However, what if you want to know how many cookies Jane has? How did you get a specific value from the dictionary? Let's get an item from our dictionary. First, know the key for the data you want. In this case, we want Jane's number of cookies, so we need the key Jain. Second, using the key jain and square brackets to get the item. Second, use the key Jane and square brackets to get the item. This code returns a number that Jane corresponds to, which is three. Let's see this in action. First, write the variable name for the dictionary, which is name to cookies, add square brackets, then the key, hit Enter. This gives us the value corresponding to Jane, as we can see here. Let's do that again, but now for John, write the variable name for the dictionary. And add square brackets, then the key John. Hi enter. Again, this gives us the value corresponding to John in our dictionary. Now, what if we do the same for a name that doesn't exist? Let's try Bob. Hi enter. This gives us a key error, meaning that the key Bob does not exist in the dictionary. If you ever see a key error out in the wild, you may have a typo in your key. Let's recap what we learned about dictionaries. We use curly braces to define a dictionary. We use brackets and the key to get items from a dictionary. Across the two collections that we've covered, we've used a lot of punctuation in this lesson. Let's quickly recap what is used for what using this cheat sheet here. First, in the previous lesson, we covered lists, which are ordered collections of items. We define a list using square brackets. Then we get an item from a list using the index and square brackets. Second, we have dictionaries, which are mappings from keys to values. Define a dictionary using curly braces. Get an item from a dictionary using the key and square brackets. If you'd like to access and download these slides, visit this URL. You can now represent any data of your choosing with Python data collections. Let's now cover some bonus topics for dictionaries. Just like you can modify lists, you can also modify dictionaries. Here, for the key Jane, we can change the value 3-10. Name cookies of Jane is equal to ten. Hit Enter. To check that our assignment was successful, we can get the value corresponding to Jane. And here we see ten. We can also output the entire dictionary name to cookies. Hitting Enter returns the modified dictionary of cookie counts. Before this was Jane three, John two. Now it's Jane ten John two. This is a cookie, but that's it. 13. Project: Location Checker: This lesson, we'll build a NIFT tool that reports your location. This tool specifically uses an identifier called an IP address. At a very rough level, an IP address reveals what city you're in. However, if you use a VPN, your location should default to a completely unrelated location. For example, if you use Cloud VPN, your location might default as San Francisco, even if you're in Seattle, say. As a result, you could check your VPN is working using this tool. For this NIFT tool, we'll start immediately in the file editor in the top half of Pi Twiddle. Start by importing a function that opens web pages for us. Use a library called requests, and it's function called GT. We type here from requests Import GT. Using GT, fetch the contents of a website called IP Info DIO. Here we call the function G on the string HTTPS IP info DO slash JS. Let's now assign the returned contents to a variable named response. Before proceeding, let's try running this code so far. Hit run in the top left. And we get a massive wall of red text. Here you can see that our red text ends in a connection error. It turns out that ad block will understandably block calls this URL. Namely, any website that accesses this IP in IO can guess your location. However, in this case, we are the developers trying to access our own location, so you'll need to disable ad block temporarily for this function to work. So let me do that. I've now disabled Ad block, re run by hitting run in the top left. Now we see a warning here, but no errors. That means our web page fetch has worked. Next, call Call the response objects Jason method to get the web pages contents as a Python dictionary. Response dot JS. Assign the return value to variable named data. By the way, I keep writing code in these two steps. First, write the right hand side, then write the left hand side. Just to make it extra clear to you what's going on. You don't need to write code in this way. In fact, since I don't usually write code in this way, I may skip these intermediate steps moving forward. Now, in this dictionary data, let's access the key city. Okay. Finally, just like in previous lessons, use the print function to display the city. Hit run the top left to see which city your computer is accessing the Internet from VPN is activated, if VPN is working correctly. Here, we get Seattle, which is where I'm currently in, but I don't have a VPN activated. That's it. 14. (Bonus) Guided Exercises for Collections: Welcome to Bonus Content. Lesson 4 is guided exercises. In this video, we'll walk through exercises covering concepts from the last lesson. Again, there are three steps for each exercise; I will present an exercise, pause the video and try the exercise, then I will walk you through the solution. Some exercises are practiced when the exercise is the first to cover a concept, and the other exercises are quizzes, you should try testing your knowledge with these. Let's hop right in. Navigate to repl.it/languages/python3. You'll see a page similar to the one on the right. I've minimized a few of the tabs so that you can only see the interpreter on the right hand half the screen. Now, let's go ahead and start off with question number 1. This is a practice question. Define a list with three numbers. Assign the list to a variable called numbers. Give it a minute to try. Now we can define numbers is equal to, and a list with three numbers, I'm going to write 4, 5, and 2. Hit "Enter". We're going to type in numbers to check that our list was defined successfully. Hit "Enter" and there we go. Question number 2. This is now a quiz question. Define a list with the numbers 4, 2, and 7 in any order. Assign your list to a variable called numbers2. Give it a minute to try. Now, here's a solution: numbers2 is equal to [4, 2, 7]. Again, don't forget your opening and closing square brackets. Now, question number 3. This is a quiz question. Define a list with the strings "a", "b", and "c." Assign the list to a variable called strings. Give it a minute to try. Here's the solution. Typing strings is equal to a list of strings ["a", "b", "c"]. Go ahead and hit "Enter". We're going to double check that this list was defined successfully, and indeed it was. Question number 4: define a list with one boolean. Assign the list to a variable called booleans. As a hint, remember booleans are either true or false with capital Ts and capital Fs. Give it a minute to try. Here's the solution. We're going to define a list called booleans is equal to, and this list will only contain one boolean, in this case, we'll say True. Go ahead and hit "Enter". Once again, we'll check that this list was defined according to way that we wanted, and there we go. Question number 5. We now want to get the first number in the list "numbers." Give it a minute to try. Here's the solution. Go ahead and type in numbers, square bracket of zero. Again, remember that zero is the index of the first item, so this will fetch the first item in the list of numbers, which, in this case, is the number 4. Go ahead and hit "Enter", and there we have four. Question number 6, this is now a quiz question. Get the third item in the list "strings." Give it a minute to try. Now we have strings, and the third item in the list is at index two. Remember, the first item is at index zero, the second item is at index one, and the third item is at index two, so go ahead and type in square bracket two, "Enter", and there we get the third item in the list. Question number 7. This is now a practice question. Define a dictionary mapping strings to Booleans. Assign "Jack" to False, "Jane" to True, and "Alex" to True. Assign the final dictionary that you get to a variable called "name_to_hungry." Give it a minute to try. Now we start off by defining the variable, so name_to_hungry is equal to, and now we're going to define the dictionary. Dictionaries are denoted by a curly brace, and we'll now type in the key which is "Jack" and the value which is False. Then the key is "Jane" and the value is False. The final key here is "Alex" and the value is True. Go ahead and add that curly brace. You'll notice that in this interpreter, the line is wrapped around. If your interpreter is wider than this or if your screen is wider than this, then you won't see this line wrap around. I didn't hit "Enter" or create a line break, this interpreter wrapped around on its own. Go ahead and hit "Enter". We want to double-check that this dictionary has what we want, so type in name_to_hungry, and that is the dictionary that we indeed want. Go ahead, and I'm going to hit "Clear" in the top right. You don't have to do this, but if you do, click into your window and make sure to hit "Enter" so that you see this orange carrot once more. Question number 8. Define a dictionary mapping names to numbers. Assign these keys to these numbers and assign the final dictionary to a variable called "name_to_burgers." Take a minute to try this question. Now, here is the solution. We're going to define the variable, name_to_burgers, is equal to, and here we have a dictionary denoted with a curly brace. We're going to assign the string "Emily" to one, the string "Jenny" to the number two, the string "Neel" to the value three. Go ahead and end this with another curly brace, hit "Enter", and we're going to double check this dictionary. There we go, we have what we want. Question number 9. Here's another practice question. Define a dictionary mapping strings to strings. Assign the dictionary to a variable called "names_to_ names." Go ahead and give it a minute. Here's the solution. Go ahead and type out names_to_names is equal to, and we're going to say "Jack" to "Emily", and then "Jenny" to "Neel", and "Alex" to "Bob". Go ahead and hit "Enter", and there is our dictionary mapping names_to_names. Question number 10. This is now a quiz question. Define a dictionary mapping numbers to strings. Assign the dictionary to a variable called "age_to_name". Give it a minute to try. Here's the solution. We're going to type out age_to_name is equal to, and dictionary with a curly brace, and we're going to come up with arbitrary numbers to strings. Here we're going to say, 14 to "Bob", we're going to say 15 to "Alex", and let's say 20 to "Jenny." Go ahead and hit "Enter", and there is our dictionary. Question number 10. This is now another practice question. Fetch the boolean corresponding to "Jack" in the dictionary "name_to_hungry." Give it a minute to try. Here's the solution. Name_to_hungry, and we want the value corresponding to the key "Jack", so we're going to add a square bracket and type in the key. As we'd expect from the previous set of questions, the value is False. Now, question number 12, this is a quiz question. Fetch number of burgers corresponding to "Neel" in the dictionary "name_to_burgers." Give it a minute to try. Now let's type out the solution, name_to_burgers, and the key is "Neel." We're going to type in "Neel" and hit "Enter", and there we get three. Question number 13, this is now practice question. Define a list of dictionaries. Go ahead and give it a shot. Now let's go and type out the solution. Here we're going to have the variable name, list_of_dict. Here we're going to define dictionary, we'll say "a" to one. Because I'm lazy, it's only going to have one key and one value, and we're going to have just a second dictionary in this list. Go and hit "Enter". Again, you can create whatever dictionaries you want with whatever keys and values you want. Go ahead and now move on to next question, question 14. Here's a quiz question. Define a dictionary mapping strings to lists. Give it a minute to try. Here is a possible solution; we're going to define a dictionary, let's say str_to_lst is equal to a dictionary mapping a string, let's say, "Jack" to a list of numbers. I'm going to be lazy here and just add one key and one value. Go ahead and hit "Enter, and there we go, str_to_lst. Once again, let's start off with temperature check, how are you doing? If this was doable, that's great. If this was barely doable, don't worry, keep going and you'll build familiarity as we go. Finally, if this wasn't doable, that's also okay. Watch this video and the previous one again. Each time you rewatch, the concept will sink in a little bit more. If you have any questions, definitely don't hesitate to leave a question in the discussion section in the class. If you feel you've mastered this lesson, try to come up with a few extra questions and solutions. Again, leave them in the discussion section of the class and your fellow students will thank you for the extra practice. That's it for Lesson 4's guided exercises. 15. (Bonus) Guided Exercises for Using Functions: The Bonus Content, lesson 5's guided exercises. In this video, we'll walk through exercises covering concepts from the last lesson. Again, there are three steps for each exercises. One, I will present an exercise. Two, pause the video and try the exercise. Three, I will walk you through the solution. Some exercises are practice. On the exercise is the first to cover concept and the other exercises are quizzes. You should try testing your knowledge with these. Let's hop right in. Navigate to repl.it/languages/python3. You should then see a page like the one on the right. I have split my screens that you can see the question on the left hand side and the interpreter on the right hand side. Question number 1. This is practice. A function "min" returns the smaller of two numbers. Call "min" with two numbers as input arguments. Give it a try. Here's another solution. Min, and I will put in two arbitrary numbers two and six. Question number 2, this is a quiz. A function "max" returns the larger of two numbers. Call "max" with two numbers as input arguments. Give it a try. Here's now the solution. We have max and I'm going to type in the two same numbers, and there we go. Question number 3. This is again practice. A function "sum" returns the sum of a list of numbers. Call "sum" with a list of numbers as input. Give it a try. Here is now a solution. Sum, add a parentheses to call the function, and then add a square bracket to denote your list. I'm going to pass in a bunch of random numbers here. I'm going to type in 4, 8, and 6. I'm going to close the list with the square bracket and then end with a END parentheses. Go ahead and hit "Enter" and we get our sum. Question number 4. This is now a quiz question. A function "all" returns whether all booleans in the list are true. Call "all" with a list of booleans as input. Recall booleans are true or false with capital T and capital F. Give it a try. Here's now the solution. We're going to type in all parentheses to call the function, and we're going to create a list of booleans with square bracket for a list and then we're going to type in True, False, False. End the list and the function call and hit "Enter". Question 5, here's now a quiz. A function "any" returns whether any boolean in a list is true. Sorry, this is a typo. Here, let me go in and fix that right now. Call any with the list of booleans as input. Give it a try. Here's the solution. We type in any and then give it a list of true, false, false, end the list, end the function call, hit "Enter", and there we go. Question number 6. This is now a practice question. A string method "lower" takes zero arguments and returns a lowercase version in the string. Lowercase this string. Give it a try. Now let's see the solution. We're going to type in "HAHAHA". To call a method, remember you need dot and then the method name. In this case the method name is lower and there are zero arguments, so we just add parentheses with nothing in between. Go ahead and hit "Enter" and there we go. Question number 7. This is now a quiz. A string method "lstrip" takes zero arguments and removes leading spaces. Leading spaces are any spaces that the string starts with. Go ahead and remove all leading spaces from "hehe." Give it a try. Here's now the answer. We're going to just type in the string that we had from before here. We have double-quotes space "hehe" and we're going to write.lstrip with no arguments, hit "Enter" and we've removed all leading spaces. Question number 8. This is now a practice. A string method "endswith" takes one string argument and returns true if the string ends with that argument. We want to check if he@d.com ends with.com. Give it a try. Here's now the answer. We're going to type in "he@d.com".endswith, and we're going to have another string, that is,.com. This should give us true as expected. Question number 9. This is now a quiz. A string method "startswith" takes one string argument and returns true if the string ends with that argument. Check if "Mr. Bean" starts with "Mr.". Give it a try. Here's now the solution. We're going to create the string "Mr. Bean", and then we're going to type.startswith. Here we'll have another string that is "Mr." and that is also true. Question number 10, this is a quiz question. A string method "find" takes one string argument and looks for that argument in the original string. Find the position of cali in supercalifragilistic. Go ahead and give it a shot. Here is now the answer. We're going to type in "supercalifragilistic.find" and then a string "cali". It's at position 5. Question number 11. A string method "count" takes one string argument and counts the number of times that argument appears. Find the number of "i"s in Mississippi. Give it a try. Here is now the solution. We're going to type in "Mississippi".count "i". It shows up four times. Question number 12. A string method "replace" takes two arguments, replacing all instances of the first string with the second string. Replace all "a"s in "hahahaha" with "e"s. Give it a try. Here's now the solution. We're going to type in "hahahaha".replace all "a"s with "e"s. Hit "Enter" and there we go "hehehehe." Question number 13. Here is now a quiz question. Replace all "Bob"s with "Jon" in "Bob poked Bob's dog." Give it a try. Here's the solution. We're going to type in "Bob poked Bob's dog,".replace all instances of Bob with "Jon". Hit "Enter" and there we go Jon poked Jon's dog. Oh, I forgot to clear so that you don't get stuck in the bottom part of the screen. I'm going to click on "Clear" in the top right, and if you do the same, make sure to click into the window, hit "Enter" and ensure there is an orange carrot. Question number 14. A dictionary method "values" returns all values in the dictionary. Return all values in the following dictionary. Give it a try. Here's now the solution. Go ahead and type out that dictionary, and then colon 2. Again, these spaces are optional. I just follow that convention of adding a space after these colons. Go ahead and type in now.values. Before we had a bunch of string objects where those string objects had some methods. Now we have a dictionary with a method. Go ahead and hit "Enter" and we get the values for this dictionary. Question number 15. Here's now a quiz. A dictionary method "keys" returns all keys in the dictionary. Return all keys in the following dictionary. Give it a try. Here's now the solution. We're going to have "a": 1, "b": 2.keys. Hit "Enter" and there we go. Question number 16. Say you have a string, and this string is just a comma. The string method "join" accepts a list of strings as input. For example, this comma.join of this list produces a, b, c. Use join to convert a list of URL pieces into a full URL. For example, from a bunch of these chunks, "Google.com", "Mail", and "Hi", to "google.com/mail/hi." Now, you may think that this is cheating because I gave you the solution right here with an example. But in reality, this is what happens when you Google a function or a method online. You'll see a bunch of examples that follow the definition of the method or function. In fact, this is a fairly reasonable expectation to have when you're trying to use a function. Go ahead and give this a shot. Here's another solution. We're going to write out the /string.join, and then we're going to pass in the list of strings: Google.com, mail, and then hi. Make sure to end your list and then end your function call. Hit "Enter" and there we go. Now, this was a particularly challenging question just because this is a really weird Python syntax, but this is just how Python does it. This is how you combine a bunch of pieces of strings with some separator. In this case, the separator is the slash. Once again, check how are you doing. This was a difficult section. Note that in reality, you can always Google how a function or method is being used by others. You can also try the function or the method in the interpreter to see how it works. As a result, there's no need to memorize these functions or these function's usages. You just need to know what calling a function or method means, which you've now done dozens of times in this video. If this is doable, great. If this is barely doable, don't worry, keep going and you'll build familiarity as we progress in the subsequent lessons. If this wasn't doable, that's also okay. Just watch this video and the previous one again. Each time you rewatch, the concepts will sink in a little bit more. If you feel that you've mastered this lesson, try to come up with a few extra questions and the solutions. Leave them in the discussion section of the class and your fellow students will thank you for the extra practice. That's it for lesson 5's guided exercises. 16. If-Else Statement: This lesson, we will cover code that allows us to change the code we run based on a condition. Start by navigating to Pi title.com. As usual, I have it pulled up on my right hand side already. An if statement runs code if a condition is true. Here's what that looks like in pseudocode. If a condition is true, run code. Let's formalize this now with some code. Start by writing, then add your condition. In this case, the condition checks that x is less than five. Add a colon at the end of the line. Don't forget this colon. Then add four spaces at the start of the next line. These spaces are also extremely important. Don't forget these. Finally, add the code that will run if the condition is true. Here, statement really just means any piece of code. Here are all the parts annotated. For an if statement, we need the if, a colon at the end of the first line, and four spaces before every line that we want to conditionally run. We can change the condition in brown to anything we want, and we can also change the expression in orange, however we want. Let's try this in code. Unlike in previous interactive lessons, we will write code directly in the file editor in the top half of Pi Title. This is because we will now be writing more complex code that spans multiple lines, and the file editor makes it much easier to edit multi line code. First, define a value for x, x is equal to three. Then write your first if statement, copy the statement from the slides. Don't forget the colon at the end of the first line. Hit Enter. Here, the editor should automatically add four spaces for you. If it doesn't, add four spaces manually. Type in x is equal to ten. Hit Enter again, and make sure the D dent out of the statement by hitting backspace. Your cursor should now be aligned with the start of if Let's print the value for x. Before we run the program, what do you think the final value of x will be after this IL statement executes. Pause the video here. Here's the answer. Since x is equal to three, x is less than five. The condition is true. Since the condition is true, x is assigned to ten. As a result, we now expect x to be ten. Let's double check ourselves by hitting run in the top left. There we go. X is ten as expected. Let's test that the opposite works to ensure the block doesn't run if x is greater than or equal to five. Change x's value to be any value greater than or equal to five. I'll change mine to eight. Hit run in the top left. There we go. Since x is no longer less than five, the block should not execute. As a result, we expect x to remain to remain equal to eight after this code executes. To recap, this code on the left hand side, says, if x is less than five, assign x to the value ten. That's not all though. If statement has one more optional part. You can also add an L statement. The upcoming code runs if the condition x is less than five is not true. Like before, add four spaces. Then add the statement to conditionally run. These are all the parts annotated so far, and here is the full F L statement annotated. Now, you may hear the term block when coders describe parts of this F L statement. We call the first two lines the block and we call the last two lines the L block. For example, say x was previously eight. Since x is not less than five, the brown condition is false. As a result, we say the L block executes. The L block then reassigns the variable x to two. In summary, if x is previously eight, x will be two after this statement executes. Let's try this now. Let's first augment our statement up here to include the L block. Hit Enter and make sure to Dent before typing L. L should be aligned with. Again, don't forget our colon after L and make sure that the next line is preceded by four spaces. X equals to two. Remember that x is eight before you run this FL statement. After this program executes, we expect x to become two. Now hit run in the top left to execute the program and double check ourselves. As we expected, we see two. Now, let's change x's value to be any value less than five. I'll change min to two. Since x is less than five, the block should execute and x should become ten again. Hit run in the top left to execute the program. There we go, x becomes ten. Let's write one more I L statement using strings instead of numbers. Here we'll delete our code and now type in name equals to Bob. Notice that we used one equal sign to assign a value to a variable. Recall from our earlier lessons to check for equality, though, Use two equal signs. As a result, to check if the name is equal to John, we use two equal signs. Don't forget your colon. Hit Enter, and again, you should see four spaces, if not manually add them. If the condition above is true, then we print out the string name verified. L, and again, remember L should be aligned with if print out the string unrecognized name. Now, hit run in the top left of the program. This time, the condition is not true. Bob is not equal to John. As a result, the Llock runs and the program prints unrecognized name. Okay. Let's recap. In this lesson, we covered how to write an L statement. Specifically, if a condition is true, we run the if block. In this case, it would be x equals to ten. If the condition is not true, we run the L block. In this case, it's x equals to two. If you'd like to access and download these slides or view completed code for the example in this lesson, visit this URL. In the next interactive lesson, you'll learn how to write your very first loop. In other words, how to run a piece of code repeatedly. 17. Project: Birthday Countdown: In this lesson, we'll write a nifty tool that computes the number of days until your next birthday. You could use this to compute the number of days until your favorite holidays, for example. To do this, we'll need to combine all of our knowledge so far about calling methods, functions, if statements, and more. Start by navigating to Pi total.com. Let's use datetime as an example. A datetime is a type of object in Python. We can create a datetime object by calling the datetime function. This function takes three arguments, the year, the month, and the day. Let's create a few of these datetime objects. In this lesson, we'll start by exploring some code in the interpreter in the bottom half of Pi twiddle. First, from the library called DateTime import datetime. For the purposes of this lesson, we will say that date time here is a function that returns a special datetime object. Now we can construct any date and time we want. As we said before, date time takes several arguments. The first argument is the year. The second is the month where one means January. The third argument is the day of the month. For example, this date right here is January 2030. Hit Enter. Daytime objects also have additional arguments that represent the hour, minute, and seconds. For example, we can write 2050 for the year. May 1 at noon. Hit Enter, you can see that the output is another daytime object. Let's assign this object to a variable called DT. DT is equal to datetime and now we'll write 2030, March 15. As we discussed before, objects have certain methods. In this case, datetimes have a weekday method, which tells you which day of the week that date is. As a recap, here's how you call a method. The weekday method doesn't take any arguments here. Let's try this. DT, which is our datetime object dot weekday hit Enter. You'll see four in our case, which corresponds to Thursday. There's also a datetime method called ISO format, which converts the datetime format back into a string, DTOat hit Enter. Datetime objects also have attributes for each piece of the date and time. For example, there's an attribute that tells you which year the datetime represents as a recap to access an attribute, use dot notation. Write the object, a dot, then the attribute name. Let's try this now. D dot ear. This gives us 2030. Remember from above, our date time is 20:30, March 15. There are also other attributes. For example, we can access the datetimes month, dt month, which we expect is March or three. There's also d d, which we expect is 15. Let's now create a second date time for that year's New Year's Eve. DT two is equal to date time 2030 December 31, hit Enter. Then we can do something interesting. Before you could compare numbers to see which is bigger. Here we can do both with date times two, compare and subtract. For example, we can compare date times to see which is in the future. DT two is greater than DT. We can also subtract the two to get the time between them, DT two minus dt. Now, this is a new data type we haven't seen before. It's a new object, a time Delta object. Like the date time object, it has a few useful attributes and methods. Let's assign this time Delta to a variable to work with. DIF is equal to dt two minus dt. Now let's check the time Delta objects attributes. There's a days attribute that tells us how many days between the dates DT two and DT. Di days. Here we can see that it's 291 days between the New Year's Eve of that year and March 15 of that year. There's also a total seconds method which expresses the number of days in seconds. Here we have total seconds. That's a lot of seconds. That's it. There's no need to remember all of this functionality. We're going to use just a subset of this right now. The goal is to get you familiar with datetime objects. Now we will write a program that reports the number of days until your next birthday. We'll be using the file editor instead of the interpreter now. Like before, import the datetime function from the datetime library from date time import datetime. Before we said that date time was a function. In reality, date time is not a function. It will take an entire course to explain what date time actually is. For now, ignore what it really is. The important part is that date time actually also has methods. One of its methods is called and now returns the current date time. Assign the current date time to a variable called datetime. Let's create a date time that represents your next birthday. To do this, we'll first create a date time that represents this year's birthday. Next B day is equal to datetime now year, which means the current year, and I'll put October 10 year, but you can do whatever month and day you want to. However, say it's just two days past your birthday. This year's birthday has already passed. This year's birthday is not the next birthday. We will now use an if condition to check if this year's birthday has already passed. If next B day is less than now. If this year's birthday has already passed, increment the year by one, so we consider next year's birthday as the next birthday. Next B day is equal to next B day dot replace. Here, the replace method takes one argument or the first argument it takes is the new year. Now, deed end out of the statement body, your cursor should be aligned with the start of I. At this point, compute the difference between the next birthday and today by simply subtracting them. DIF is equal to next birthday minus now. Count the number of days until the next birthday and finally, report the number of days. Hit run on the top left to see how many more days until your birthday. Here we have 137 days until October 10, and that's it. You now have a countdown until your next birthday. Here's a recap of what you learned. We've learned how to create datetime objects, reviewed how to access attributes of items, and learned how to compute time Deltas. If you'd like to access and download these slides or view the completed code for this Nifty tool, visit this URL. In this way, you can now make countdown timers for all of your favorite dates, your friends birthdays, important work deadlines, or your favorite holiday. Onto the next lesson. 18. While Loops: In this lesson, we will learn how to run a piece of code repeatedly using something called a wi loop. Start by navigating to pittle.com. As usual, I haven't pulled up on my right hand side already. A wop iterates over a piece of code multiple times. It continues to iterate indefinitely while the condition is true, or as I've written here, until a condition becomes false. In other words, while some condition is true, keep running some code over and over again. Start by writing. Then add your condition. In this case, the condition checks that x is less than five. Add a colon at the end of the line. Don't forget this colon. Then add four spaces at the start of the next line. These spaces are also extremely important. Finally, add the code that will keep running while the condition is true. Here, each time the orange expression is run, x will be incremented by one, as we discussed in the previous lesson. Here are all the parts annotated. For a while loop, we need the i, a colon at the end of the first line and four spaces before every line that we want to run repeatedly. We can change the condition in brown to anything we want, and we can also change the expression in orange however we want. In sum, while x is less than five, increment x by one. S x was previously zero. After running this code, what would the value of x be? Pause the video here and ponder for a moment. After running this code, x will be five. In the first pass, x is equal to zero. In the brown, we see that x equals to zero, which is less than five. We then run the wild block, which is the orange right here. We increment x by one now x is equal to one. One is still less than five, so we increment x by one again. Now x is two, two is still less than five, so we increment x by one again. And we keep doing this until x is equal to five. Then five is not less than five, so the wileop stops. The final value of x is then five. Let's try this out. In your Pi total editor, we're first going to operate or we're only going to operate in the file editor in the top half. First, define a variable x to be zero. Then copy the wallop from our slide on the left. While x is less than five. Hit Enter. Again, it should create four spaces for you automatically if it doesn't add those four spaces manually. Here we're going to add an extra print statement so we can see how the value of x evolves print of x. Then increment x by one. Finally, at the very end of your program, make sure to de dent so that your cursor is aligned with while and type in print of x. Hit run in the top left, and you should now see a number of different outputs. This is what we discussed previously. Let's start with x is equal to zero. In the very first iterate, zero is less than five, so we execute the will block. We print x and then we increment x by one. That print is right here, the zero. After we've incremented x by one, x is now equal to one, which is again less than five, we execute the will block again. We print x, which is one, and then we increment x by one, and we keep doing this. We keep incrementing x by one until we get here to four. Now, four is less than five, we print four, and then we increment four by one. X is now five, five is no longer less than five, so we terminate this a loop, and we finally print five at the very end. To recap, here's how to define a loop. Use the keyword i, a condition, and the code that will loop repeatedly until the condition is false. If you'd like to access and download these slides or view completed code for example in this lesson, visit this URL. In the next interactive lesson, you'll learn about a different way to loop called a four loop. 19. Project: Bacon Ipsum: In this lesson, we will build a nifty tool that generates food themed filler text for us. This is useful for designers looking to generate orm ipsum, but with a twist. It's bacon Ipsum. For this NTT tool, we'll directly write code in the file editor from the requests library, Import the get function. At a high level, we're again going to ask the user for input. This time, we ask for the number of sentences of filler text to generate, and even better, we're going to add input validation. If the user inputs an invalid integer, the program will ignore the input and continue to ask the user for input. To do this, create a variable called sentences and assign it to an empty string. Now, we will keep asking the user for input until the user provided input is a valid integer. For this, we can use a wall loop. This will loop will continue to loop so long as the variable sentences does not contain a valid integer. Fortunately, there's a string method called digit, which tells us if the string is a valid integer. And we want to check if the string does not contain a valid integer. We write sentences dot is digit. Don't forget your colon. Hit Enter, you should see four spaces. On each iterate of the will loop, prompt the user for the number of sentences to generate filler text four. Here we'll write sentences is equal to input of number of sentences. Now, let's test our program so far. Click run in the top left. Now, try providing all sorts of random input like letters, maybe punctuation, and your program should stop asking you for input only after you've provided a valid integer. Once you've verified your program is working so far, come back to the fiator to make some more changes. Now, hit Enter and make sure to D dent out of the WOW loop. Again, your cursor should now be aligned with the start of the OL statement. Construct the URL that will provide us with food themed filler text. URL is equal to https, baconpsm com API. Question mark type equals to all and sentences is equal to plus sentences. To explain what's going on here. These values, keys and values after the question mark are called query parameters. They pass parameters to the URL bacon dips.com API, just like we pass arguments to functions. Here we write sentences is equal to the number of sentences that we've collected from the user and type is equal to all meat. Okay. We don't need to know these arguments. In short, what's important to know is that these are arguments, and this is how you pass arguments to a URL. Now, use our get function to fetch the web pages contents, assign the response object to a variable named response. Now, get the returned Jason as a dictionary and assign the value to a variable called paragraphs. The Bacon iPS website returns a list of paragraphs. Let's grab the first paragraph. Remember, we index into a list by using square brackets and the index of the item. Because of zero indexing, the first item is actually at index zero. Let's assign that to a variable called paragraph, and finally, output the paragraph of content. Hit run at the top left. Type in a number of sentences, keep it small like five to ten. Okay. And there we go. This wraps up our filler text tool. And our program gives us a bunch of food themed filler text. You can now use this to fill text and design mock ups or provide sample inputs to a program. Onto the next lesson as usual. 20. For Loops: In this lesson, we'll talk about a different way to run code multiple times. Start by navigating to Pi twitle.com. Let's start with a new range. Range takes one argument, the number of items in the range. Let's see what this range function returns and iterable. We'll see this in action now in the interpreter in Pi Title. Let's start with the interpreter, like we said, to explore a new function we haven't seen before. In this lesson, we'll use a new function called range. Call range of the number like five. Hit Enter. Range returns a special data type. We can see there's a range object that ranges 0-5. The specific data type is not that important. However, there are a few facts we do need to know. First, the range object is iterable. Second, an iterable is anything you can iterate over. Let's store the returned iterable in a variable. Iterable is equal to range of five. There's one more fact to know. We can convert any iterable like this one into a list. All we need is the list function. This function list turns an iterable into a list. This lets us see what is in the iterable. This is perfect for range. Let's use list to see what's in the range iterable. Call list on the returned iterable. And now you can see the contents of the range iterable. Range effectively returns a list of numbers from zero up to the number you inputed minus one. We input it five. So the list of numbers goes from zero up to four, and there are five total numbers in this list. Now, let's use the range function to write four loops. First, consider the iterable we want to loop over. We want to loop over all the numbers in the range from zero up to four. To iterate over this range, we will use a four loop. The characters in black, four, in and the colon are all required parts of a four loop. The green item variable is assigned to the next value in the range on each iteration. On the first iteration, is assigned to the first value in the range, a zero. On the second iteration, is assigned to the second value in the range, a one, on the next, two, and so on and so forth. Then add four spaces at the start of the next line. These spaces are important. Finally, add the expression that we run once for every value in the range. There are five values in the range object. This expression will run five times, once for each value in the range. Here are all the parts annotated. For a four loop, we need the four in and a colon at the end of the first line, as well as four spaces before every line that we want to run repeatedly. We can change the item variable in green, the iterable in brown, and the expression in orange to whatever we want. Let's try this now in code. Now we're going to write multi line code again. Let's write code in the file editor instead. Write your first file loop by copying the code on the left. Don't forget your colon at the end of the first line. Hit Enter, you should see four spaces, and in the four loop, output the value of i so that we can see evolve. Hit run in the top left to run your program, and you'll now see the values zero four printed. This is because the loop ran five times. For the first iterate, I was zero. For the second iterate, I was one, and so on and so forth. Now, let's try a for loop on strings. First, a string is also an iterable. So we can pass that iterable string into the list function. Let's see what happens when we call list on a string in the interpreter list of Hello World. Okay. And here you can see, we get a list of letters, one letter at a time. So if we iterate over a string, we will get one letter at a time. Let's try this in the file letter now. Replace our existing code with for in a string hello world. Print of. Hit run the top left, and as you can see, the program prints one letter at a time. Okay. Let's recap. We learned how to use four loops. Four loops enable us to iterate over an iterable object in the brown here. Each item in the iterable is assigned to the variable in green. Finally, the code in orange is executed repeatedly for each value in the iter. If you'd like to access and download these slides, or view completed code for the example in this lesson, visit this URL. This concludes the four loop lesson. In the next interactive lesson, we'll talk about how to define our own functions. Okay. 21. Project: Generate Password: First, do you use a password manager? If you don't already, you probably should. I personally use Google passwords, and one of my pet peeves is when Google doesn't recognize a password field on a registration page. Then Google doesn't suggest a new randomized password for me. So let's create a nifty tool that will create randomized passwords for you. As usual, we will start working in the file editor. Start by importing from two libraries this time, directly in your file editor. First, from the library Random, import the choice function, which we saw earlier. From the library string, we will also import a few strings that contain letters, numbers, and punctuation. Previously, we've only imported functions from libraries. You can import any data type, not just functions, too, bullions, strings, numbers, you name it. In this particular case, we've imported strings. You can also import multiple values from a library at once, as long as you separate the names by commas like we've done here. Now, concatenate all the strings that we just imported here into one large string. Characters equals to ask letters plus digits plus punctuation. This large string represents all of the possible characters our password can contain. Now prompt the user for the password length, using the input function that we discussed previously. Extract the integer from the string offied integer using the int function. Now we build the password by starting from an empty string. On each iterate of a for loop, we will then build this password character by character. Let's write a for loop now that iterates length number of times. Notice that we define the item variable to be an underscore. The underscore is python convention for a variable that we won't actually use. In this case, we just want to run code length times. We don't need to know which step of the looper on. Just like in a previous NIFT tool, we now use the choice function to select at random from a set of items. In this case, pass the string of characters that contains possible characters for our password. Choice con taking a string, a list, any data type that can be iterated over. Next, add the newly sampled character to our password. Make sure to Dent out of the for loop. Your cursor should be aligned with the start of the four loop. Print the password we've built up and hit run in the top left of our program. Enter into length. I will do ten, and there we go. We've now got our very own password generator. Now you can use this nifty tool to generate randomized passwords for yourself. 22. Define Functions: In the previous lessons, you learned how to use existing functions. In this lesson, we'll actually create our own functions. Start by navigating to Pi total.com. First, how do I define a function? As we mentioned before, think of functions from your math class. As a recap, functions accept some input value and return some value. Okay. Consider the square function. It takes in a number x, multiplies x with itself and returns the squared number. Let's now define the square function. Start every function definition with death. Then add the function name, add parentheses like you're calling the function, but this time, make sure to also add a colon. Add your input argument. In this case, our function square accepts only one argument. Then add four spaces at the start of the next line. These spaces are how Python knows you are now adding code to the body of the function. Since this function is simple, the first and only line of our function is a return statement. The return statement stops the function and returns whatever expression comes next. In this case, the expression is x times itself. Here are all the parts annotated once more. Note that all parts in black are needed to define any function. You always need deaf parentheses for the input arguments, and a colon to denote the function is starting. The function name, inputs, and expressions can all change. You also need the return statement to return values to the programmer calling your function. Let's try this now. Like at the end of the last lesson, you will now write code in a file instead of in the interpreter. In the top half of the editor, copy the code on the left hand side. Deaf square x. Don't forget your colon. Hit Enter and the editor should automatically add four spaces for you. Type in return x times x. Make sure your code runs by hitting run in the top left. Down below in the output console, there should be no error, the three arrows that denote the interpreter. Now, let's see how to use this function. How do I call my own function. Just like you would call any other function. Use parentheses and pass your input argument in. In this case, we pass in the argument value five. Let's see what happens to this five. Your function accepts an argument x, and we see that this argument x is used in the functions expression. Since we called square with the argument five, the square function replaces all x's with five. The expression is now five times five or 25. Your square function then returns the value 25. Now let's try calling the square function in code. Still in the file editor, let's call our brand new function. Hit enter to create a new line. Make sure you delete all the spaces before your cursor and your cursor should now be aligned with the start of death. Now we can call your brand new function just like you would call any other function. Assign the return value to a variable called result. Then we need to output the value of that variable, print result. Click run on the top left, and as expected, we get the square of five, which is 25. Let's try a few more values. Replace five with negative one. Hit run in the top left and you get positive one. Let's do this one more time. Replace negative one with three, hit run in the top left, and we get nine. You've now defined and used your very first function. Let's recap what we've talked about in this lesson. Here's how to define a function. Use the deaf keyword, the function name, specify the arguments, and fill in the body of the function. Every line in the function must start with four spaces. To return output, use a return statement along with an expression. If you'd like to access and download these slides or view completed code for the example in this lesson, visit this URL. You can now define custom functions as needed. This is actually all the concepts we wanted to introduce in this course. We, we will build one last nifty tool using many of the concepts we've learned so far. 23. Project: Secret Messages: In this lesson, you'll build a program that allows you to send secret messages to your colleagues. Although this isn't the most practical example, it's hopefully a fun one. Start by navigating to pi tittle.com. Let's use what's called a Cesar cipher. The Cesar cipher works by mapping each letter to another letter. In particular, each letter is mapped to another letter that comes 13 letters later. A is mapped to n, B is mapped to O C to P, and so on and so forth. But here's the interesting part. Since there are 26 letters in the alphabet, this also means that if we apply the Caesar Cipher twice to a piece of text, you get back the original. A is mapped to n and n is mapped right back to A. B is mapped to O and O is mapped right back to B. Now, let's code this up. Again, in your file editor, start by importing your web page reading function from requests Import G. Now, access a custom uL I've set up for you. This UL contains the Caesar Cipher mapping as a dictionary. Here we'll get the following URL, which I'll show in the slides here. HTTPS, alvin.com slash coding one oh one cipher JSON. Don't forget the HTTPS. Here at the very beginning, I'm going to assign this return value to the variable JSON. Next, let's convert the JSON into a dictionary using the JSON method. Then create a function called cipher, which will compute the secret message. This function takes in one argument, which is the original text. Start with an empty text for the secret message. Iterate over each letter in the original piece of text. Recall from what we saw before. We can write four letter in a piece of text or a string. Use the dictionary now to look up the old letter. The corresponding value will be the new letter. New letter is equal to the mapping of the old letter. Remember, this is the key. This is the value for our dictionary mapping. Now, add the new letter to the secret message. D dent out of only the four loop. Your cursor should now be aligned with four. Return the secret message that we've accumulated. Now Ddent out of the functions body, our cursor is now aligned with death. Ask for the text to encrypt, text equals to input text or the secret. Run the cipher on the user input it text and assign the result to the variable result. Finally, print the final result. That completes our program. Hit run and input whatever text you would like. I'm going to input hello. Now, take this secret message, copy it, run your program again, and paste in your secret. Hit Enter, and you should get back your original piece of text. In my case, hello. Now, feel free to encrypt any secret message you want and send it off to your friends. To recap, we've learned about the Caesar cipher, which simply maps every letter to the letter that comes 13 letters afterwards. This way, if you apply the Caser Cipher twice, you get back the original text. This is perfect for sending secret messages. If you'd like to access and download these slides or view completed code for the example in this lesson, visit this URL. This wraps up our last nifty tool for the course. Awesome work. Let's move on to the conclusion for this course. 24. (Bonus) Guided Exercises for Defining Functions: Welcome to some more bonus content, lesson 6 's guided exercises. I'm sure you're familiar with the format by now. There are three steps for each exercise. One, I present an exercise. Two, you pause the video and try the exercise. Three, I walk you through the solution. Some exercises are practice and other exercises are quizzes. You should try testing your knowledge with quizzes. Let's hop right in. Go ahead and navigate to aaalv.in/coding101/exercises6. You'll then be greeted with a page like this one. In the top left, you can click on the name of the "Repl.8" and click on "Fork." You'll then see an editable version like this one. Notice that I've changed the layout. You will now be using the file editor on the left half of the screen instead of the interpreter on the right. Instead of an orange carrot, you should be looking at the section of the page with a line number 1, 2, 3, so on and so forth. On this screen, I'm going to minimize the left-hand tab here by clicking on "Files" and then I'm going to drag on this center cursor so that my file's a little bit larger. All right, let's go ahead and start off with question number 1. For this first question, we have practice problem, we want to define a function "mul3" that takes a number argument and returns that number multiplied by 3. Go ahead and give it a shot. Here's the solution. Let's define the function def mul3 that accepts a single number argument. Here we'll add a parenthesis, we'll call that number argument x, and then add a colon, don't forget your colon. Then we return x times 3. Go ahead and run to make sure that your function and that your code is valid then we can try our function by typing in mul3 and 5 and that should give us 15. Question number 2, this is now a quiz. Define a function "sub3" that accepts a number argument and returns that number subtracted by 3. Go ahead and try. For the solution, define sub3. It accepts a single number argument and return x minus 3. We can hit "Run" and then try sub3, 10 should give us seven. Question number 3, this is now a practice problem. Define a function prod that accepts two number arguments and returns the product of both numbers. Give it a shot, and here's the solution. Define "prod" that accepts two number arguments. We'll call these x and y, returns the product of both numbers. On the right side we're going to start off by running and then prod 3, 5 for 15. Question number 4, this is now a quiz. Define a function "add" that accepts two number arguments and returns the sum of both numbers. Give it a shot, and here's a solution. Define add x, y, and return the sum of both numbers. Go ahead and run and then we can check, add 3, 5 gives us eight. Question 5, this is now a quiz. Define find function prod that accepts three number arguments and returns the product of all three numbers. I'll go ahead and scroll up a little bit more so you can see the previous solution as a reference. Go ahead and give it a shot. Here's a solution. We'll define prod and we'll give it three arguments and return the product of all three. Now go ahead and run. Here we now have prod 3, 5, 7, and that will give us a big number. Question 6. Define a function "gt3" that accepts a number argument and returns whether or not that number is greater than 3, give it a shot. Now, define the function gt3 that accepts a single number argument, we'll call this x and returns whether or not x is greater than 3. Go ahead and hit "Play" or "Run" and then we'll have gt3 of 5 and that should give us true. Question number 7, this is now a quiz. Define a function "lt10" that accepts a number argument and returns whether or not the number is less than 10, give it a try. Now, here's a solution. Define "lt10" that takes in a number argument and returns whether or not the number is less than 10. Go ahead and run, and then we can check "lt10," we'll type in five and that'll give us true. Question number 8, this is now a quiz. Define a function both gt3 that accepts two number arguments and returns whether or not both numbers are greater than 3. Here's a little hint, recall that x and y for some arbitrary code x and y, all return whether or not both of these are true. Give it a try. Here's now the solution, we'll type in the function name both gt3. This will take in two numbers, x, and y and we'll return x is greater than 3 and y is greater than 3. Go ahead and run the code. In the top right we can now try this code, both gt3 and we'll type in 5 and 7 and that will return true. Question number 9, this is now practice. Define a function sum3 that accepts a list of numbers and return the sum of that list multiplied by 3, give it a try. Now, define sum3 that accepts a list of numbers, we'll call this list "lst" and then we'll return the sum of the list multiplied by 3. Run their code and we can try the code now, sum3 and this will be 1, 2, 3. This sum should give us 6 times 3 should give us 18, hit "Enter" and we got 18. Question number 10, this now a quiz. A dictionary method "values" returns all values in the dictionary. Define a function "sumv" that accepts a dictionary and returns the sum of all values in that dictionary. Now, use your function "sumv" to compute the sum of all values in this particular dictionary. Let's go and define, oops, go, and give a shot first. Now, let's go and define this function def sumv. This will take in a dictionary and it'll return the sum of all the values, so here we'll do sum of all the values. Let's go ahead and run this code and try the code. Here we'll have {"a": 1, "b": 2}, and we'll get 3 as expected. Question number 11. This is a practice question. Define a function "is_jack_one" that accepts a dictionary as input and checks if the number corresponding to "jack" in the input dictionary, is one. Give it a shot. Now, define "is_jack_one," pass in a dictionary, and then we will check if the dictionary's value corresponding to "jack" is equal to 1. Go ahead and run your code. Here we'll write "is_jack_one" and we'll type in { "jack": 1} and yes it is. We'll also try a case where this should give us false so we'll pass in two, and that gives us false as expected. Question number 12, this is now a quiz. Define a function "add3_jack" that accepts a dictionary as input and returns three more than the number corresponding to "jack" in the input dictionary. Go ahead and give it a try. All right, and here's the solution. Let's go ahead and type in define, add3_jack that takes in a dictionary. First, you fetch the value corresponding to "jack," so dictionary of "jack," and then you add three to it. Let's go ahead and run this code and try this code, add3_jack, "jack": 1, and that should give us 4. Then we'll also try a different value "jack": 2 and that should give us five. Perfect. Once again, we want to check how are you doing, if this was doable that's great, if this was barely doable don't worry, keep going and you'll build familiarity. This was a challenging lesson. We continued to not only build off previous concepts but also integrate a number of new concepts. Number 3, if this wasn't doable that's okay, watch this video and previous one again. Each time you re-watch the concepts will sink in a little bit more. If you're feeling you've mastered this lesson just like before, try to come up with a few extra questions and solutions, lead them in the discussion section of the class and your fellow students will thank you for the extra practice. That's it for lesson 5 's guided exercises or lesson 6 's guided exercises. See you in the next lesson. 25. (Bonus) Guided Exercises for If, While: Welcome to Bonus Content, Lesson 7's Guided Exercises. In this video, we'll walk through exercises covering concepts from the last lesson. Again, there are three steps for each exercise. I will present an exercise. Two, you pause the video and try the exercise. Three, I will walk you through the solution. Some exercises are practice and the others are quizzes. You should try these quizzes to test your knowledge. Let's hop right in. Navigate to aaalv.in/coding101/exercises7. You'll then be greeted with a page like this one. Go ahead and click on the top left, and click on "Fork." You'll then have an editable Repl.it, just like this one. Start with question 1. Practice: Define a function gt5 that accepts one number argument; if that argument is greater than five, return "yay!." Give it a shot. Here's the solution. Define in gtf, it takes in one number argument, which we'll call x. If x is greater than five, return "yay!." That's it. We can run this function, and then gt5 and let's pass in 10 and returns "yay!." Otherwise, if we pass in two, nothing happens. Question number 2, this is now a quiz. Define a function reaction that accepts one string argument; if that argument is among us, return "yay!." Give it a shot. Here's the solution. Define reaction that takes in one string argument. We'll call this string argument game. You can call it whatever you'd like. If game is equal to among us, then return "yay!." Now, we'll try this code and type in reaction some other game, tic tac toe, nothing happens, but if we type in among us, then we get "yay!. Question number 3, this is practice. Define a function gt5o, that accepts one number argument. If the argument is greater than five, return "yay!," and otherwise, return "nu!." Give it a shot. Here's a solution. Define gt5o that accepts one number argument, which we'll call x. If x is greater than five, return "yay!," and else return "nu!." Run this code, and we can now try gt5o. If we pass in 10, then we'll get "yay!," and otherwise, if we pass in two, we'll get "nu!." Question 4, this is a quiz. Define a function reaction that accepts one string argument; if that argument is among us, return "yay!," otherwise, return "nu!." Very similar to the previous questions that we've seen. Give it a shot. Now, here's a solution. Define reaction that takes in game; if the game is among us, return "yay!," and otherwise, return else return "nu!." We can now try this function, hit "Run." Type in reaction "among us," and that gives us "yay!." Reaction of tic tac toe gives us "nu!." Question 5, practice. Define a function blackjack that accepts a list of numbers. If the sum of the numbers is less than 21, return the sum, otherwise, return zero. Give it a shot. Here's a solution. Define blackjack that accepts a list of numbers, we'll call this lst. If the sum of the numbers is less than 21, so if sum of the list is less than 21, return the sum, otherwise, return zero. Hit "Run." We'll now try blackjack 20, 20. This should return zero, because it's greater than 21, and now, we try for 3, 4, 5, and this is less than 21, so we expect 12. Question number 6. This is now a quiz. Define a function can_cook that accepts a list of strings. If the list of strings contains lemon, return the list, otherwise, return an empty list. Here's a hint. If you type in the following code, "hello" in list, this will return True, if the variable list contains the string hello. Give it a shot. Here's the solution. Define a function can_cook that accepts a list of strings. If the list of strings contains lemon return the list. So if lemon, in list, return the list, otherwise, return an empty list, which is just two square brackets with no contents. Go ahead and hit "Run," and now, type in can_cook, and we'll pass in a list with lemon in it, and that will give us the list back. Otherwise, if they pass in list without lemon in it, then this will give us an empty list. Question number 7, this is a quiz. Define a function laugh that accepts a list of Booleans; if any of the Booleans are true, return "haha," otherwise, return "uh." Here's a hint. The any function will return True if any Boolean in the input list is True. Give it a shot. Here's a solution. Define laugh that accepts a list of Booleans. If any of the Booleans are true, return "haha," otherwise, return "uh." Note that this line right here, if any list, could also be if True in list, very similar to our previous question. Either one of these would work. To test our function, go ahead and run your code. On the right-hand side, type in laugh, and we'll pass in a list of Booleans where they're all false, that gives us "uh" as expected, and we'll pass in one true, that gives us "haha." Question number 8, Practice: Write a while loop that prints every number from 5-10. Here, we'll type in i is equal to five, and then I will write while i is less than 11, we'll print i, and then we'll increment i. Now, we can try running this code in the right-hand side. Go ahead and hit "Run." There we go. We've got all numbers from 5-10. Note that you could have also put this. Actually, here's an alternative. So I'm going to comment out this code, and here's an alternative solution you could have written. You could have written i is equal to four, while i is less than 10, i plus equal to one, print i.We will increment i by one before printing, so the first number will be five and the last number will be 10. Just like before, we get the same result. Question number 9, Quiz: Write a while loop that prints every odd number from 5-15. Give it a shot. Here's the solution. We can type in i is equal to five. While i is less than 16. Here, we can actually do something simpler. We can just say print i and then i plus equals to two. That'll give us every other element. The very first one would be five, and then seven, and so and so forth. Go ahead and run your code. Here, we can see five up to 15, all of the odd numbers, as we'd expect. Now, question number 10, Quiz: Write a function print_from_to, that accepts two number arguments and prints every number from the first argument to the second, for example, print_from_to three, six would print all numbers from three to six. Give it a shot. Here's the solution. Define print_from_to x, y. These are two variables, not the two numbers. Let's go ahead and now use these numbers. Let's define an increment i is equal to x, and while i is less than y plus one, print i and then increment i. Let's now try this code in the very top. Hit Play to run the code and type in print_from_to three, six, and this will print every number from three up to six. Question 11, Practice: Write a while loop that prints every number from 5-10 that is not a multiple of three. Now, we can use a while loop. Here, we'll start it actually by defining i is equal to five, and then we'll write while i is less than 11, actually. We will check if i modulo three is not a multiple of three. We want to check if this is not equal to zero, then we print the value i, and then we increment i by one. Here, we'll check, is five a multiple of three? If five modulo three is not equal to zero, then it is in fact not a multiple of three, and reprint the number, and then we do this all the way up until we get to 10. Go ahead and run your code. Here, we'll see all the numbers that are not a multiple of three printed. Question number 12, Quiz: Write a while loop that prints every number from 5-15 that is not a multiple of six. You'll notice, this is very similar to the previous question. Try it now. Here's a solution. Go ahead and type in i is equal to five, while i is less than 16, if i modulo six is not equal to zero, not equal to zero. If this number is not a multiple of six, then we print the number, and we continue to increment. Go and run this code. At the very, very bottom, you can actually see that we've now got every number from five up to 15 that is not a multiple of six, so you don't see 12 or six here. Once again, we want to check how are you doing. If this is doable, that's great. This was a very difficult lesson. We combined many of the concepts from before. If this was barely doable, don't worry, keep going, and you'll build familiarity as we go. Number 3, if this wasn't doable, that's completely okay. Watch this video and the previous one again. Each time you re-watch, the concepts will sink in a little bit more. If you have any questions, please don't hesitate to leave them in the discussion section of the class, and I'll be more than happy to answer them. If you feel you've mastered this lesson, try to come up with a few extra questions and solutions, leave them in the discussion section of the class, and your fellow students will thank you for the extra practice. That's it for Lesson 7's Guided Exercises. 26. (Bonus) Guided Exercises for For Loops: Welcome to Bonus Content, Lesson 8's Guided Exercises. In this video, we'll walk through exercises covering concepts from the last video. Again, there are three steps for each exercise. One, I will present an exercise. Two, you'll pause the video and try the exercise. Three, I'll walk you through the solution. Some exercises are practice and others are quizzes. You should try testing your knowledge with these quiz questions. Let's hop right in. Navigate to aaalv.in/coding101/exercises8. You'll then see a page like this one. I'm going to hit, oh. Once you're on this page, click on Fork. Click on the title on the top left and then click on Fork. Then you'll get an editable version of this template. On the left-hand side, I'm going to click on Files - to minimize this tab - and I'm also going to drag this bar over to the right, so there's more space for the code in our file. On the left-hand side, we're going to go ahead and start with question number one, practice. Define a function "print list" that accepts a list of strings and, for all strings, prints the string on a new line, go ahead and try. Here's the solution. Define print_list. We're going to pass in a list of strings and, for each string in the list, print the string. "Print." Each time print is called, the string will be printed on new line. Go ahead and run your code. On the right-hand side call print_list and we'll pass in a list of strings. Add a close square bracket, close parenthesis, and there we go. Question number two, a quiz. Define a function "print_gt3" that accepts a list of numbers and, for all numbers, prints whether it is greater than three or not. Give it a shot. Here's the solution. Define the function "print_gt3" that takes a list of numbers and, for numbers in the list, print whether the number is greater than three or not. Oops, there's no "the". Go ahead and run the code. In here, we print_gt3 and pass in a list of numbers. There we go. The first two numbers, one and three, are not greater than three, but five is indeed greater than three. Question number three, this is a quiz. Define a function "print_add3" that accepts a list of numbers and, for all numbers, prints three more than the number. Give it a shot. Here is the solution. Define "print_add3". This takes in a list of numbers and, for each number in the list, print three more than the number. Run the code. We can double-check that this function works by calling it with a list of numbers. There we go. We have three more than each number in the list. Question four, practice. Define a function, "print_a_names" that accepts a list of names and, for all names, prints the name only if the name starts with an "a". Give it a shot. Here's the solution. Define, "print_a_names" and takes in a list of names and, for each name in the list, we can print name, but only if the name starts with an "a". Recall from a previous set of exercises that we can check if name starts with "a". Run your code, and now let's try this function. We will have a bunch of names with "a" and a few names without "a". Question five, quiz. Define a function "print_nums_gt3" that accepts a list of numbers and only prints numbers greater than three. Give it a shot. Now, here's the solution. Define "print__nums_gt3" that accepts a list of numbers and, for each number, if the number is greater than three, print the number. Run your code. Now "print__nums_gt3" and we'll pass in a bunch of numbers, some greater than three. So here five, seven, and nine are all greater than three, so they are printed. Question number six, this is practice. Define a function "get_name" that accepts a list of names and returns the first name that starts with an "a". Give it a shot. Now, let's talk about the solution. Notice that here I said returns the first name, not print. So go ahead and define "get_name". This accepts a list of names and for name in names, just return if the name starts with "a" return that name. One thing that we haven't quite talked about here is that the return statement actually terminates the function. As soon as this return statement is executed, nothing else in the function will run. So this ensures that the first name that starts with a capital "a" is returned. Let's run. Let's now use this function. So here we'll have David, Alex, and let's say Emily. Here, we get Alex, the first name that starts with an "a". Question number seven, quiz. Define a function "get_odd" that accepts a list of numbers and returns the first number that is odd. Give it a shot. Here's the solution. Define "get_odd" that accepts a list that numbers and we'll once again loop through all the numbers and if the number is odd, then we return the number. We can now run this code and check that the code is correct Two, three, and five. Here, we expect three for our return value. Perfect. Once again, let's check how are you doing. If this was doable, great. If this was barely doable, don't worry. Once again, let's check how are you doing. If this was doable, great. If this was barely doable, don't worry. This was a challenging set of exercises. What's most important is that you can read the code and understand how it works. Third, if this wasn't doable, that's okay. Watch this video and the previous one again. Each time you rewatch, the concepts will sink in a little bit more. If you're feeling you've mastered this lesson, try to come up with a few extra questions and solutions. Leave them in the discussion section of the class and your fellow students will thank you for the extra practice. That's it for Lesson 8's Guided Exercises. 27. Coding101 Conclusion: Congratulations. You've number one covered a number of different coding fundamentals. Number two, you've had hands on experience with code, and three, now have a slew of NIP equals to use. You've picked up a code to begin automating bits and pieces of your day to day life. My advice is to start small. Start from the categories we have examples for in this class, manipulating text, calculating dates, or using weather information. There may be an inkling of doubt, though. How do I try new categories of tools? I don't know how exactly to write my Nifty tool, and that's completely okay. Remember, the goal is to get you interested in and able to look for and read code. What's more important than knowing the right answer is having the interest to continue. If you're stuck, ask Chat CBT or post a question in the discussions tab, you have me and your classmates as a resource. I hope you had fun, but most importantly, I hope you see now how much utility code can provide today. It doesn't have to be months long, years long journeys. Anyone can leverage the power of code, and now you can begin to. Got a supernupw too. I and your peers would love to try it out. Take a screenshot your code, upload to the projects and Resources tab, and don't forget to include a Linked Ta Pi Twittle. I look forward to seeing your projects. I've designed a second course to follow up this one, which covers object oriented programming, called learn how to learn coding faster, object oriented programming and Python. If you're looking to dive straight into different applications of code, you can try my computer vision one oh one class to experiment with computer vision. The data science 11 class to play with data. Or the SQ one oh one class to query and design databases. There is more content coming to help you ace coding interviews and grow into an advanced python coding. If these sound interesting, go to my Skillshare profile and click Follow to get notified when those classes are long. Congratulations once more on making it to the end of the course and until next time.