Python for Absolute Beginners - Learn Python in a Week | Andreas Exadaktylos | Skillshare

Playback Speed


1.0x


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

Python for Absolute Beginners - Learn Python in a Week

teacher avatar Andreas Exadaktylos, Teacher | Expert Computer Scientist | Entrepreneur

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:27

    • 2.

      Why Learn Python?

      2:02

    • 3.

      Five (5) Beginner Tips for Learning python Programming

      6:55

    • 4.

      INTRODUCTION - Download & Install Python 3 (2024)

      1:25

    • 5.

      Download & Install Python 3 (Windows)

      6:55

    • 6.

      Using the Python Shell

      2:19

    • 7.

      Setting Up Python (Summary)

      1:11

    • 8.

      Code Editors

      2:15

    • 9.

      Your first Python program – Introduction

      1:09

    • 10.

      Writing our first Python Program

      9:12

    • 11.

      Let’s make some mistakes

      6:31

    • 12.

      Creating a Variable

      13:45

    • 13.

      Adding Comments

      4:06

    • 14.

      CHALLENGE: Interact with IDLE (Python Shell)

      4:44

    • 15.

      How to Find Help

      3:06

    • 16.

      Writing your first Python program (Summary)

      1:06

    • 17.

      Strings and String Methods (Introduction)

      1:23

    • 18.

      What is a String

      5:47

    • 19.

      EXERCISE: What Is a String

      2:18

    • 20.

      SOLUTION: What Is a String

      5:38

    • 21.

      Manipulating Strings with Methods

      11:55

    • 22.

      EXERCISE: Change the Case

      1:09

    • 23.

      SOLUTION: Change the Case

      3:20

    • 24.

      EXERCISE: Remove Whitespace

      1:08

    • 25.

      SOLUTION: Remove Whitespace

      2:17

    • 26.

      String Indexing

      2:36

    • 27.

      String Slicing

      3:30

    • 28.

      EXERCISE: String Slicing

      0:28

    • 29.

      SOLUTION: String Slicing

      2:40

    • 30.

      String Concatenation

      2:18

    • 31.

      EXERCISE: String Concatenation

      0:38

    • 32.

      SOLUTION: String Concatenation

      2:38

    • 33.

      String Formatting

      3:50

    • 34.

      F-Strings: An Improved String Formatting Syntax

      7:04

    • 35.

      EXERCISE: Streamline Your Prints

      1:06

    • 36.

      SOLUTION: Streamline Your Prints

      4:39

    • 37.

      Interact With User Input()

      4:53

    • 38.

      EXERCISE: Interact With User Input

      0:46

    • 39.

      SOLUTION: Interact With User Input

      4:57

    • 40.

      Working With Strings and Numbers

      13:55

    • 41.

      EXERCISE: Work With Strings and Numbers

      1:07

    • 42.

      SOLUTION: Work With Strings and Numbers

      6:58

    • 43.

      Print() Formatting Methods

      7:43

    • 44.

      Finding a String in a String

      9:18

    • 45.

      EXERCISE: Find a Letter in a String

      0:47

    • 46.

      SOLUTION: Find a Letter in a String

      4:10

    • 47.

      Strings and String Methods (SUMMARY)

      0:57

    • 48.

      PROJECT: Create a Receipt Printing Program

      12:21

    • 49.

      Numbers and Math (Overview)

      1:26

    • 50.

      Numeric Types in Python

      4:50

    • 51.

      Integers

      6:50

    • 52.

      EXERCISE: Define Integer Literals

      1:17

    • 53.

      SOLUTION: Define Integer Literals

      4:07

    • 54.

      Floating Point Numbers

      7:38

    • 55.

      Arithmetic & Comparison Operators

      5:15

    • 56.

      Logical (Boolean) & Chained Comparison Operators

      2:46

    • 57.

      Floating-Point Representation Error

      6:02

    • 58.

      Math Functions and Number Methods

      9:32

    • 59.

      Numbers Formatted as Strings

      4:15

    • 60.

      EXERCISE: Show a Percentage

      0:19

    • 61.

      SOLUTION: Show a Percentage

      1:04

    • 62.

      Complex Numbers

      4:40

    • 63.

      The Remainder (% Modulo) Operator

      6:25

    • 64.

      Reading Numbers with the input Function

      8:11

    • 65.

      Numbers and Math (SUMMARY)

      1:24

    • 66.

      CHALLENGE: Calculating a Percentage

      3:21

    • 67.

      CHALLENGE: Calculating an Average

      5:15

    • 68.

      CHALLENGE: Converting a Math Formula to a Programming Statement

      5:47

    • 69.

      Dates and Times

      4:18

    • 70.

      What is a List

      5:50

    • 71.

      Working with Lists

      3:44

    • 72.

      Making Numerical Lists

      1:41

    • 73.

      Printing Lists

      2:07

    • 74.

      Tuples

      4:00

    • 75.

      Tuple Assignment, Packing, and Unpacking

      4:00

    • 76.

      Working with Dictionaries

      4:07

    • 77.

      Sets

      4:25

    • 78.

      If Statements

      3:38

    • 79.

      EXAMPLES of Using the if Statement in an Application

      10:19

    • 80.

      For Loops

      2:09

    • 81.

      EXAMPLES of Using the for Statement

      6:12

    • 82.

      While Loops

      3:35

    • 83.

      Break and Continue

      2:25

    • 84.

      PROJECT: Guessing Game

      6:27

    • 85.

      Using if Statements with Lists

      1:42

    • 86.

      Using for Loops with Lists

      2:02

    • 87.

      Using a while Loop with Lists and Dictionaries

      3:03

    • 88.

      Creating Stacks Using Lists

      4:04

    • 89.

      Searching and Sorting Lists

      4:34

    • 90.

      Looping Through a Dictionary

      2:14

    • 91.

      Replacing the switch statement with a dictionary

      3:33

    • 92.

      Working with the Counter Object

      2:25

    • 93.

      What are Functions

      2:13

    • 94.

      Built In Functions

      2:09

    • 95.

      Defining your Function

      2:57

    • 96.

      More Built In Functions

      9:37

    • 97.

      Global and Local Scopes

      4:54

    • 98.

      PROJECT: Improved Guessing Game (version 2) - PART 1

      7:14

    • 99.

      PROJECT: Improved Guessing Game (version 2) - PART 2

      4:29

    • 100.

      PROJECT: Improved Guessing Game 3 (version 2) - PART 3

      9:16

    • 101.

      Dealing with errors

      3:22

    • 102.

      Common Syntax Problems

      8:40

    • 103.

      Become a Bug Bounty Hunter

      9:10

    • 104.

      Basic Exception Handling

      5:57

    • 105.

      Handling Multiple Exceptions

      7:26

    • 106.

      Raising Exceptions

      2:28

    • 107.

      How to Debug in IDLE 2021

      3:27

    • 108.

      Rock, Paper, Scissors OVERVIEW

      1:49

    • 109.

      Rock, Paper, Scissors With Python Input and Loops

      7:46

    • 110.

      Rock, Paper, Scissors With Python How to Determine a Winner

      13:24

    • 111.

      What Is Object Oriented Programming (OOP)

      3:16

    • 112.

      Classes in Python

      2:50

    • 113.

      Class and Instance Attributes

      5:18

    • 114.

      Adding Attributes to a Python Class

      6:44

    • 115.

      Adding Methods to a Python Class

      6:00

    • 116.

      Introduction to OOP Inheritance

      3:52

    • 117.

      Inheritance Example

      9:15

    • 118.

      Scripts, Modules, Packages, and Libraries 2022

      4:18

    • 119.

      Writing a Module

      2:44

    • 120.

      The Module Search Path

      4:42

    • 121.

      The import Statement

      6:08

    • 122.

      The dir() Function

      3:52

    • 123.

      Executing a Module

      5:41

    • 124.

      Reloading a Module

      3:16

    • 125.

      How to Install a Package in Python using PIP

      3:18

    • 126.

      Python Packages

      4:33

    • 127.

      Create Graphics and Shapes Using Python’s Turtle Module

      5:56

    • 128.

      Python's open, read from, and write to a file

      5:49

    • 129.

      Getting a Directory Listing and File Attributes

      7:56

    • 130.

      Making and Deleting Directories

      10:28

    • 131.

      Deleting, Copying, Moving, and Renaming Files

      7:37

    • 132.

      Milestone Project Create an interactive Math Game

      1:30

    • 133.

      Part 1 Importing Modules and Getting the User’s Score

      3:44

    • 134.

      Part 1 Exception Handling and Updating the User’s Score

      7:15

    • 135.

      Part 1 Generating the Questions and the Mathematical

      6:16

    • 136.

      Part 1 Generating a Mathematical Expression and Evaluating the result

      6:03

    • 137.

      Part 2 Writing the Main Program

      5:48

  • --
  • 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.

1,121

Students

5

Projects

About This Class

A Python 3 Practical Programming Course for Absolute Beginners - Learn how to Code in Python (+Python Projects)

Start coding in Python immediately!   

If you are a beginner in Programming, then this course will help you learn Python Programming fast.

Python is an incredibly efficient language: your programs will do more in fewer lines of code than many other languages would require. It is also used in scientific fields for academic research and applied work.   

My goal was to create a Course for people of any age who have never programmed in Python before or have never programmed at all, so you can build programs that work.   

The course is full of examples and projects that are carefully chosen to demonstrate each concept so that you can gain a deeper understand of the language. It is designed to serve as a single, all-inclusive learning resource for all Python newcomers, whether they will be using Python 2.X, Python 3.X, or both   

Python Programming for Beginners is also perfect for middle school and high school teachers who want to offer their students a project-based introduction to programming.  

Are you looking to learn practical Python Programming you can put to use instantly? If so, then this is the course for you. It’s entirely project based and it’s full of examples which are fully explained and easy to understand. It has been recorder in full HD 1080p.

 Python is a great language to learn, so enroll in this course and let’s get started!

Meet Your Teacher

Teacher Profile Image

Andreas Exadaktylos

Teacher | Expert Computer Scientist | Entrepreneur

Teacher

LinkedIn: https://www.linkedin.com/in/andreasexadaktylos

Hi, I am Andreas and I'm a teacher. I really love learning and teaching whenever i can.

I have over 16 years of experience in teaching as an instructor. I have my own computer learning school, called Futurekids, from 2001 to now. I am the founder of Mellon Training, an online video tutorials learning school.

I have a Masters Degree in Computer Science and a Degree in Electronic Engineering.

I always wanted to create my own business. Being your own boss is an incredibly liberating experience but difficult as well.

I have a passion for software products that make people's lives easier. I love to create websites and optimizing them with Search Engine optimization techniques. I created my online e-sh... 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: Hello and welcome. My name is Andreas, and I'll be your instructor for this Python course. I'm a computer engineer and have been a teacher for over 20 years. I have my computer learning school, and I teach Python programming to tens of thousands of happy students just like you. And I'm so excited to be your instructor on this course. Python is absolutely the fastest growing programming language in climbing to the top three languages to learn for the future. Python is one of the most versatile programming languages. You can use it for anything like machine learning, web development, applications, automation, game development, and so much more. In this course, you will receive a detailed and thorough explanation of fundamental Python programming concepts. And I'm going to make the learning process so easy and memorable, you won't even need to take notes. You're going to learn by doing and building many projects. Along the way, you also have milestone projects that help you create fully functioning programs and games that you can show off to your colleagues. We have over 100 lectures of ten ADP, high quality explanatory videos and fully detailed slides that go along for each lecture. So if you are completely new to programming or new to Python language, you have come to the perfect place. So with all that in mind, what are you waiting for? Go ahead and click that signing button, and I'll see you on the other side. 2. Why Learn Python?: Hello, and welcome to the exciting world of programming. In this lecture, we will do a brief overview of what Python is, why choose Python for programming and what you can do with Python. Python was created in 1990 by Guido Van Rosam. It was specifically designed as an easy to use programming language. The Python programming language is named after the comedy group called Monty Python, not the reptile. When we say programming, we mean that we enter instructions for the computer to perform. Python is a widely used high level programming language. Of course, many high level programming languages are available, such as C, C plus plus, and Java. But if you are new to programming, Python is a great place to start. Let's see some reasons why to learn Python. Number one, Python is more straightforward than other programming languages and ideal for beginners. Most programs require considerably fewer lines of code to perform the same task compared to other languages. Two, Python is an efficient language. Python syntax helps you write clean code, easy to read, easy to debug, and easy to extend and build upon. Three, Python has a wide range of use. You can make games, build web applications, and solve business problems. Python is also used heavily in the scientific fields for academic research. Four, Python has a large number of third party tools such as Pinstaller that allows us to package our Python code into stand alone executable programs for operating systems like Windows and MacOS. Five, Python has a great community. Having a supportive community is critical in solving problems, especially in your first programming steps. These are the five most important reasons why we choose and learn Python. If I convinced you, it's time to start. Thanks for watching. 3. Five (5) Beginner Tips for Learning python Programming: Welcome back everybody. In this video, I will give you five beginner tips for learning Python programming. You're going to look at how to code every day, how writing it out can help going interactive, talking breaks, and asking good questions. Let's start by looking at coding every day. Little in often is better than one large chunk a week. If you only had an hour a week, despair, you'd be much better off spending ten minutes on six days of the week and having a day off than doing one hour one day of the week and having six days off. Leaving a long time before you practice any new skill can mean it will be lost to you and you'll end up having to recover the same ground again and again. Whereas covering it every day for a week will help you retain it much better and then longer gaps afterwards won't be so much of a problem. Also being realistic about the time that you have for this, Everyone's different. Some people can spend a lot of time and we'll be able to make more progress than someone who's only has an hour or two to spare a week. So being realistic about this, remember, it's not about comparing yourself to other people. It's about comparing yourself to where you started. Start by solving small problems when you start programming, then you'll gain skills and learn new areas of Python that you didn't know before. And it can give you great confidence in being able to approach more difficult problems further down the line. Write it out. Writing out notes helps you retain information better than any other method. Yes, handwritten notes really do help when the information passes through you as you've read it and then rewrite it in your own words, your brain takes it in a method that you understand, and this is the most important part of learning. There will be different areas in which you need to concentrate on, make notes on compared to somebody next to you. Also planning for programs with written notes can help make the solution clearer. Again, here, I found that writing things out by hand is much more helpful and much more immediate than doing it on a computer. For the complicated, larger problems, which would need a lot of documentation. You would want to do this online in a method that can be updated later on. When you're initially planning this out, writing out the kind of data and variables you're going to need can be really, really important and instructive. It's often easier to create visual representations when working with paper and pencil. And for many problems, this is a useful way to approach them. Go interactive. The Python shell is a great way to examine and create code instantly. It's quick and easy to develop code in Python shell, but you can also use it to discover and explore the methods that are available to you. Open the Python shell, and now you can use this in action. Take breaks. Taking breaks as an incredibly important part of learning. One of the most commonly studied techniques used by people who are learning on the Internet is the Pomodoro Technique. Now this is actually only named after the tomato shape timer that the person who invented it used. But it consists of merely setting a 25-minute timer to work and then taking a five-minute break and then repeating. There's lots of evidence to illustrate that our brain only has a finite Lauren's time and needs breaks. Your brain needs time to take in information and also needs a rest. I would strongly suggest that you do take a real break. It'll give your brain a chance to reset. And you'll often find that ideas will come to you when you are in the resting state. Sleep is also really important for memory formation. Plenty of research has shown that a good night sleep after a day's learning really helps cement that information and lock it into long-term memory. Your brain will work on it and it will be refreshed during that break. When you come back to it, many will be the time when you'll see something you just hadn't thought of and away you go. Ask good questions. At many points in your programming career, you're going to need to ask for help. And often that can come in the form of asking questions on sites such as Stack Overflow. When doing so, it's really important that you ask questions in the right way so people can help you without duplicating the kind of testing that you've already done, that can give them a good idea of what you've already done and what you're intending the program to do. Firstly, the g of good, give context to what you're trying to do. Clearly describing the problem. Here on the left, we can see a bad example. It just says can't print properly. Whereas on the right we've got a good example. I'm trying to use an f string with format and combined with variable to give six total digits and one decimal place. But I can't find the right syntax. The one on the left can be anything from printing on a printer to using the print statement. Whereas the one on the right is really clear. We know exactly where we are and what the problem is. Outline the things you've already done to try and fix the issue. Again, you see this quite often. Tried everything on the left. That's not really helpful. It's unlikely you've actually tried every possibility. On the right, you can see that the user is tried the different variations including an odd style dot format, but nothing has worked for them. Next, offering the best guess as to what the problem might be. This helps the person who's helping you not only know what you're thinking, but also to know that you've done some thinking on your own. You've not just fallen at the first hurdle and throwing the problem for someone else to do. On the left, we have a bad example. No idea what's wrong. And on the right, I can make the formatting work using old style formatting, but I can't see where to insert the new variable in a new style. This is clear and concise and will hopefully point anyone who's trying to answer the question in the right direction to find somebody who knows really well how to use f strings. D stands for demo. Demo is what's happening. Include the code traceback error message or an explanation of the good steps that you've tried to execute that resulted in the error. This way, the person helping does not have to try and recreate the issue, including all of the code that's relevant is really important. You see quite often where people can help because they don't want to spend a half an hour trying to work out what somebody's done. They want to be able to copy the code, try running it themselves, or maybe just try looking at the code. There'll be able to tell the right person What's wrong. Here on the left, the bad example, no code at all. On the right. A good example. The variable has been set. They're using old style formatting and it says this works, but it's not an f string. This should yield a good answer fairly quickly. Quite often when you put all the information together to ask the question to someone else, the answer will become apparent to you because you put all the information in a way you haven't seen before, new ideas can come to you. As a result of that, you may realize there's something you haven't tried or there may be something that you didn't try right away. Thanks for watching, and I'll see you in the following lecture. 4. INTRODUCTION - Download & Install Python 3 (2024): Hello, everyone, and welcome to setting up Python section. My name is Andreas, and I'll be your guide. In this section, you'll learn how to download and install Python on three of the most popular operating systems Windows, MacOS, and Ubuntu Linux. You'll also learn how to operate idle, Python's integrated development and learning environment. Setting a Python is the first step to becoming a Python programmer. Many operating systems, including MacOS and Linux come with Python pre installed. The version of Python that comes with your operating system is called the System Python. The system Python is used by your operating system and is usually out of date. It's essential that you have the most recent version of Python so that you can be successfully following along with all the examples in this course. Important. Do not attempt to uninstall the system Python. The three operating systems covered in this course are some of the most popular operating systems for personal computers. But if you only have access to something like an Android. So let's get started by setting up Python on your computer. I'll see you in the next lesson. 5. Download & Install Python 3 (Windows): In this video, you'll learn how to set up Python on Windows. You'll learn where to download Python, how to install Python, and how to open the integrated development and learning environment also known as Idle. There are two ways to download Python on Windows. One is through the official Python distribution posted on python.org website. The second is through the Windows Appstore. The Windows App Store version of Python is excellent for students and educational purposes, but it has some limitations that the python.org distribution doesn't. In this course, you'll download the official Python distribution from python.org. All right. Let's start by opening your preferred Internet browser. Then navigate to python.org. At the top of the website, in the main navigation bar, there is the Downloads button. If you hover over it, you'll see a button to download the latest version of Python for Windows. At the time of this recording, that version is Python 3.12 0.5. Click on the button to download Python. When Python finishes downloading, you can click the EXE file at the bottom of your browser or use File Explorer to navigate to Downloads folder to open it from there. On the first screen of the installer, you can see that you're installing Python 3.12 0.5 or whichever version you download it. There's an Install Now button which will install Python as well as Idle PIP and Python's documentation. There's a customized installation button. You can choose the location of the install and select or deselect different features. There's an option to install the launcher for all users, which is recommended. And we'll keep checked in in this section, as well as an option to add Python 3.12 0.5 to Path. Let's talk a little bit about what that means. Before we determine whether or not you should add Python to Path, let's talk about what path is. Path is an environment variable on Windows that tells the command line where to look for files and folders. Now, if you don't know what an environment variable or the command line is, that's fine. The key takeaway is that Path tells the operating system where to look for things when you issue commands. Adding Python to your path allows you to use Python command in a terminal to run Python programs. Again, if this doesn't make sense to you, that's fine. So you should add Python to Paths. If you only have one version of Python installed, then you can safely add Python to Path in both cases. If you need multiple versions of Python installed on the same computer, then it's best to not add Python to Path. In either case, you can use the Python launcher for Windows to run Python programs instead of the Python command. In this course, we'll be using the integrated development and learning environment or idol instead of the Python command. In this course, it's assumed that you're installing Python for the first time and we only have one version of Python installed on your computer. Even though we won't be using the Python command in this course, it'll be helpful to have it available later on. So you'll see Python installed with the add Python to Path option selected. Let's get back to the installation. If you're installing Python for the first time and only plan to have one version of Python installed, then go ahead and select Add Python 3.12 0.5 to PAT. Then click Install Now. If you need to give your computer permission to make changes to your device, then go ahead and do it. Then click. On most computers, installing Python will just take a couple of minutes. Once Python finishes installing, you'll see a screen saying that the setup was successful. This screen includes links to the official online tutorial and the Python documentation. Go ahead and click the Close button. All right. So now you have Python installed, but how do you access it? In this course, we'll be using Python's integrated development and learning environment or Idle to interact with Python. There are two ways to open Idle. One is through the Start Menu. The other is through the Window search bar. To open Idle from the start menu, click on the Start Menu icon and then scroll down. Or click all Apps until you find the Python 3.12 0.5 folder. I have Windows 11 version installed. Inside of the folder, there's an application called Idle. Click on that to open Idle. This opens the Idle shell. At the top of the window, you can see the version of Python running as well as some information about your operating system. Below that information are three red angle brackets. These are called a prompt. Whenever you see this, it means that Python's waiting for you to give it some instructions. Now, go ahead and close Idle. To open Idle from the Windows search bar, start by typing Idle into the search bar. Under the app section, you'll see an option for Idle that says Python 3.12 0.5 64 bit. It might say 32 bit if you've downloaded a 32 bit version of Python for your system. Click on that to open Idle. So there you go. Now you know where to download Python, how to install it and how to open Python's integrated development and learning environment. If you'd like to see how to install Python on other operating systems like MacOS and Linux, feel free to check the next two lessons in this course. 6. Using the Python Shell: Hi, everyone. This is Andreas, and it's an exciting day as we're going to write our first command in Python. In this lecture, we'll learn how to use the Idle program that comes bundled with our Python interpreter. We'll be writing our code using the Idle program, so let's first launch it. You can search for it by typing Idle in the search box. Once it is found, click on the idol or the Python GUI to launch it. The Python shell appears on our screen. A shell is a program that lets you type instructions into the computer, much like the terminal or command prompt on the OSX and Windows respectively. We can enter one command at a time. The shell waits for a command and from the user to execute it and then returns the result of the execution. After this, the shell waits for the next command. The lines are starting with three greater than symbols. Let's do some examples. Type five plus ten, Enter. The shell returns to the answer 15. Now type five greater than one. You are asking the shell if five is greater than one. The shell replies true. So the shell is suitable for running one command at a time. It is a very convenient tool for texting Python commands, especially when we are starting to get started with the language. However, if you exit from the Python shell and enter it again, all the commands you type will be gone. Besides, you cannot use the Python shell to create an actual program, but if you want to write an entire program, the answer is the file editor. To code a simple program, you need to write the code in a text file and save it with a dot PY extension. This file is known as a Python script. You can enter the file editor from File and then new file. It's similar to a text editor, and it lets you type in manual instructions, save the file, and run the program. Keep in mind that the interactive shell window will always be the one with the three greater than symbol prompt. Instead, the file editor window will not have this prompt. In the next lecture, we are going to learn more about your coding environment. 7. Setting Up Python (Summary): Congratulations. You now have Python installed on your computer. Let's do a quick recomp of everything you learned. In this section, you learned where to download Python on Windows and MacOS. How to install Python using the official installers on Windows and MacOS or the appedPackage manager under the Ubuntu Linux. You also learned how to open Idle, Python's integrated development and learning environment. So where are you going to go from here? Well, you're ready to start coding in Python. You'll use Idle to interact with Python and to write and run Python programs. But Idle isn't your only option. You might want to look into setting up a different editor. To help you with that, in the next lesson, I'm going to show you an alternative Python editor, VS code or Visual Studio code. So it's a great alternative to the original Python Idol. I want to wish you all the very best on your Python journey, and I'll see you around. 8. Code Editors: When it comes to typing Python code, you have two options. You can use a code editor or an IDE, which is short for integrated development environment. An IDE is basically a code editor with some fancy features like auto completion, which means as you type code. This feature helps you complete your code, so you don't have to type every character by hand. It's a productivity boosting feature. It also gives you additional features like debuking, which means finding and fixing bugs in your programs, testing, and so on. For both code editors and IDEs, there are so many options out there. The most popular code editors are VS code, Adam and Sublime. You can use the code editor that you prefer. In terms of the IDEs, again, there are so many options out there. The most popular one is Pi harm. In this course, I'm going to use the official Python distribution or Idol as we discussed in the previous lessons. But in some exercises, I'm also going to use the VS code or Visual Studio code because that's my favorite code editor. Later in the course, I will show you how to install a plugin or an extension that will convert VS code to a powerful IDE. So before going any further, head over to code.visualstudio.com and download the latest version of VS Code. 9. Your first Python program – Introduction: Hey, everyone, and welcome to this new section. The first section was about getting Python installed on your computer. And now that you have it installed, it's time to start coding. In this section, you'll write your first Python script. You'll learn what happens when you run scripts with an error and you'll learn how to declare variables and inspect their value. You'll also learn a lot about how to write comments. Along the way, you're also going to learn the differences between what is called the interactive and the script windows inside of idol. You'll learn about the Red evaluate print loop, REPL. And not only will you be creating scripts, but you'll also learn how to run them. You'll learn about a very important operator called the assignment operator. What are the rules for creating variable names, and what is considered valid or invalid? Along with that, you'll learn a few of the standards that are outlined inside of PEP eight. So it's time for you to get started with writing your first Python script. 10. Writing our first Python Program: Okay, it's time to get started writing your Python script. You're going to be using a program that comes with your installation of Python. It's called Idle, which stands for integrated development in Learning Environment. It has two main windows, and you'll spend some time in both of them. The first is called the Interactive window, and I'll share that in just a second. Then the editor window, which is where you actually write scripts and programs that you'll save and run later. You can type code into both the interactive window and the editor window. The difference between the two windows is in how they execute code. All right. Let's take a look at the interactive window. If you don't already have Idle open, then go ahead and open it. You can find it in the folder that the application was installed in. In my case, I'm going to choose Python 3.12 and click on the Idle App. Idls Interactive Window contains the Python Shell. You can see this name up here, Idle Shell. It's a textural user interface used to interact with Python language. You can type a bit of Python code into the interactive window and press Enter to immediately see the result. Hence the name interactive. When the window opens up, it'll display the same text at the beginning. The text shows the version of Python that Idle is running and some of the commands that you can use to help or view information about Python. This spot over here, this is called the prompt, and it's where you're going to be able to type code. So right in front of this cursor prompt, go ahead and type in one plus one and then hit Enter. And you can see that it outputs two. Python evaluates the expression of one plus one and displays two, and then it displays yet another prompt just below that. Every time that you run code in an interactive window, a new prompt is going to appear directly below the result. When using the interactive window, it works as a loop and includes these three different steps. One, Python reads the code that you've entered at the prompt. That's again, the thing with the three different little greater than symbols. Two, it evaluates the code. Three, Python will print the result and wait for more input. This is referred to as Red evaluate print loop. We usually abbreviated as REPL. REPL, Python programmers usually refer to this as the Python Shell as the Python REPL or just repel for short. Okay, let's try something a little more interesting than just adding numbers. Rite of passage for every programmer is writing the program that prints the phrase, hello, world on the screen. At the prompt, go ahead and type in print, and then you can create a set of parentheses here. So I'm opening parentheses, and you can see that it's giving me a little bit of additional instruction here, which is kind of nice. And we'll learn all about this stuff as we go through the course. In this case, we're going to print some text. So we want hello world. And if I hit Enter, you can see that it outputs Hello world. This bit of code that you've typed in here, print is a function. A function is code that performs some tasks and can be invoked by its name. The above code invokes or calls the print function with the hello world text inside of it and outputs it. The parentheses tell Python to call the print function. If I just type print by itself, it won't know what I want to call it. It'll just tell me about it. It tells me that it's a built in function named print. In order to call that function, I need to put the parentheses and then tell it something of value. As you see, it's prompting me here to put it in there. And last time we typed the same thing, so I'll do it again. And Great. Those parentheses also enclose everything that gets sent into the function, goes into it as an input. And the quotation marks indicate that Hello world is really text and not something else that we might want to print. Inside of Idol, you can see some intriguing highlighting going on with different colors. With the current setup that I have, you can see that a function is different than the output, and you can see that something that's inside of quotation marks looks different than, say, these numbers up here. By default, functions are highlighted in purple and text is highlighted in green. This interactive window is really useful for trying out small code examples and exploring the Python language, but it has a big limitation. You have to enter the code one line at a time. So alternatively, you can save Python code in the text file and execute all that code in order to run an entire program. That's what we're going to switch into using the editor window. You'll write your own Python files using Idols Editor Window. You can open the Editor window by selecting file and new file from the menu at the top of the interactive window. Let me show you that. The interactive window is going to stay open when you open the editor window. It displays the output generated by the code in the editor window. So you'll want to arrange the two windows so that you can see them both at the same time. Inside the editor window, type in the same code that you use to print Hello World in Interactive window. Note that Idle highlights code typed into the Editor window just like it did in the interactive window. You don't have to add the prompt as it was in the interactive window. It's not required. Before you can run the program, you need to save it. So select File and Save from the menu and save file as helloworld dot PY. On some systems, it'll use a default directory where Python's installed. The same place that Idle is. Make sure that you don't save your files in that directory. Instead, save them to your desktop or to a folder in your user's home directory. I've created a folder called Python in my desktop, and I'm going to save the file there. The dot PY extension indicates that the file contains Python code. In fact, saving your file with any other extension is going to remove the code highlighting. IDL will only highlight Python code when it's stored in a dot PY file. To run the program, you can select Run from the pull down menu and run module. You also might notice some of the key commands being highlighted here. In this case, it's the function key five. So the program is going to output to the interactive window. You'll see restart and then the directory and the same name of the file that's being run and it's output. Idle restarts the Python interpreter each time, which is the computer program that actually executes your code when you run a file. This makes sure the programs are executed the same way each time. If you want to open a file, you can go to File and Open. And in my case, I'm reopening the file that we just saved under my Python folder and helloworld dot py. You can also open a file from the file manager, such as Windows Explorer or the Mac OS Finder by right clicking on them and say open with. All right. You've made your first program. Next up, it's time to make some mistakes. 11. Let’s make some mistakes: Okay, it's time to make some mistakes. It's really difficult to not make any mistakes while programming. And in case you haven't made it so far, I'm going to go ahead and have you practice making a few of them just to get an idea of what's happening. The first type that you'll be experiencing is called a syntax error. And the syntax error occurs when you write code that isn't allowed in the Python language. The language doesn't understand what you're trying to do. I'm going to have you go ahead and create an error in the code that you've already written. It's practice creating that syntax error. I want you to reopen your hello underscorworld dot py file. And at the end of it, go ahead and remove the second quotation mark. So it starts with a quotation mark and then hello world, but there isn't one that closes the quotation there. If you save that and then run or press the F five key, you get something new here where it says undetermined string literal detected at line one. Depending on the version of Python that you have, this message can change. Python 3.12 has added many more explicit explanations of errors, which is really kind of nice. And you'll see more of them throughout the course as we continue. But what you might see in an earlier version of this is a statement that says EOL, and EOL stands for end of line. In this case, it's been reformatted and says something a little nicer. So what is a string literal? Well, a string literal is what you've created here. But in this case, you haven't closed it or terminated it with the additional quotation mark. To create a string literal, you have to enclose the text that you want in both of the quotation marks. It can be either the double quotation or a single quotation, and you'll spend a lot of time on this in an upcoming course all about strings. To fix this syntax error, you would need to add that other piece and save. And then it can run and print out. So that's considered a syntax error. The other type of error that you'll experience in programming is called a runtime error. Idle catches syntax errors before the program even starts running. But in contrast, runtime errors only occur while a program is running. When an error occurs, Python stops executing the program, and then it's going to display several lines of text that is known as a trace back, and it's going to show a bunch of useful information about the error. What's very interesting about it, it's best to read them from the bottom up. I'm going to have you go back into your file, and this time, you're going to create a runtime error, and then you can see the difference between the two. To create a runtime error, try this instead. Remove both quotation marks. Did you notice how the text color changes to black when you remove the quotation marks? Idle no longer recognizes hello world as text. So what's going to happen here is this is a valid code. It understands it's syntax, but something different is going to happen. Go ahead and save that, and when you run it, you'll see this happen. So this is called a runtime error. And again, to read the trace back, this thing is happening here. It's best to read it from the bottom up. So it says right away, this is a name error. There is a name or something that you're calling for to be printed. It's called Hello, and it's not defined. It doesn't know, you know, what hello is or what it's referencing. It's valid as far as the syntax of it, the way it's written out, but hello doesn't exist. So it's not been defined yet. And that's something you're going to do in the next lesson is learn how to define variables. And if it were to continue, it actually would have the same problem with world. Again, you can read from the bottom up. So it's a name error. Name hello is not defined, and then it shows you that statement where that happens. And then it actually kind of goes a little further up here. This is the file that it's reading from. Sometimes Python projects have multiple files, and the trace back might lead into another file. So in this case, it says, Okay, where you have this saved in the name of the file, and that actually tells you which line it is. Again, you're not going to have such simple programs coming up. This one is just a single line one. So it's pretty straightforward where the issue is. But that's how traceback works, and you get to practice them much more as you continue along. So do you get the difference between a runtime error and a syntax error? Great. In the case of a syntax error, it won't let you even run it because it doesn't look like a normal Python code. It does not follow the correct syntax. In this case, this is a completely different error where it read through everything, but when it went to run it, it couldn't find hello being defined anywhere. Okay, it's time to do a little practice on your own. As a bit of a review, try writing a program that Idle won't run because it has a syntax error. Then write a different program that crashes only when it's running because it has a runtime error. You can find the solutions file in this lesson inside your resources. Okay. Next up, you're going to be learning all about creating variables. 12. Creating a Variable: Now that you've seen variables briefly in the last lesson, it's time to dive much deeper into talking about them. In Python variables or names, it can be assigned a value and then used to refer to them later on throughout your code. And that's the really crucial idea of a variable is that you can assign it and give it a value. But then if you want to reference that value anytime later on in the program, you can call up the name of the variable and use it again or potentially give it a different value. Variables are really fundamental to programming, and there's two major reasons. One, it keeps the values that you're trying to get inside your program accessible. For example, you can assign the result of some time consuming operation or expression to a variable so that your program doesn't perform the operation each time you need to use the result. It can just access the value right out of the variable. The other reason is that variables can give you context. When you have the number 20, it can mean several different things. It could mean the number of students at class. It could be the amount of times that someone has accessed a website or gone somewhere and so on. Giving the value 20 a name like a number of students makes the meaning of that value clear. In this lesson, you're going to learn how to use variables in your code and some of the rules and style guidelines behind that. To get there, though, to create a variable, you have to learn about something called the assignment operator. So let's start with the second word operator. An operator is a symbol such as plus or minus that performs an operation on one or more values. You used one earlier of two plus two, and it performs addition in that case. If it was two minus two, it would perform subtraction. In the case of assignment, values are assigned to variable names using a special symbol called the assignment operator, which is a single equal sign. And this can be a little confusing. You'll get to learn more about how this assignment operator works and how it's not necessarily comparing two things and saying that they're equal to each other. It's actually giving the value and assigning it to that variable's name. The operator takes the value that's on the right side of the operator and it assigns it to the name on the left. Let me have a look at that in the interactive window. Type this. If you're going to make a variable, its name is salutation. To assign it a value, you use the equal sign, the assignment operator. You're going to give it the string literal of Hello world. If you were to type print, then as the value, choose to use the variable name salutation. You would get the same output as if you were to have it print the literal itself hello world. Now, if you were to type salutation by itself, you would see it would be assigned to the string literal hello world. What if you were to make a typo when you went to print and you chose capital salutation? This is a valid code again. It shows that as far as the syntax is concerned, this works. But when I press Enter, you can see that I got a runtime error of a name error. The name salutation is not defined. And then, again, this is an advantage of Python where it's actually giving you a little better idea of the context of what's happening. And it says, Did you mean salutation? Because there is a variable named salutation in here, which is really nice. This is an update. You might not see this in an earlier version of Python. Oh, yeah. The case that you're using in a variable's name is important, and they are completely different. You might have learned in other programming contexts that maybe capitalization didn't matter, but in the case of Python, it does. Now there are rules of valid variables and names inside of Python. Again, to avoid things like syntax error. Variable names can contain uppercase and lowercase letters. Any of those are fine. It can include digits. It can include underscores. And the one trick, though, is that it can't begin with a number, can't begin with a digit. So let me give you a couple of examples. So a valid Python name could be a string one or an underscore A one S four, or list underscore of underscore cities. Some of the things that would not be valid would be starting with a number. So five cable or 65 tour. So just keep that in mind. You can't start with a number, can start with a digit. Okay? Great. In addition to the alphabetic characters that we just talked about and the digits in the underscore, Python variable names can contain Unicode characters. Unicode, if you're not familiar with it, is a standard for digitally representing characters, and they're used in most of the world's writing systems. So let me give you a couple of examples of things you might have seen. So decorated letters in French or Spanish or German, where you have like E with an accent on it or with an umlat, you know, different things like that that are decorated. You can use those characters in Chinese, Japanese or Arabic symbols, but not every system that you run your code in can display these characters. So it's something to be careful with, and it may work better to use the ones that we specified a little bit earlier. You're going to learn a lot more about Unicode in a much later section, but I'll also include some resources if you want to jump ahead. Choosing a good name for a variable is difficult. There are a few memes out there that show someone thinking really hard of, how do I come up with a name? And there are some guidelines that you may want to follow. The first one that I want to share with you is keeping things descriptive can be much better than keeping them super short. A variable named S is kind of difficult to know your intention of what that variable is, especially if it was something like seconds. That might be much more useful or even more explicit and descriptive would be seconds per hour. That may seem to you like a lot to type. What you'll learn is that there are lots of tools when you're working with an editor that can help you complete the names of things so that you don't have to worry much about keeping things super tight and short. It can be much more useful for you going forward to have a descriptive name than just a simple short name. The good rule of thumb is to maybe limit the variable name to three or four words at maximum. Alright. So I said that you could use lowercase or uppercase letters. Well, where should you use them? The case that you should use can vary depending on what you're wanting to do, but there are some guidelines. Let's talk about different ways that this can be done. One term that's used is mix case, where you start with, say, lowercase letters, and then every individual word that you're adding inside of that variable name, you make it uppercase for the first letter of it. So here's some examples. So like a number of students could be num capital students or a list of capital names and so forth. So that's called mixed case. The other way to do it is to use underscores, keeping everything lower case and then using an underscore in between each one of these. This is also referred to as snake case. That's what those variables would look like in snake case or lower case with underscores. In Python, it is more common to write variable names in that style. It's not prohibited to use mixed case, but it typically is more in the style of Python generally to do it that style. In fact, there's a whole topic about this, and it's referred to as PEP eight. PEP eight is widely regarded as the official style guide for writing Python, how things are named, how things should be formatted, how things should look. And you can learn a lot more about it by looking at this website, pepight.org. Someone has created this site to give you a tour of all the features in a nice formatted way. There's more information. I'll include a link in the description. Following the standards outlined and PEP eight will ensure that your Python code is readable code to most Python programmers, it'll look in the style of other Python users. As far as the name PEP, it stands for Python Enhancement Protocol. A PEP is a design document. It is used by the Python community to propose new features or changes to the language. When working with variables, it's nice to be able to inspect the values, and you can do that inside the interactive window. To inspect the value that a variable holds right now, you can type the name of the variable by itself at the prompt. Just typing the name by itself at the prompt will often display something different than what is displayed compared to using print. You can also learn about what the type of variable it is by putting the name of the variable in type. Let me show you what those look like. Let's say you created a variable of X and X is going to be assigned the value of two. If I type X and inspect the variable, you can see its value is two. And if I were to print, I get the same output. Now, it might look a little different if I were to say, assign Y to the value of string literal two. So this is text instead of an actual numeric value. So in that case, if I type Y, you'll see that it outputs something slightly different versus if I were to print it. So that can be a little confusing. And what you'll learn is that these are different types, and they're interpreted differently inside of Python. And this is a big subject that you're going to dive into in much later sections. One thing you can check is you can say type. You can see here that it'll ask for the object or name, and then it's going to return. That's what the arrow is indicating the object's type. And this is just a preview. So try it out with X. It says that it is a class of integer. Now, versus type of Y. Y is the class of a string, and they're represented differently when you simply just enter in the name of the variable. And keep this in mind that variable inspection like this, it only works in this interactive window inside of an REPL. For example, try running the following program from the editor window. So here, let's say we start by defining salutation and it says it equals hello world. And then on the next line, simply type salutation. What's it going to output when you run this program? As you can see when it ran it, it didn't output anything. That type of inspection of a variable only works here in the interactive window. As a review, here's a couple of exercises you can do using the interactive window. Display some text using print. And then using the interactive window, assign a string literal to a variable. Then print the contents of the variable using the print function. Repeat these first two exercises using the Editor window now with a file. You can find the solution file in the lesson inside of your resources. All right. Up next, how can you leave yourself notes inside of your code? Thanks for watching. 13. Adding Comments: In this lesson, you're going to learn how to leave yourself helpful notes. They're called comments. Programmers sometimes read code that they wrote a while ago and wonder, what does this do? When you haven't looked at a code in a while, it can be difficult to remember why you wrote it the way that you did. To help avoid this problem, you can leave comments in your code. Comments are lines of texts that don't affect the way that the program runs. They document what the code does and why you, the programmer, made certain decisions. Let's open up a previous file, hello world, and let's edit the code. All ended in the first line of the code. Salutation equals to hello world. Print salutation. To start a comment, you use the hash symbol, sometimes called the number sign. That's what I like to refer to it as. It's also sometimes called the pound sign in the US. The UK might disagree with that. A technical name is an Octothorp. You might have heard of that. Start with that hash symbol, and then anything you write after that is going to be ignored when the program is run. So if I save and then run this code, you can see that it just ran as it did normally. It didn't change anything about how this particular code runs. There's two ways that you can comment on your code. The first one starts with a hash symbol on a new line and it's called a block comment. The other style is called an inline comment. It continues on the same line with a hash symbol just after the code. You can still use that pound sign, the hash symbol inside of a string. For instance, Python won't mistake the following for a string. Let me go back to the interactive window. If I were to print a string saying number one, it wouldn't have a problem with that. It's still going to be printed because it's part of a string. In general, it's a good idea to keep your comments as short as possible. But sometimes you need to write more than reasonably fits on a single line. In that case, you can continue your comment on a new line and also begin it with a hash symbol. You can also comment out lines of your code. To do this, you place that hash number sign in the beginning of a line of a code. It's a non destructive way to test the behavior of your program without it running specific lines of the code. And there are a few recommendations for how you should format your comments. Again, these are according to PEP eight, comments should always be written in complete sentences. They should have a single space between the hash symbol and the first word of the comment. Inline comment should start with two spaces after your code. PEP eight also recommends that your comments are used sparingly. Comments that actually describe what is already obvious are unnecessary and can be a big pet peeve of many programmers. Comments are best used to clarify code that may be difficult to understand or to explain why something is coded in certain ways. Thanks for watching. 14. CHALLENGE: Interact with IDLE (Python Shell): Throughout this course, we'll be getting you involved in a lot of these interactive coding exercises. The idea is that you're not just sitting there watching me talk, that you're actually putting everything you're learning into practice. That way, it actually becomes your own. These coding exercises are great because we can give you instructions and show you what should happen if you write the correct code, what it needs to do, and what you'll be able to do with your code, as well as see it run in the console. It's through a lot of these exercises that you're going to be able to level up and you're going to become a better coder. So to make sure that you can interact with idol, try the following steps on your computer. Pause the video now and complete this challenge. All right. How did you get on? I really hope that you gave this a good go. Because it's in these moments where you're going to be learning to code. Of course, this is the very start. Now, this is a very simple exercise that is designed to make sure that you can locate the idle software on your program, start idle, and then do something very simple on it. So just type in a print statement. First, we're going to locate idle on your system. So I'll click here to search for Idle. Here it is. Alternatively, click the Star button. Locate the Python folder. And then you'll see an item for idle in this group. So just click on that. And that should start the idol running on our system. A Idol runs in this Python shell window. Here we have the interactive mode interpreter running, and we have the prompt, the three greater than signs. That's the prompt that is waiting for us to type a Python statement, and then it will execute that statement. So the exercise tells you to type a print statement. Let's go ahead and type that. Print. And then we have an opening parenthesis, and then we type the characters that we want to print inside a set of quotation marks. This is a test of idol. And then we put a closing quotation mark and closing parenthesis. Now I'm going to press the enter key, and we should see the result of this statement. So when I press the enter key, the Python interpreter executed this statement, and here we see the output. So if you typed everything correctly, your screen should look like this. It's possible that you made a typing mistake. For example, a common mistake is to leave out the quotation marks. So if you did something like that, let me just go ahead and purposely make that mistake. So there you can see that I typed in the statement, but I left out the quotation marks. And in this instance, I get an error message telling me that I have a syntax error, invalid syntax. So if you say something like that, look at the way the statement appears in your textbook and make sure that you type it exactly the way that it appears. Now, another common mistake is leaving out the correct number of parentheses, for example. So here I type the print statement out correctly, except that I haven't typed the closing parenthesis. Now, if I press the enter key, you'll notice that I don't get an error message, but the Python interpreter is actually waiting for me to complete the statement. The cursor just goes down to the next line, and every time I hit the enter key, it just goes down to the next line, but it doesn't give me any output. It's waiting for me to type the closing parenthesis, and then it gives me the output. So if you see that behavior, it's probably an indication that you've left out a parenthesis. All of these things you'll get accustomed to as you work more and more within the idle environment. Now when you're finished with Idol, you can go to the File menu and you can select Exit, or you can just type Control plus Q with a keyboard, and that will close it down. Thanks for watching. 15. How to Find Help: Yo. What's up, everyone. In this lecture, we're going to cover how to find help when you're stuck. Also, you'll learn the best web pages and resources for Python questions and answers. So let's get started. When you are learning to program at some point, you will get stuck. This is absolutely normal for beginners and also experienced users in programming. When you're stuck and before you can get help from anyone else, your first step should be to assess your situation. I mean, to question yourself and what you are trying to do and what result you have been getting. Solving programming problems is not as difficult as you may think. Let's do an example. Type in A plus B. And then press Enter. An arrow occurs in red color. Python prints a traceback when an exception is raised in your code. A trace back is a report containing the function calls made in your code at a specific point. No worries. I have a whole section explaining errors and how to handle them. It's not necessary to understand what the error message means right now, but I'll give you a brief explanation. This is a name error, one of the most common types of Python errors. A name error means that you've tried to use a variable that does not yet exist. A name error is raised when you try to use a variable or a function name that is not valid. In Python, code runs from the top to bottom. This means that you cannot declare a variable after you try to use it in your code. Python would not know what you wanted the variable to do. In our example, we have not declared a variable called A and a variable called B. To solve this problem, we need to declare A and B before we use them in our code. There are two main kinds of errors. A syntax error basically means that you made a punctuation mistake. These are the most common errors. Get used to reading that you've typed very closely and comparing it very carefully to what you should have typed. Logic errors occur when you've misunderstood what you're trying to do or what you've asked Python to do. These errors can be difficult to spot and more difficult to track down. The easiest way to get help is by copying the error message into the Google search, and you should see tons of links explaining what the error message means and what causes it. You can also try asking people directly in a web form such as stack overflow. Here is the web address. Stack Overflow is one of the most popular question and answer sites for programmers. It's very reliable because users can vote on the responses they find most helpful. So the best answers are usually the first ones you'll find. Another way to find help is through the official Python documentation. Here is the web address. It's useful and contains a lot of documentation. Finally, a great webpage is pythontutor.com. It has a tool to write or paste Python program and visualize what the computer is doing step by step as it executes those programs. 16. Writing your first Python program (Summary): In this lesson, I'm going to summarize the section and share some additional resources for you to continue learning. Throughout this section, you were introduced to several new concepts. You learn how variables give names to values in your code. You learn how to use the assignment operator to assign values to the variables. Learn about syntax errors and how they occur when you write code that's not allowed within the Python language. And you also learned about runtime errors and how they occur while a program is running. Runtime errors also give you a trace back that can show you useful information about the error and they're best read from the bottom up. How comments are lines of code that don't get executed and mainly serve as documentation. To test your knowledge, there's a quiz that you can check out for this section. Congratulations on writing your first program, and I hope to see you soon in the next section. 17. Strings and String Methods (Introduction): Hello, everybody, and welcome to strings and string methods. Python programmers deal with text daily, whether it's displaying text on a webpage or within a graphical user interface, or even accepting a input that a user has typed into your application. There are even entire segments of data science that deal with extracting information from text, such as sentiment analysis. Collections of text in Python are called strings, and there are special functions called string methods used to manipulate strings, like changing a string from upper to lowercase, or removing white space or replacing portions of the string with a different text. In this section, you'll learn how to do some of the manipulating of strings using string methods. You'll work with user input. You'll learn how to deal with strings of numbers and turning numbers into strings, how to format strings for printing. And along the way, you'll learn about F strings, multi line strings, and how to do string indexing and slicing. What is string immutability and how to discover additional methods using Idle yourself? Alright, it's time to dig into what is a string. 18. What is a String: Hello, everyone. This is Andreas, and I would like to welcome you to this new section. In the following lectures, you'll learn about the different kinds of data that you can work within your Python programs. We have a lot to do, so fire up your Python shell, and let's get started. A string is a series of characters, a text if you prefer. Anything inside quotes is considered a string. In Python, you can use single or double quotes around your strings. For example, if I type Python with double quotes and Python with single quotes, the result is not the same. It's essential to understand what we do when we use quotes and when not. If I type sales equal to 1,000 in quotes, sales is a string, not a number. But if I type sales equal to 1,000 without quotes, then sales is an integer. But how can you use a quote inside a string? Type and press Enter. This is invalid syntax, as you see, there are solutions for that. One way is to begin with the string and double quotes like this. Since the string starts with a double quote, Python knows that single quote is part of the string and not marking the strings end. But if you need to use both single quotes and double quotes in the string, you'll need to use an escape character or escape sequences. An escape character consists of a backslash followed by the character that you want to add to the string. So the escape character for single quote is this. Let's type the above string using now escape character and avoiding double quotes. I Great. There is another use of escape characters, which is the special meanings such as new lines, and we'll see it in action next. So here, D is being defined with a text. This is line one followed by a backslash N, which means we are meaning a new line. Now let's continue typing. This is line two. And the quotes of finished at the end. So here we have the backslash N character, which means a new line. If we use print D, you will see this is line one, and on a separate line, this is line two. Now, this is something that we use a lot, especially if we work with text files, and often you'll find you need to insert or remove a new line of characters from texts. It's also possible to do tabs with backslash T. So here you can see variables defined with some tab characters. And once again, printing this. Those are the tabs that have been inserted between the words. It's essential to be aware of the different escape characters you can insert inside the text. You can see a selection of escape characters such as backslash single quote, double quote, new line with N, carriage return with R, tab with T, and the ability to define characters using octal or hexadecimal values. All right. Let's talk about raw strings. In a raw string, escape sequence characters such as you saw before, are not interpreted. We're going to see how to define a raw character. Let's define a variable called A using the new line character. To create a raw string, a string is prefixed with an R as seen here. Otherwise, the context is exactly the same. Printing this out shows the raw string, meaning that the new line character is not interpreted by print at its left intact. This is useful in applications where the escape sequence characters are not to be interpreted normally, such as regular expressions. Sometimes you need to insert a multiline string. A multiline string begins and ends with either three single quotes or three double quotes. Any quotes, tabs, or news lines between the triple quotes are considered part of the string. Let's type the following. The result appears on the shell. Also, a multi line string is often used for comments. Great. I hope you understood what strings are and how you can create and use them. Keep in mind that strings are one of the fundamental data types in Python. Thanks for watching. 19. EXERCISE: What Is a String: Welcome back, everybody, to the first exercise of this section. Our exercise lessons are all about training. You'll train in the process of writing code by solving carefully selected exercises. You'll also train reading other people's code and communicating your thought process. Doing all that, you'll practice the concepts that you've learned about in the previous lecture and help make them stick. In the upcoming exercise lessons, I'll introduce you to tasks. Give you an opportunity to solve them yourself, and then show you step by step how I solved each of them. Go through three steps for each task, learn about the exercise, code your own solution, and then compare your solution and the process that got you there to mine. When I walk you through a task, I'll explain what I do and also why I do it like that. That'll give you a chance to compare not just our final solutions, but also how we got there. Ideally, this can help you gain some insights into the processes of getting from a task description to working solution in code. Okay, enough talking. Here is your first exercise. What is a string? Very philosophical question, but we're going to go about it in a little more practicality. Your task is going to be to print four individual strings that fulfill certain conditions. The first one is that there should be double quotation marks inside the string. The second one should have an apostrophe inside the string. The third one should have multiple lines with white space preserved, and the fourth one should be coded on multiple lines, but then it gets printed only on a single line. These are different ways of constructing strings, and it's just a way to remind yourself how you can create strings that fulfill the certain conditions. Go ahead. Do this now, and once you're done with your solution, hop over to the next lesson where I will solve the four tasks as well, and then you can compare with my solution. 20. SOLUTION: What Is a String: Here I am in the interactive idle shell. I'll go ahead and take quick notes of the different tasks that I've got to do here. There were four tasks. I always like to start by just taking notes on what I'm supposed to do, which helps me get organized and remember what the task is actually. So the first one was to print a string with double quotes. So I want double quotes in the string. That's the first task. Then the second one was to have an apostrophe in the string. The third one was to have a multiline string that also gets printed on multiple lines. And the fourth one was to write a string in multi line, but printed in a single line. So I just took some short notes to remind myself of the tasks and I'm going to get going. The first one is to print double quotes in the string, and I can do that using a single quotation marks to delimit the string. And then I can use double quotation marks inside. I open up a string by putting a single quotation mark. Then I can write something in here. So I will say, there are double quotes in this string. And I surrounded the words double quotes with the actual double quotes. And it should print fine because I'm not mixing the quotation marks. I'm using single quotation marks to delimit my string. And then the double quotation marks inside. They're not considered as string delimiters, but they're just the character's double quotation marks. So now I press Enter, and my print call executes, and I get as an output the string. Great. The second one, an apostrophe in the string. Do another print call, and now I will use double quotation marks to delimit the string. So I'm opening it up with a double quotation mark. Then I can write something. I will say, This string's got an apostrophe, and I use an apostrophe after the word string. So this string has got an apostrophe. This is not an English lesson, and I wouldn't be the best person to teach this anyway. But I do have a single quotation mark or an apostrophe in the string. And now I press Enter, and this will execute and work fine. Exercise three was to write a multi line string that also prints on multiple lines. So I can do this using triple quotation marks. So for example, double quotation marks or triple single quotation marks work the same. And now I can say this string was written on multiple lines. Well, not yet. Let me press Enter. And then I continue with the string and I say, it displays across multiple lines. And I need to close the string. So I'll close it again with triple double quotation marks. One, two, three, and then also close the parentheses from the print function. And now I'm ready to press Enter, and this executes. And as you can see, the new line character. So the enter that I pressed in here, this new line character is also part of the string. So the output includes it, and that's why it displays on two lines. And then finally the last task, write a multiline string that prints on a single line, and you can do that by escaping the new line character. Now, I'm just going to use one double quotation mark, and I'll say this one line string was written. And then I will use the backslash character, which escapes. It's a special character that escapes the following character, which in this case, is going to be a new line because after putting the backslash character, I'll press Enter and continue typing in the next line. But Python considers this to still be part of the previous line. So continue writing my strings, saying using multiple lines. And then close the string. With a string like this one that's delimited with only one quotation mark. Spreading a string over multiple lines like I do here only work when you use the backslash character. Otherwise, Python would raise a syntax error, and now press Enter. And as you can see, it displays on just a single line because I escape the new line character that I used here. All right. So that was a quick recap on the different ways that you can mix and match quotation marks when writing your string literals. 21. Manipulating Strings with Methods: Strings come bundled with special functions. They're called string methods that you can use to work with and manipulate strings. There are numerous string methods available, as you'll see. First, you get to focus on a handful of commonly used ones. In this lesson, you'll learn how to convert a string to uppercase or lowercase, how to remove white spaces from a string, and how to determine if a string begins or ends with certain characters. Okay, time to learn your first method. The first one is going to work on converting the case of the string. That method is dot lower. It'll convert the string to all lowercase letters, taking any capital letters and turning them into lower case. It looks something like this. If you add the string of Albert Einstein and then you add dot lower as a method, it'll return all lowercase characters. The dot tells Python what follows is the name of a method, and in this case, the lower method. You'll hear this referred to very often with string methods using a dot at the beginning of their names, for example, dot lower or as you'll learn here in a second, dot upper. This makes it a little easier to differentiate functions that are string methods from built in functions like print or type that you've learned earlier. The methods will work on a string by itself by adding the dot and lower. Don't forget to call the method with parentheses. They also work if you've assigned them to a variable. So in this case, let's type name and put the.in and want to return the lowercase version of name. Okay. Now that you've played with dot lower, the next you're going to learn is dot upper. So dot upper converts the string of all uppercase letters. So if you take the same variable name and apply the dot upper method, you'll see that it returns all capital letters. So just one more comparison between methods and functions that you saw previously. String methods will begin with a dot at the beginning of their names, and that's how you'll refer to them with the leading dot. So dot lower or dot upper. That'll make it a lot easier to differentiate functions that are string methods from built in functions like print or n. When you compare them aside from the different results of these functions, the important distinction is how they are used. These built in functions are just called by themselves. So if you want to find the length of a name string, you call Ln and put name inside of it. Or if you want a print name, you could just do the same thing versus on the other hand with upper and lower, they need to be used in conjunction with the string. They don't exist independently. White space is any character that is printed as a blank space. This includes things like spaces, tabs, and even line feeds, which are special characters that move output to a new line. Sometimes you need to remove white space from the beginning or end of a string. This is especially useful when working with strings that come from user input, something that someone's typed in, which may sometimes include extra whitespace characters by accident. There are three string methods that you can use to remove this white space from a string. Dot R strip removes the trailing spaces from the right side of the string. Dot strip removes the preceding spaces from the left side of the string. And Dot strip removes white spaces from both left and right sides, so anything at the beginning or at the end of the string would be removed. Interestingly, it doesn't remove spaces from the middle. Let's try some of this out in the interactive window. First, we need to create some white space. So I'll make a new name, put a couple of spaces and a tab, and I'll put my own name in again. You can use your own name. In this case, I'm going to add a couple of spaces and a tab, and then slash in which is a line feed. Actually, I'll add two of these line feeds with a couple of spaces in between. So there's a lot of different white space there. In fact, if you try to print out with name, you'll see all the white space, including the additional line feeds, the two of them. Okay? So what happens if you use dot R strip? It stripped away all the whitespace characters from the right side, including the line feeds. Again, name's still the same. So if I do name and dot strip, it'll get rid of the whitespace in the front. And if we use dot strip, it gets rid of the spaces on both sides, all the white space. Be it tabs, spaces or line feeds. When you work with text, sometimes you need to determine if a given string starts or ends with a certain character. You can use two string methods to solve this problem. The first is dot starts with, and the other is dot ends with. Let's try it out in the interactive window. Let's say we have a string bioelectric. We'll create a variable called power and capitalize bioelectric. If you use the method starts with, and in this case, you need to, you can see that it starts requesting what you'd like the prefix to be. And what if I put lowercase bio? Will that work? That returns false. You might have figured out why because it starts with a B. The fact that it starts with the method is actually case sensitive. To get this to be true, you'd have to type the same thing, but start with a capital Bo, that would return true. And similarly, if you wanted to try out another one ends with in this case, let's say you say, does it end with electric? You'd get true. This too is case sensitive. The true and false values are not strings. There are a special kind of data called booling value. You'll learn more about Boleing values in later lesson. Now, strings are immutable. Most string methods alter a string like upper and lower, but they actually return copies of the original string with those modifications. So if you aren't careful, you might not recognize this, and it might introduce subtle bugs into your program. Try this one out. So put a name this time Wells Virginia. Okay. So again, if you type name and put the method dot upper, you'll get all uppercase. But you might have noticed I showed this a little earlier, too, how the original is not modified. Now, to get it to change the variable name, you would need to reassign it. So that would look like this. Name equals name upper. Now, name has been changed. That will override the original string that you assigned to name by reassigning it. You might have noticed that there are a lot of methods associated with strings. The methods that I'm showing in this lesson barely scratch the surface. Idle can help you find these new string methods. Let me show you how you can discover some of them. Let's go back to our electric example. If you start with a variable name and then add the dot, a little box will pop up and start to show you some of the different ones that are available. If you type a letter, you'll also get some of them. It'll narrow down the results. In fact, if I start to spell upper, you'll see it highlighted there. You can complete this by pressing tab, and then you can finish by calling the method. This is a nice way that you can discover additional methods that are available. Okay. Now that you've practiced a little bit by trying to find some of those additional methods, here's a quick review. Using IDL, you can type the name of a variable that's assigned to a string, and then you add a period, often spoken as dot, and then you wait. Typing in a letter will narrow down some of the results and pressing Tab will automatically fill in that method name if you've started to name it. And one note, this even works with variable names. Try typing the first few letters of electric and pressing Tab. If you haven't defined any other names that share those first couple of letters, Idle completes the name electric for you. So tab is a nice sort of autocomplete that you can use across Idol. Okay. Time to review what you've learned. Time for practice. Exercise one. Write a program that converts the following strings to lowercase. Then print each lowercase string on a separate line. Exercise two. Try repeating exercise one, but convert each string to uppercase instead of lowercase. Exercise three, write out a program that removes white space from the following strings. Then print out the strings with all of the white space removed. Exercise four. Write a program that prints out the results of starts with B on each of the following strings. Exercise five. Using the same four strings as exercise four, write a program that uses string methods to alter each string so that the starts with B returns true for all of them. So again, write a program that uses other string methods to alter the strings so that start with B returns true for all of them. You can find solutions to these exercises and the code in the resource files of this lesson. All right. Next up, how to do string indexing and slicing. Thanks for watching. 22. EXERCISE: Change the Case: Here's your next exercise. It's about a change of case. In this exercise, your task is to change the case of strings. Just experiment and practice a bit with the different string methods that you can use for, changing case in strings. And the task is to write a program that converts the following strings to lower case first. And then you have four strings here. The first one is animals. The second one is badger. The third one is honey space B, and the fourth one is honey space Badger. And after converting all of them to lowercase, then you should convert each of those to strings and to upper case. And you should print each of the strings on a separate line. So the result of solving this task basically is going to be a whole lot of lines of print calls where you apply some string methods in it. Give it a try and then hop over to the next lesson and compare your solution to mine. 23. SOLUTION: Change the Case: The task is to create four strings, convert them all to lower case, and then convert them all to uppercase, each on a separate line. I'm going to start off by defining the strings and assigning them to variables. String one was animals in the title case. String two was Badger. String three honey bee. And string four honey Badger, the most dangerous of them all. All right. And now I'm going to write calls to print. Print, open parenthesis, string one dot lower. Close it, Enter. And I get animals as an output. Print string two dot lower. So this is a bit of a typing exercise, as you can see, because you're really just redoing the same thing for each of the strings. And later on in the course, you will also learn how to do this a bit more automated so that you wouldn't have to type so much. But for now, it does not hurt getting a bit of typing exercise and just practice using these string methods and how you apply them to a string, which is by first writing the string, then a dot and then the string method. And you use these parentheses here, in this case, they're empty to call this method. So it's similar to the print function, as you can see here where you also need the parentheses. Great. We converted all of them to lowercase. As you can see, the output is in all lower cases. And now we want to do the same, but convert them to uppercase. So we'll say PrintString one dot upper. Enter. And you can see that animals gets returned in all uppercase. Let's continue the typing exercise. PrintString two dot upper. Prince string three dont upper. And finally, string four dot upper. Nice. And this is the end of the exercise. 24. EXERCISE: Remove Whitespace: In this exercise, your task is to write a program that removes white space from the following strings. Then print out the strings with the white space removed. String one is filet mignon. I guess these are a couple of food items, but it looks like the person who wrote the menu had some issues with putting a bit too much white space in different places. So I'm making up the story around the task that you're the programmer of the restaurant and you're supposed to clean up the online menu, something like that. You see, the first drink has some white space on the left. The second one has some white space on the right, and the third one has whitespace on the left and right. So it's a cheese burger with some whitespace bun. One thing though, that's useful for you before you start this task, assume that I have typed five spaces at the front end end of each of these words because it'll make it easier for me than typing out these white spaces, even though it doesn't matter how many there are. Let's go remove some white space. 25. SOLUTION: Remove Whitespace: So the task is to remove the white space and clean the menu. Let's type these three strings. Now, I have access to all three of those string one, string two, and string three. And you can see that they have this white space that you should get rid of. Now, the string method to do this is dot strip. So you can say, for example, string three dot strip, and that'll remove the white space at both the beginning as well as the end. Which means that you could use strip for each of those strings, and it'll do what you're asked to do. But Python has two more specific methods here where you can just remove space from the right or the left side, which I will apply for the ones over here. String two, I can use dot R strip. It just removes from the right side, but not from the left. For string one, I can say dot strip. Which is going to strip away white space from the left side, but not do anything on the right side. You can either use strip for all of them, and that'll work, or you can use the more specific L strip and R strip for string one or string two respectively. 26. String Indexing: Often in programming languages, individual items in an ordered set of data can be accessed directly using a numerical index or key value. This process is referring to indexing. Strings are ordered sequences of character data and the individual characters of string can be accessed directly using a numeric index. String indexing in Python is zero based. So the very first character in the string would have an index zero, and the next would be one and so on. The index of the last character will be the length of the string minus one. Let's look at an example. So for the string apple, the first index, index zero, will have a letter A, and the last letter, which is index four is E. Let's try this out interactively. Here's a string A that would be apple. To access the first item in my string, I use square brackets. In this case with index zero, and it will pull out the first letter of my string, and so forth. So Index one will be the second character, P, and the last character E will be index four. Another way to get to that would be to use the built in len function length. So the length of the string A minus one will get the last character also. If I go to an index that is beyond the length of the string, I will get an index error, string index out of range. String indexing can also be specific with negative numbers. Negative indexing is also available. In this case, you go backwards. Negative one will be coming to the back, so E will be minus one, and negative five will be A, your first letter. Let me try that out. So A, negative one into square brackets will provide the last letter and so forth. Again, you could use the n function like this. That will be your first letter. With Index, you can access individual characters, and you can also grab ranges of that. It's called string slicing and comes up next. Thanks for watching. 27. String Slicing: Python also allows a form of indexing syntax that extracts substrings from a string. It is known as string slicing. The syntax that you use, it's really similar to indexing. Instead of just one value being put into the square brackets, you put two with the colon between the two. So in this example, D is a string, and M and N are two values that return a portion of D, starting with the position M and up to but not including position N. Let's define the string D for avocado. If you select index one up two, but not including four, what do you get? VOC. Again, zero is A, one is V, two is O, three is C, and four is A, also, but not including four. So what happens if you omit the first N or last index? If you omit the first index, in this case, A, colon, and then N, it's going to start slicing at the beginning of the string and go up to the not calculate index value N. Omitting the last index is not going to extend that slice from the first index M all the way to the string. Omitting both indexes, it's going to return the entire original string. It's not a copy. It's a reference to the original string. Let's look at these in practice. Type D, colon two, and it will return AV. Up to five, we'll return A VOCA. All the way to the end, you can do that by typing. Another way to do that would be to put the value of your starting index and then use the length function as your end index. If you try the strings with no values, it will start from the beginning until the end. It's a reference to the original string. Negative indexing works as well. You can also do a combination of positive and negative indexes. I'll start with an index negative five and go up to index negative one. What do you get? You get OCAD. When you do slicing, you can specify a string in a slice string. It's adding an additional colon and a third index designates what the stride would be. It's also called the step. So in this case, if our slice would come from the beginnings, then followed by step two, it would start with the very first item, which is zero and the letter A, and then skip taking two steps to grab the letter O and then skip ahead to grab index four, and then go to the end. What if we type colon colon with step two? It will grab those letters AO AO. You can also use a negative stride. That's it for today. I hope you understand what string slicing is. Thanks for watching. 28. EXERCISE: String Slicing: This exercise is about slicing a string, and your task is to print the string at by using slice notation to specify the correct range of characters in the string crate. So you start off with the string crate, and then you slice that string to take out only the part that says at. Rata ta, let's go. 29. SOLUTION: String Slicing: Alright, I've opened my Python idle. My task is to slice crate to get rat. So I'll start off by assigning the string crate to a variable. So I'm just going to call it word in that case. Okay, here we have crate, and then I'm going to use slice notation to get out the rat part of it. And to use slice notation, you use square brackets. Inside of the square brackets, you have to put in the indexes that you want to use. String indexing starts with zero. So C is at the index zero, and then I have R at the index one. So I can start off with one. And then in this case, I want to get everything that starts with one and goes to the letter T, which is in index three. This is also called the stopping index. So I can just do that by putting a colon there. I want to put a big fat disclaimer here. You have to specify one plus the last character that you want to get. So I want to go to four, which is the index of E, and that means that I'm going to get everything up to E. So word one colon four should give me the actual string that I'm looking for, which is Rat. So by typing word one colon four, I should get out just the string Rat. And let's confirm by pressing Enter. Here it is. I sliced a rat from crate. There you go. However, if you have a longer string and you want to get everything up to maybe the final character, but not the final character, then counting like this can get quite hard. So instead, you can go backwards. And you can also count indices starting with a minus. So the first one is going to be minus one, and then T is going to be minus two, et cetera. So I can instead specify words starting from one and then going all the way up to minus one, which is going to do the same as saying one up to four. So that's another way to just get rat. And now I found two ways to get at without the final character E. 30. String Concatenation: A couple of operators can be used on numeric operands can be applied to strings as well. In this case, the operator that looks like a plus sign is considered the concatenation operator and the multiplication sign operator, which in strings creates multiple copies of a string. So to start, the plus operator concatenate strings. It returns a string consisting of the operands joined together. First, I'll define some strings. A equal to apple. The next string objective that we'll create is B equal to banana. And finally, C equal to cherry. So what happens if I use the plus sign, the concatenation operator, A plus B and Enter. Let's combine all three things. It will concatenate all three. We can also concatenate strings into print functions like this. M. So that's the concatenation operator. Let's look at the multiplication operator, which is an asterix, which creates multiple copies of a string to return a string consisting of a concatenated copies of a string. Let me show you what it looks like. I'll create an object, D, which is an integer that is equal to five. What happens if you multiply A, multiply D? So the operator replicates the string object five times and concatenates them together. So the multiplier needs to be an integer. You can't multiply by a float number, for example. What if it is a negative number? That will return an empty string. 31. EXERCISE: String Concatenation: Here is your second exercise on concatenation Lesson. Create two strings, concatenate them, and print the resulting string. And then there's the question. Can you also add a space between them using only concatenation? So pick two words that you always wanted to concatenate together. I will pick the words bat and man. Go over into your Python Editor and make it happen. After that, move on to the next lesson and watch me do it. 32. SOLUTION: String Concatenation: The task was to create two strings and assign them to variables. Concatenate them without space and concatenate them with space. Let's get started by creating two variables that point to strings. I'll start with string underscore left, which I will point to a string called that. And then I'll do another one string underscore right. That I'll point to man. And now I can use a call to print to stick these two together. So I'll open up the parentheses after writing print and then I'll type String underscore left plus string underscore right. Close the parentheses. So as you can see here, I'm using the plus operator, which if you use it with strings, it concatenates them together. So it'll literally stick bat and man together without any space in between. I press Enter to confirm, and we get the string Batman stuck together. Now, the last task was to concatenate them with a space. So I will just copy my call to print and jump into the middle of this next to the plus operator. And here I'll add yet another string, a whitespace character. So I'm opening up to the quotes, putting a whitespace character, and then closing the quotes again. That's a perfectly valid string. It's just a string that only consists of one character, which is a space in that case. Again, I'm using plus operators left and right to stick these three strings together. So now in IbressEnter, I will get one string Batman all in one, and that's the exercise. 33. String Formatting: Now, I'll show you how to format strings using the percentage operator. This is also called the percentage string formatting or C style. The syntax for using the percent operator is the following. There are three parts to syntax, the string in quotes, the percentage operator, and values or variables to be inserted into a string separated by commas. The first stamp is to write the string to be formatted in quotes. After that, we write the percent symbol. And finally, we write the variables or values inside brackets. The percent format is used to represent a string, Andreas in this case. While the percent D format represents an integer, 75 kilograms in this case. Python Prince, my name is Andreas, and my weight is 75 kilograms. You can download a PDF that I've created, which is a list of complete sets of symbols that can be used along with percent. You can find it in your resource files. Instead of using the percent operator to format strings, Python also provides us with a format method to format strings. The syntax is string dot format, values or variables to be inserted into a string separated by commas. When we use the format method, we do not use percentage S or percentage D as placeholders. Instead, we use curly brackets like this. First, we write the parameters position to use inside the curly bracket, followed by a colon, and after the colon, we write the format with no spaces within the curly brackets. When we write zero colon S, we are asking the interpreter to replace zero colon S with a parameter in position zero that it is a string because the formatter is S. When we write one colon D, we refer to the parameter in position one, which is the integer. The format symbol is D. Notice that positions always start from zero. The result is the same as above. If you do not want to format the string, you can simply write. A The interpreter will replace the curly brackets based on the order of parameters provided. We covered the basics of string formatting methods, which we will learn in the next lesson in more detail. Thanks for watching. 34. F-Strings: An Improved String Formatting Syntax: Alright, let's talk about F strings. So why do I use Python three F strings? They are more readable. They are more concise, less prone to error and faster. But I'll start you off with the old school string formatting, the percent formatting, the string dot format. Let me start you off with a few examples. Open the Python Shell. Let's set up a variable and give it a name. For example, Alan. Use that variable in a string. Using percent a within your string and at the end of it. The percent and then the name of the variable, Enter. Suppose we have another one variable. Now we have two variables. We'd like to add to our string. This is the same with the name. And then we put in, are the age, percent and S. So in this case, we have two variables that we'll plug in. To do that, type percent, and then the name, age inside parentheses. What if you have a lot more variables? Let's set up some variables. To put all these in a single string, it starts to get a little messy. We'll have to count the number of percent S to make sure that we have them in the right order N which ones you are replacing. At the end here, we need to put all the variables inside parentheses. All right. It looks right. Press Enter. Fortunately, there are better ways to do this. Let's talk about string dot format. We can put placeholders in our string in curly brackets. And at the very end of the string, we would say dot format, and then we could put arguments in name and age. We can also reference the variables inside their index. Let's say this is Index one and this one is index zero. And we reverse order name and age. So we get the same result. Now let's talk about a new and improved way to format strings in Python, F strings. F strings are also known as formatted string literals and created in Python 3.6 version. They have simple syntax. They are evaluated at runtime, and they are formatted using the format protocol. Let me show you some examples. Let's set up three variables. Name, age, and profession to build a string inside our curly brackets. We put our expressions. And if you like, you can use F at the beginning of your string. Nice and simple. Now that I've shown you the simple syntax of F strings, let's talk about arbitrary expressions. You can do simple mass inside of curly brackets. You can do something like that also. I can also call functions and methods, but these are concepts that will do it later. Now we can also create multi line strings. This is a multi line message here. What does this message look like? Type message. Just remember that you need to put the F at each one for each of these to enter each of these expressions into the string. What about speed? F strings are faster than both percentage formatting and STR dot format. So I'm going to take you through a review of everything you've covered and learned in this lesson. We started with the oldest string formatting, the percent string formatting also called C Style. After that, we started to talk about the string dot format method, which started from 2.6 Python version. And finally, we covered the newest string formatting method, the F string, which started from 3.6 Python version. That's it for today. So thanks again for joining me in this lesson. And I hope you can now see how much more concise, readable, and convenient and faster F strings can be. 35. EXERCISE: Streamline Your Prints: In this exercise, you'll get to streamline your prints. Like you saw before, just concatenating them might get a little clunky. So here you've got an exercise where you can try three different types of displaying the same string using different ways of assembling the string concatenation, string dot format, and also using an F string. The task is to create a float object named weight with the value of 0.2, and then create a string object named animal with the value Anim and then use these objects to print the following string. So first, only using concatenation, the string should say 0.2 kilograms is the weight of an anim. And then you should display the same string using the dot format method and empty curly bracket place holders. And finally, I also do the same thing using an F string. Go ahead and solve that challenge for yourself, and then I'll see you in the next lesson. 36. SOLUTION: Streamline Your Prints: Here I am again in the interactive shell, and the task was to start by defining two variables. One was weight equal to 0.2 floating point. And then animal was the string that should point to the string Nim. Okay, let's start with the concatenation. I'm going to print it even though here in the console, we would get a result also if it didn't print it. But let's stick with this. And here again, I will have to convert the first one to a string because this is currently a float. If I try to add a float and a string together using the plus operator, that would give me an error like you saw earlier. So I will say string weight, convert it to a string explicitly, and then plus. Open double quotes and type. Space kilogram is the weight of the space again, double quotes again. And then I will concatenate that again with animal. So it says, 0.2 kilogram is the weight of an NM. And then I guess there should be a period at the end to make it a proper sentence. If I press Enter here, you can see that it says 0.2 kilograms is the weight of the NM. So that's a solution that works using just strnkencnation and nothing else. Now we're going to try to use the dot format method on the string. So again, I open up the print function. And now I can use the curly braces as the placeholder. This is a place where I want to insert something. In the first spot, I want to insert the weight. Then again, comes the middle part of the string. Kilogram is the weight of the, and now I will use another pair of curly braces where I will insert the animal. This should say Nim, and then I can put a period there. And now this is my string template, kind of, where I want to insert these two variables that I have to find earlier. And I can do that using dot format. So on that string, curly braces kilogram is the weight of the curly braces. I'm calling dot format. And now I will pass on the two variables that I want to insert into the two placeholders here. Into the first one, I want to insert weight, and then animal. And it's going to take the first argument and insert it into the first placeholder and then the second argument and insert it into the second placeholder. So if I now close the parentheses for the print call and then press Enter, then you can see I get the same output as before. So that's how you can do this using the dot format method. You can see that it makes it more readable already than just using the pure string concatenation, and it saves you the effort of having to do explicit type conversion on objects that aren't strings. And now, in my opinion, even a little more readable is going to be the F string. So again, I'm opening up a call to print. And in here, I will start by typing F and then opening up the string by just doing two quotation marks. And I will again use the curly braces placeholder. But now instead of keeping it empty, I will put in the variable name directly. So I'm going to say weight, and then the middle part of the string kilogram is the weight of the. Open up another set of curly braces and input animal directly into the curly braces, and then a period at the end. And that's all you need to do for the F string. If I press Enter now, you can see that again, you get the same output as in the two other variants. So these are three different ways of assembling this final string that gives the information that contains both a string, the NEM string, as well as the string representation of a floating point number. All right, this is the way you can do this. Let me know which is your favorite. 37. Interact With User Input(): To be useful, the program usually needs to communicate with the outside world by obtaining input data from the user and displaying result data back to the user. This tutorial will introduce you to Python input and output. Input may come directly from the user via the keyboard or from some external source like a file or database. Output can be displayed directly to the console or IDE to the screen via a graphical user interface or again to an external source. Programs often need to obtain data from the user, usually by way of input from the keyboard. The simplest way to accomplish this in Python is with input. Input is an excellent function in Python and is often used in programming. It pauses your program and waits for the user to enter some text. Once Python receives the user input, it stores it in a variable. Let's make some examples. Type. Once the user presses the enter key, all characters type are read and returned as a string. Note that the new line generated when the user presses the enter key isn't included as part of the return string. If you include the optional prompt argument, input displays it as a prompt to the user before pausing the red input. The input function takes one argument. The instructions you want to display to the user. Then the user sees the prompt, what's your name and waits while the user enters their response and continues after the user presses Enter. The response is stored in the variable message. Then message displays the user's input. It's better to add a space at the end of your prompts after the question mark in our example to separate the prompt from the user's response. Also, I use double quotes because I've already quoted it inside the text. Now let's try something different. We want to write a prompt for longer than one line. The first slide stores the first part of the message with the variable prompt. In the second line, the operator plus the string stored in a prompt and adds the new string onto the end. The backslash N change line. The prompt is then stored in a variable name and pass that variable to the input function. Finally, we print the text high, the variable name and the phrase, my name is robot. If you see carefully the code line, the syntax error is because of the quotes. I opened with double quotes and closed with single quote. Let me fix that. Great. Input always returns a string. If you want a numeric type, then you need to convert the string to the appropriate type with the NT, float or complex built in functions. This line converts N to an integer so the print statement succeeds. I think you're ready to explore user input a little bit deeper on your own. Here's some review exercises for you. Try writing a program that takes input from the user and then displays that input back, kind of like what you've done already, but change it up a bit. Try writing a program that takes input from the user and then displays that input in lowercase. Try writing a program that takes input from the user and then displays the number of characters, counting the characters of the input that was typed in. As always, you can find the solutions to these exercises and the code in the resource files of this lesson. All right. Up next, you're going to start working with strings and numbers. 38. EXERCISE: Interact With User Input: In this exercise, you're venturing into the world of interacting with your users. And in this case, you should write a program that takes input from the user, then displays that input back, but first convert it to lowercase. So if the user writes hello in uppercase or in mixed case, they should always get it back in lowercase, whatever they type in there. Then there's an additional little task where you can also display the number of characters that the user input. Okay. Think about this. Take a moment, write it out in your editor or in the REPL, and then move over to the next lesson and compare it to my solution. 39. SOLUTION: Interact With User Input: To solve this exercise, you're going to need to use the input function in Python to collect the user input and then some string methods to convert it. And then there's also a function called n that can help you to get the length of the strings. I could do this over here in Idle now, and I'm probably going to experiment a bit. But I also opened up a file where I'm going to write the code so that I can run it multiple times easier without having to type it out every time. That gives me a chance to actually also test and see whether my script works, not just for one input, but for the repeated different inputs. So I'm going to write the code in the script, but you can also write it over REPL if you want. These are the three tasks that my script should do. I'm going to start off with number one, where I'll use input with a little prompt in here. The prompt is going to say type something. And I'm adding this space here to format it a bit nicer. Then I need to collect the result of this. So if I just run input like that, let's try out over here in the REPL. I'll get the prompt that says type something. And I can say hello, and it gets returned. But in my script, I'm currently not collecting it anywhere or also here in the Idol shell. I wasn't collecting it anywhere, so I need to assign it to a variable that I can then do something with it, like lowercase it and display it and get its length, et cetera. So back in my editor on line one, I'm going to say, user underscore inputs equal the return of calling input and whatever then the user types in there. And then I want to convert it to lowercase and display it. So let's start with this. I will use the print function by typing print, opening the parentheses, and then putting in the user underscore input dot lower. So this is just the dot lower string method that you've used a couple of times by now and displaying it back to the user by using the print function. I'm going to test this script by running it in idle. You can press F five to run it, save it, and run it. So we'll do that. We can see over here, I get the prompt to type something. I'm going to try again to say hello in all upper case, you can see that my script works. I get back the same string, but in all lowercase, another advantage of having a script here is that I can just run this again without needing to type anything else. I get another prompt and I can try out mixed case. Hello. And again, I just get it back in lowercase. So this is working. Now I'm going to solve the task on line three, print the length of the input as well. For this, I can just use the len function. The len function works that it takes in a collection, for example, a string, and then it just returns the number of items in that collection. So if I put a string here and I said, hello, I get back five, which is the number of characters. One, two, three, four, five. So that's exactly what I want. And back in my script, I'm going to say print. Open up the parentheses, and then I will say Len because that's what I want to print out. N as an argument, I'm going to pass user input. Note that the user input that I'm passing here is actually the original one. So it's not the lowercase one, but it doesn't matter because dot lower is not going to change the number of characters. It's really just going to lowercase it. So both the lowercase version and whatever the user input case version is going to have the same amount of characters. And now I'm going to test the script again by running it. Save and run. Type something. I already know that hello has five, so we will use that and type of mixed case hello. Press Enter. And as an output, I get the lowercase version of that string and the number of characters in that string. Great. That solves all three tasks here. 40. Working With Strings and Numbers: Now that you've worked with user input a bit, let's talk about working with strings and numbers. When you get user input using the built in input function, the result is always a string. There are many other situations in which input is given to a program as a string. Sometimes those strings contain numbers, and they need to be fed into calculations. In this lesson, you'll learn how to deal with strings of numbers. And you'll also see how arithmetic operations work on strings and how they often lead to surprising results. Then you'll learn how to convert between strings and number types. Let's start out in the interactive Window. Try this out. I'll have you create a variable called Num. Then I'll assign it the string with the number two in it. So this is Num with a string literal with two in it. What if you use the plus operation and say num plus num? What does that do? You might have thought about this already that it's going to concatenate them together. It doesn't equal four, but two and two, which is 22. Well, the string 22, not the number. If you took NUM and you use the asterix, which is the multiplication operator, and you say, Okay, multiply that by five. Well, that should equal ten, right? Well, in this case, it's going to create a string with the number two being repeated five times. So you get a string of five twos, concatenating them altogether. Using the strings with arithmetic operators, now you can tell that it behaves a little differently than you might have thought. The plus operator can catenate two strings together as you've practiced before, and the asterix or the star multiplication operator, creates multiple copies of a string. And it doesn't matter if the number is on the right side of the expression or the left. Say you had seven times numb, it still sees NUM as a string, and seven is just going to be the number of times that the number that's inside of Num, the string is concatenated together. You actually do it with other things, right? You could say five times hello. One thing that you can do is, let's say you said the string of 12 multiplied by the string of three. Then we'll give you a type error. You can't multiply these two together because it says that you can't multiply a sequence of type string. So the sequence it's talking about is the string one, two, which is a sequence of two characters, and then trying to multiply it by three, which is a non integer string. So this doesn't work. It's raising a type error. And similarly, what if you took the string of three and you tried to add it to the number three by itself? Gives another type of type error. It says you can only concatenate string, not an int to a string. If an object on either side of the plus is a string, then Python tries to perform string concatenation. It will only perform in addition if both objects are numbers. You would have to first convert that string three into a number before you could add it to three. Let's look at how to do that. So what do you do with all these strings that you would prefer to be numbers? You're going to use some built in functions for that. The INT function converts objects into whole numbers or is also known as integers. Sometimes you're going to want objects to be turned into numbers that actually have decimal points. In that case, you'll want to use the built in float function. Let's try these out. To test this out, head back to Idle, and you're going to create a new file. You can use the pull down menu of file and New or you can use the key command of Command plus N or Control plus N on Windows to open an edit window. Over here in the edit window, we create a Num object. And it will accept the input from a user. And this is the prompt. You're saying enter a number to be doubled. Close that out. So the built in input function is going to prompt this, and then whatever the value that's typed in will be assigned to the variable NUM. Then to create doubled NUM you will say NUM is multiplied by two. Then the print output. Great. Go ahead and save that. I'll call it doubled or double dot pi. And again, just save it to my desktop. In this case, if you press F five to run it over here, it's asking you for a number to be doubled. And I will say, Oh, six, please. Oh, you see my error? I created a variable with the wrong name here. I didn't use the correct name again, so I need to either change it here or change it there. So I'm going to change it here or change it there and save. So a little name error issue. All right. Now that I've saved it, we can run it again. Okay. This time now I can type six. Instead of getting six times two of 12, I get 66. So six and six because it's doing that for two strings. So we've got to figure out how to change this. Open up a new shell window here to kind of clean things up a little bit. You can keep going in yours. I just want to not have so much typing on the bottom. So how can you work with this? Well, we were dealing with the number six earlier. What you can do, again, instead of just working with the number six by itself as a string is you can convert a string like six into an integer. And you can see INT will convert that into an actual number value of six here. It doesn't have the quotation marks around it like a string literal. INT stands for integer and converts objects into whole numbers, whereas float is going to convert it to a number with a decimal point. So if I were to use float for six, you'll see 6.0. Okay, so what do we need to do? Well, what we can do is convert it here and say INT for the number. This is one solution. Let's try it out. So I just saved it again. If I press F five to run it, Oh, this time, let's say 12. Great. There, 12 multiplied by two is 24. But what if I wanted to type in, I don't know, 2.5. Well, then we would need it to be afloat. And it wouldn't be bad if this were 12 point oh. So maybe it would be safer depending on what we want to type in. A little more flexible to use float instead. So I'm going to do that, and let's run it after saving. Now, if I were to, like I said, type 2.5, Oops. I forgot to change the INT to float here. Did you notice my error? Yes. Now, let's run again in type 2.5. I'll say 5.0. Or even if I were to run it again and type in 12 point oh or even 12 by itself, it will come back as a floating point. Why did we use float instead of INT? If you gave the built in INT function something that is not in base ten, like if you were to say 2.5, it gets a little angry. It says that's an invalid literal for INT with this requirement of base ten. So even if you said 12 point oh, you get the same kind of error. So float gives you a lot more flexibility, depending on the string that you're putting into it. Sometimes you need to convert a number into a string. To do that reverse, there is a function for it, too. Let me give you an example. Let's say we're going to do some concatenation again. Let's say we have a variable called the number apples, and it's currently four. You're super hungry and you say, I am going to eat. Then concatenate the number of apples to another string with apples in it. Automatically print that out and insert the number. Well, you can only concatenate a string, not an integer to a string. Since the variable num apples is a number, Python can't concatenate it with the other string. You need to convert the Num apples integer into a string, and that's where we use the built in STR function. Just like INT and float, there's a built in function STR that returns a string version of an object. And here you can add the built in STR function which takes an object and puts it into a string. Great. Let's see if that works. Yep. That works great. What's kind of cool is the built in STR function can actually handle arithmetic expressions right inside of it. So let's say you had a total apples that was four. And these are how many that you've eaten so far, which is two. So we've assigned two variables, total apples to the integer four and apples eaten to the integer two. And you want to create a string that says only space can catenate. And this time, you're converting to a string. And you're going to say the total apples minus the apples that have been eaten and concatenate that to show the number of apples that are left. I So it can do that subtraction right inside there. Let's look at some additional exercises for you to practice with these. Exercise one. Create a string containing an integer, then convert that string into an actual integer using the built in INT function. Test that your new object as a number by multiplying it by another number and displaying the result. Exercise two. Try out the previous exercise again, but use a floating point number and the built in float function. Exercise three. Try creating a string object and an integer object. Then display them side by side with a single print using the string function. Exercise four. Okay. In this one, you're going to use input twice to get two different numbers from a user, then multiply the numbers together and display the result. The printout should look something like this. You can find the solutions to these exercises and the code in the resource files of this lesson. Up next, you're going to learn how to streamline your print function. 41. EXERCISE: Work With Strings and Numbers: And you'll continue with some more input exercises. This one is called Working with strings and numbers. Write a program that uses input function twice to get two numbers from the user, multiplies the numbers together and displays the result. If the user enters two and four, for example, the new input should print the following text. The product of two and four is eight dot zero. What you can see here is that the result should be displayed as a floating point number. And then keep in mind that the input function always creates a string that you can convert certain strings into actual numbers using the int and the float functions, and that you can convert numbers to strings using the string function STR. So what you'll have to do is user input collection, then type conversion, and then also a little bit of math and displaying it back to the user. Give it a try yourself, and then if you want, you can watch the next lesson where I'll solve the task. 42. SOLUTION: Work With Strings and Numbers: I've opened up a new file and wrote down a couple of notes for the instructions. I want to get two numbers from the user, multiply them, and then display the result. That's the things I want to do in this multiplication. There's actually, another step in there. I'm also going to want to convert them to numbers. So I can do that at some point, but I need to do it before I multiply them. And that's because you can't actually multiply two strings together. That's just going to be an error. So I hop over to the REPL just to show this to you. If I have two strings and try to multiply them together, I'm going to get a type error that Python can't multiply sequences by non int of type string. This is a nicely descriptive message that just tells me that that doesn't work. But if you do collect user input, it's always going to be a string, even if the user types in a number. Try that out too. So I will assign the return value of input to A. I'm just going to give an empty prompt here. And so the prompt, it prompts me now to input something. If I input here four. So I'm thinking that I'm inputting a number. What I get as a result is still a string. As you can see, it's a class STR. It looks like that. So if you're collecting user input, it's always going to arrive as a string. And then if you're trying to multiply two strings together, you're going to run into an error. There's a little fun on the side, though. If you had a different program that had a fixed integer that you're multiplying the user input with, let's say, then if you don't do a type conversion here, you could run into an output that you might not expect. We have a, which points to four, right? And let's say the program multiplies the input of a user by 20, right? So what you get in that case is a string concatenation. Python concatenates the input string 20 times. So you get 20 fours as an output, which would be a strange calculation result for doing four times 20. So to avoid that, you need to explicitly convert it. You could, for example, convert A to an integer and then do the multiplication, and that works out, right? That works correctly, and math makes sense again. That's just to keep in mind that you will need to convert these numbers. With that, let's get started by collecting the two numbers from the user. Let's return to our editor and go to line two. Letter A is input. Now open parentheses in double quotes and type. Enter a number. Give them a prompt to make it a bit more readable, and then the same thing again for another number. I'll say B is input. Then type, Enter another number. Then I want to convert them to numbers so that I can multiply them. I'll do it in one step. So I'll convert to floats because in the output, I want to have floats. So saying explicitly converting both A and B to floating point numbers and then assigning that to a variable called product. Here I'm doing the conversion and the multiplication in one step. And then finally, I need to display the result. I'm going to do this just using string concatenation, which, as you'll see, is going to get pretty long. You've probably already encountered a better way of doing that. But for now, let's just stick with string concatenation because I also want to show you something similar to multiplication that doesn't work with two strings. You can't do concatenation if not both of them are strings. So in order to be able to display this message, the product of here, you can just use the variable that I've collected because A is a string, right? I'm only converting it in the multiplication to a floating point number. So A still points to the original string entered. So I can say the product of A and B, is And now, if I just add the product here without any conversion, I'd again run into an error. Let's try that out on the console. So here what I'm trying to do is concatenate a string and a floating point number. So it's marked it over here. I'm going to say, A, this is my string plus a floating point number, 0.2. And you can see that Python again gives a type error where it tells you that it can only concatenate strings to strings and not a float to a string. So in order to be able to put product into the string that you're concatenating here, you'll have to explicitly convert it to a string by using the STR function and passing product as the argument. With that, it'll work out. And you can continue also adding yet another string, which in this case, it's just a period. All right. So this is a really, really long way of assembling this message, basically just using string concatenation. But let's give it a try and see if it works. I save and run it. Enter number two, enter another number four, and the product of two and four is 8.0. So I'm getting the expected output. The result of the input looks like a floating point number. But here in the print call, you're converting it to a string before concatenating it with other pieces of the string that you're assembling. If you've used dot format or an F string for the final message, that's also a great way to go. So if you're stuck with string concatenation up to now, you'll get a chance to try out something new. 43. Print() Formatting Methods: Hello, everyone, and welcome back to the course. In this lesson, I'll spend a bit more time on how to format strings so that you can create more complicated messages inside of your print function. First off, you can concentrate two strings to create a third one. Hello plus world would result in a third string called Hello World. You have to be a little careful in Python. This doesn't actually edit the string. It creates a third brand new string. This can make string manipulation a little memory intensive and slow in performance. Over the years, Python has added several ways of manipulating strings. The first is similar to C, supporting the percent a notation. The second has placeholders using curly bracket, and the third, which is fairly recent, is an F string. We already discussed these three methods when we learned about strings. Now I'll show you how to embed these formatting methods into print function. Generally it's recommended to use the F string as much as possible, but there's still a couple cases where C style might be more important. I'll show you how to use these two in the terminal right now. I'm going to start out by creating a few variables here. First name. Last name age. And the first formatting example is percentage S. The percentage as in this string is a placeholder for where the content is going to be injected. The percent at the end of the string says what to inject. In this case, the value of last names gets put into the string. You can put multiple percent inside of a format. In order to do that, you must pass a turple to the string instead of a single value. Notice that if you want to use the last name twice, you have to use the 2% S, one for each instance of the last name and the variable twice inside of the tuples. Percent S says that you're going to be putting a string in. Percent D says that you're going to be putting in an integer. Percent F is for floats. Type in. The number cut off 3.14. Why is that? Let's explain here. The first number is the total minimum number of digits that the string should contain. The number after is the decimal. It stands for how many numbers to show past the decimal point? That's why the result is 3.14. So if I were to change this to three, it would show 142. If I make it a large number, for example, eight, it will fill in the rest of these numbers with zeros. Now let's change the first number. Let's say 20 and run the program. Notice how we fill a bunch of white spaces. Now, let's remember how to convert to a string. We could also use a percentage sign R, which does the same thing with the percentage S sign. Let's do another example using multiple percentage signs. Python will take them in order. The first percentage side will be assigned to the first item, and the second percentage sign will be assigned to the second item. Okay, now let's do the same example using the second format method type. And I'm going to use curly brackets here and put some arbitrary variable level. For example, X close with quotes and then a period and call the format method on that string. Then the variable X and my name as a string. Nice. Let's change that code, adding the following phrase and a second variable label. For example, why? Python three introduced the concept of an F string. The F in front of the string indicates that this is a formatting string. Now, curly brackets indicate where to put the injection. This is the same as the first example. I find this mechanism far easier to read, particularly if you've got multiple variables. Format strings support calculation. They also support formatting. Let's open a new shell window, import the first module math, which provides access to mathematical functions. Inside of the curly brackets, you put a colon, indicating your format mechanism. Oops, I forgot to define the variable age. The 0.2 F is similar to the 0.2 F above, giving us Alan Turing's age times Pi to two significant digits. Great. Make sure to take your time and watch the lecture carefully. If you have any questions, please post them on the Q&A discussion board. Thanks for watching. 44. Finding a String in a String: Now that you've worked out how to streamline your prints with F strings, it's tied to find a string within a string. One of the most useful string methods is find. As its name implies, this method allows you to find the location of one string within another string, commonly referred to as a substring. To use find, you tack it on the end of a variable or a string literal with the string you want to find typed between the parentheses. The value that Find returns is an index of the first occurrence of the string you pass to it. Let's take a look at that in the interactive window. Let's start with a phrase. So the variable phrase is going to be assigned to the string literal. The fire alarm keeps beeping. If you were to use the fine method instead of the brackets, you choose what the substring is that you're looking for within the string. So in this case, we're going to say, look for fire. Let's type. Phrase on finden, fire in double quotes, close parenthesis. It will return the index of the first occurrence of the substring inside the string. So in this case, it's the fourth index point. So here's zero, one, two, three, four. I know that's the fifth position, but again, starting from zero, zero, one, two, three, four. That's where this begins. Great. What if the substring doesn't exist within the string? Let's type phrase dot find in a random word. You'll get a return of negative one, meaning that it did not find it. So as a note, don't forget that it requires that the case matches. So if I give it a F for fire, it will return negative one. Let's try another example. I'll call it a new phrase. And it will be equal to I put a string inside your string. In this particular case, when you say new phrase dont find, what will you get if you type in string? So in this case, it's just the first occurrence. It did not return the second one. That returns the index only of the first occurrence, starting from the beginning of the string. And note, if you had a string, let's say of a phone number. If you are trying to find the number four, as in this case, an integer, it gives you an error. It's saying here in the feedback, it's a type error. The value needs to be a string, not an integer that it's going to search for. So you would require finding a literal string of four and it's right there at the very beginning index zero. Sometimes you may want to replace all the occurrences of a particular string within a string. Since find returns the index of the first occurrence of a substring, you can't easily use it to perform this operation. But strings have a replace method that replaces each instance of a substring with another string. Just like this method find, you tack replace onto the end of a variable or a string literal. In this case, though, you need to put two strings inside the parentheses and separate them with a comma. First would be the substring that you want to find, and the second is a string with which you want to replace Ido currents of the substring. Let's try that out in the interactive window. So just like find, you tag the method replace onto the end of the variable or the string literal. Let's try that out. Let's say we had a variable called My story. Okay. And in this case, you wanted to replace using dot replace. And you can see here it says, put in the old, meaning the substring you were looking for to be replaced by the new string. So I'll say, look for the truth and replace it with lies. Now, how cool is that? Now, what happened to my story itself, you might remember that strings are immutable objects, and replace won't alter the my story variable. And using the replace method doesn't alter the string my story. If you immediately type my story onto the interactive window, you'll see that if you wanted to change the value of the string my story, you need to reassign it. So, again, a bit of a refresher on this, you would say, I would like to assign my story to, in this case, this replacement. So, you'd say, Let's say we want to do the same thing, exchanging the truth for lies. So now, what's inside my story? You'll see here that it's been modified and reassigned. Replace will replace every single instance of the substring with the replacement text. What if you had another string that was assigned to some of the stuff? So here's the text, and you wanted a new version of the text. And you wanted to do a couple of replacements. Say you wanted to replace some of with all But you also wanted to replace stuff with things. Well, you'd have to do them one at a time. So New text says all of the stuff, and you could say, Okay, well, new text. I also want to do new text don't replace stuff coma things. So now you've accomplished both. The replacement method replaces every instance of a particular substring with a replacement text. Now, if you want to replace multiple different substrings within a string, then you need to use replace multiple times. It's time to challenge yourself with some new review exercises. Exercise one. In one line of code, display the result of trying to find the substring lowercase A in the string of three A. Note, the result should be a negative one. Exercise two, replace every occurrence of the character S with X. In this string, somebody said something to John. Exercise three, write a program that accepts user input with input and then displays the result of trying to find a particular letter in that input. You can find the solutions to these exercises and the code in the resource files of this lesson. Thanks for watching. 45. EXERCISE: Find a Letter in a String: Your next exercise is called find a letter in a string. Here you should write a program that accepts user input with the input function and displays the result of trying to find a particular letter in that input string using dot find. Which letter isn't defined here. So it seems like this is going to be another input, probably from the user, or maybe it's just not a very good description. Anyway, so I'm going to add this description that the user should be able to input both the word or the sentence and then also what letter to search for in this sentence. Okay, give it a try and then move on to the next lesson. 46. SOLUTION: Find a Letter in a String: So the task talked about writing a program, which usually is an indicator that you should use a script for it. So again, I've opened up a new script and then put it to like short notes. I want to collect input and then display the results of searching for a letter. Let's start by collecting input and then saving that to somewhere. So my text is going to be input enter a letter. Then I want to display this result of searching for a letter in that text. So I want to say text dot Find. And then a letter. What is the letter? I don't know. I could search for just, like, a hard coded letter, for example, X in here and then print the result of that. Let's give that a spin. I'll save and run it. Now I can enter a text. I will save Virginia and I get minus one because there's no X in Virginia. Now, if I run the script again and try with a text that contains an X, for example, Xavier, then I get zero. So it finds X at the first position. So that works with X, but I don't think that's great. If it will always look for X, it's maybe a little boring. So instead, I'm going to change this to allow the user to also input what character to search for. So I'll create another variable that I will call character. And that'll be another call to input. And then I'll say Enter Character to search for. Finally, I also need to replace the argument to text fine with character. Which then means it'll be whatever the user input. Technically, this user input could be more than a single character. Dot find works with substrings, so you could enter more than one character as a substring to search for. If Python finds the substring, then it returns the index of the beginning of where the substring first shows up in the string. But for this exercise, you don't have to worry about any of that. You'll assume that your users are good citizens and follow the instructions to only input a single character. Let's run that again. Enter a text. So now I can say Samantha and search for A. And then you can see that it finds it at the index position one. So at the second position, which is the index position one. And let's do it again. See whether it still works as expected. If I say Samantha and search for X, I get minus one. And one more test. If I type in Samantha and search for T, then you can see I get five, which is the index position of the first T that Python finds in the input string. All right. So that works. Let's clean up the script, remove the comments, and we're done with this exercise. 47. Strings and String Methods (SUMMARY): Welcome back, everybody. In this section, you learn how to manipulate strings with string methods. You learn how to work with user input and deal with strings of numbers. Along with that, you learned a handful of ways to format strings for printing. Also, we covered splitting, concatenating, and joining strings in Python. And along the way, you also learned about F strings, multi line strings, how to index and slice strings, how strings are immutable, and you also learn how to discover additional methods using idle. In the next section, we are going to practice working with strings and string methods. Doing all that, you'll practice the concepts that you've learned about in the section and to help make them stick. I want to say thanks and congratulations on completing the section. 48. PROJECT: Create a Receipt Printing Program: Welcome to your first project. We'll be creating a very basic receipt printing program. For the week, as we've learned about variables, operators in string manipulation will be using these skills in order to create this program. It's always good to picture a design of what you're trying to build. For larger projects, you'll want to create a flow chart or some sort of design document that will keep you on track. That way, you don't sway away from the intended result. For us, we'll be building a small receipt printing program with the concepts we've learned in which the output will look like the following. So let's begin. Whenever you begin a project, you must always understand where to start. No matter the size of the project, there are certain dependencies. Like building a house, you must have a foundation before you can put a roof on. Let's begin to define the variables we'll be working with throughout this program. A it's good to implement good coding techniques when writing a Python program. This technique introduced within its block is the ability to declare multiple variables on the same line. To do so, we separate the variable names and their associated values by. Looking at the first two variables declared, the value of oranges will be saved with the variable name P one underscore name and the value of 5.90. This will be saved into the variable name P one underscore price. Rather than writing six lines, we've reduced our program by half already. The less lines we use, the better most times. Next, let's define the variables we'll be using for the company at the top of the receipt. I as an example, we've left the company name all lowercase so you can use a streaming manipulation method to fix this issue. Lastly, let's declare the message that will output to the user at the bottom of the receipt. As we can see from the design that we've laid out at the beginning of the project, we'll need to pris out a border on the top and bottom. Let's start with a top border. All we're trying to do is print out 50 stars in a row for Tom Border rather than making 50 print statements. We can simply multiply the string by the number that we want. We've already defined our variables in the company by the preceding lines, so let's display them. Escape characters are read into the defining backslash character. Whatever comes after that backslash is what the computer will interpret. In the first three print statements, we will use the backslash T for tab indentation. When we use the two escaping characters in a row to center within our output, now let's create a divider. Like how we've printed out our top border, we'll multiply the equal symbol by 50 to create the same width line. This will give the appearance of separate sections. Now we want to create a header before we list out each product's name and price. This can be done simply by using our escape characters for indenting. Due to the size of the header names, we only want to use a single tab before each header. Now we can go ahead and output a row for each product's information. Okay. Okay. We're using similar styles in the previous print statements in order to center each product's title, price, and in their respective headers. Try not to get confused by all the symbols with the printing string, as you can simply break them down into a tab, followed by the first variable being formatted into the string, followed by two tabs, followed by $1 sign in order to make the price look like currency and followed in the second variable formatting into the string. This completes the section for our items, so let's put in another section divider. Like the product section. We want to create a header for our total, but we also want to center it underneath the price column, like in the product section. To do this, we'll need three tabs. Now that we have our total header aligned to the price column in the products, we can import our total onto the next line. Before we can print out a total, however, we must first calculate the total, which is the sum of all of our products. Let's define a variable called total, and then we'll print it out. Again, we've gone ahead and added three tabs plus $1 sign to make the total value appear as currency. Let's now add a section border. Y. To display the final thank you message, our design is spaced out slightly more than any other section, so we'll need to add a couple of new lines to give it some extra spacing. Our message is now centered, and we're ready to move on. To finish off the simple printing program, we need to throw in a bottom border for aesthetic. Run the program. Notice that the price of our third product, olive oil is in centered with the other two products. So let's delete a tab. Run the program again. And it works great. Congratulations. As simple as it may be, it's a huge milestone. Try breaking the program. I always encourage students to try and break programs because it will teach you how to fix it. Now I have a challenging question. In the project, we ended up creating borders above and below the information printed out. Try adding a star border on the sides as well now on the side borders. The solution is always inside to resources files. If you have any questions or any suggestions on how to improve the program, please let me know. Thanks for watching. 49. Numbers and Math (Overview): Computers use numbers to represent all kinds of information from text, images, music, and even videos like the one you're currently watching. Pretty much everything is a number from the computer's perspective. For this reason, numbers and the ability to handle them play an important role in every programming language, including Python. Perhaps that's also why some beginners believe they need strong mathematical skills to become programmers. However, that's a common misconception. In reality, your elementary school knowledge of math should be more than enough to start coding. The actual level of mathematical familiarity will depend on your specific role in the application you're building. For example, you were less likely to need to know about linear algebra or statistics as a web developer than as a data scientist. In this course, you'll get an overview of the numeric types in Python, creating integers, floats, and complex numbers, perform arithmetic operations. Learn about the floating point representation error, work with math functions and number methods, format and display numbers as strings. Alright, it's time for you to get started by having an overview of the numeric types available in Python. 50. Numeric Types in Python: In this lesson, you'll get a bird's eye view of the available numeric types in Python. Python has three numeric types built into the syntax, which means that you can start using them right away when you run idle. The three numeric types of native to Python are integers or whole numbers such as negative three, zero, or 42. Python calls them It for short. Then there are floating point numbers, which might have a fractional part, such as negative 2.32 or 3.14, for example. These are known as floats, and you'll learn why they are called like that. Finally, there are complex numbers composed of the real and imaginary parts. These are slightly more advanced and rarely used in practice. So you'll cover complex numbers in a later lesson. The corresponding data type in Python is called complex. It's worth mentioning that all three numeric types built into Python are signed, which means that they can store both positive and negative values along with the neutral zero. Additionally, integers don't have a maximum or minimum value, which is only limited by the available memory on your computer. In contrast, floating point numbers and their complex number cousins do have a fixed range of values as well as precision. Nevertheless, they're big enough to accommodate most real life use cases. Strictly speaking, Python has yet another numeric type, which is the special kind of integer data type. It's called boolean or Bool for short, and can only store one of two values, true or false. These values can be represented as one and zero, respectively. However, you shouldn't really think of booleans as numbers because they're used for a different purpose, which you'll learn about in a separate video course about conditional logic. In most applications, you'll use integers and floating point numbers most exclusively because they cover the widest range of problems while being the most efficient. One notable exception though, are financial operations on fractional values, which require exact precision, especially when you work with big and small quantities at the same time. Since floating point numbers have a limited precision, using them to represent currency amounts would inevitably lead to significant rounding errors. You should never use floats to represent financial data in real world applications unless you don't mind losing information about your customer's money. A common pattern for representing amounts of money is storing them as integers in terms of the smallest currency unit, such as cents, and then converting them back to dollars. However, that approach won't work across multiple currencies which might use different units. For example, $1 has exactly 100 cents, while one bitcoin can be subdivided into almost any fraction. To address the problem with floats, Python provides a few additional numeric types through these standard library modules, which you'll learn about at another time. You won't need those extra numeric types during this course, but it's worth knowing about them. The first one is called decimal because it internally stores numbers using the decimal position system instead of the binary one, like most other numeric types. Aside from that, it behaves mostly like a floating point number. Unlike a floating point number, however, it has an arbitrary yet finite position, which defaults to 28 decimal places. So you must decide upfront how many digits you'd like to keep. Also, while a decimal number works with integers, you can't mix it with floating point numbers easily. If that's a requirement, then you can use another numeric type that comes with Python called fraction. It represents a rational number or a quotient of two integers like one third. Fractions have infinite precision, which lets you represent numbers exactly, even if they have a reoccurring decimal or binary expansion without any loss of information due to rounding. Now that you have a general idea about the numeric types in Python, it's time to take a closer look at integers. 51. Integers: In this lesson, you'll take a deep dive into one of the most common numeric types in programming, the integer data type, which Python calls Int. If you'd like to follow along in an interactive Python interpreter session, then go ahead and start idle now. An integer is a whole number with no decimal places. The quickest way to create an integer in Python is by creating an integer literal consisting of digits that appear literally in your code. For example, typing 42 and idle creates an integer. You can check the type of such a literal, which Python refers to as It because integers are whole numbers. They don't come with a fractional part. So as soon as you include the decimal point in your literal, you no longer create an integer. Even if the fractional part of your literal is equal to zero, like in this example, the result will be a floating point number, which you'll learn about it in the next lesson. On the other hand, an integer literal can include the minus sign. This creates a negative integer number. Additionally, you can delimit groups of multiple digits by placing a single underscore character anywhere in your literal to make it a big number, a little bit easier to read. It makes no difference to Python whether you use the underscores or not, but writing a number with them is arguably more readable for humans. So far, you've only seen decimal literals consisting of the familiar ten digits zero through nine. However, occasionally, you might want to express a number using a different numeral system. Because computers use binary and sometimes a few other numeral systems, Python lets you create integers using those alternatives. By prefixing your integer literal with one of the few supported system bases, you can change how many digits you want to use. For example, the number 42 can be expressed as one, zero, one, zero, one, zero in the binary system. To tell Python to interpret such a literal as binary digits or bits, you can use the zero B prefix. Notice how idle presents the number to you in the decimal system again. It's the same number only represented in two different ways. Similarly, you can express the number 42 in the hexadecimal system using the zero x prefix followed by digits two A. Have up to 16 digits at your disposal in the hexadecimal system. The usual ten digits 0-9 plus six Latin letters A to F. The letters can be either uppercase or lowercase. The last numeral system supported by Python literals is the octal one, which has eight digits 0-7. You can enable an octal literal with a 00 prefix. Again, you get a decimal representation of the created integer. It's fair to say that you will rarely need to use integer literals other than the default decimal one. Nevertheless, they can sometimes be useful. Using integer literals is best when you know your numbers upfront and want to embed them in your code with a literal form. However, numbers often come as strings from the users who typed them on their keyboard. From an earlier lesson, you might remember that you can convert a string to an integer by calling the built in into function in Python. Notice the quotes around 42, which define a string literal. What you get back is the corresponding integer value denoted without the quotes. Again, you can verify the type of the return value which happens to be int. By default, the int function assumes that you will supply a string consisting of decimal digits zero to nine. If you'd like to choose a different base for the numeral system, then you can optimally pass a second argument to the function after a comma. In this case, you are creating an integer number 42 from a string of binary digits 101010. The maximum value for the base supported by Python is 36. It's worth noting that IT accepts a value of any data type, not just strings. For example, you can pass a floating point number in order to truncate its fractional part. As you can see, the int function allows for converting values from other data types to integers, which you might need to perform some calculations on numbers rather than strings. When you call Int without passing any value as an argument, you will always return zero as a result. The third way to create integers in Python is through expressions such as arithmetic expressions or function calls. You'll learn more about those in the future. In the meantime, integer literals should be completely sufficient. All right. Now you know how to create whole numbers in Python using integer literals, which you can represent with different numeral systems, including the decimal, binary, hexadecimal, and octal systems. In this case, they're all different representations of the same value. You also know about the in function, which returns zero when you call it without any arguments. Otherwise, it will convert whatever datatype you supply, such as a string literal to the corresponding integer number. When you call the in function with a floating point number as an argument, it will truncate its fractional part and only return the whole part as an integer. Finally, the in function can optionally take another argument, which is the base of the system used to interpret a string of digits, such as 10, one, 010 in the given base. Next up, you'll explore floating point numbers, the second most important kind of numbers and Python. But before that, I have an exercise in the next lesson about integers. In working through these exercises, you'll deepen your knowledge and solidify your understanding of the Python language. You'll not only gain confidence in your programming abilities, but also enhance your problem solving skills. 52. EXERCISE: Define Integer Literals: This exercise will test your ability to define integers in Python using their literal form. It would help to remember what integer literals are. As you already know, an integer is a whole number with no decimal places. For example, one is an integer, but 1.0 isn't. You can create an integer by typing the desired number. For instance, the following assigns the integer 25 to the variable num. When you create an integer like this, the value 25 is called an integer literal because the integer is literally typed into the code. All right. Here are your instructions for the exercise. You need to write a program that creates two variables num one and num two. Both num one and num two should be assigned the integer literal 25 million, one written with underscores and one without. Then print num one and num two on two separate lines. I'll let you think this through by yourself before moving on to the next lesson where we'll solve this exercise together. 53. SOLUTION: Define Integer Literals: I have Idol already open in the default interactive mode, which you can tell by the prompt consisting of three right angle brackets. This is the Python shell, which you can use as a playground to quickly test out ideas by running short code snippets before saving them in a file. I'm going to dock this window on the left side of the screen so that I have some space on the right where I can open another window with an empty file ready for editing. I like to have split screen with everything I need on a single workspace like this to avoid losing focus or switching between different programs. You'll also notice that I use a lot of keyboard shortcuts to make things a little quicker. While your shortcuts may be slightly different than mine, you can always find them on the menu at the top if you're interested in what they are. I'll paste the exercise instructions as a Python string into the code editor for a quick reference. As you can see, I've already turned each sentence into a separate bullet point, which we're going to tackle one by one. We're going to create two variables named num one and num two. It's customary to define each variable on a separate line in Python for better readability, even though it's technically possible to squash them onto a single line, which can sometimes be justified. A quick reminder, you can define a variable by specifying its name, such as num one, followed by the assignment operator, which is the equal sign in Python, and finally, the value. According to the second bullet point, both variables are supposed to have the same integer value of 25 million, but they're written using two alternative literal forms. Let's use the integer literal with underscores for the first variable and one without the underscores for the second variable. You can place underscores anywhere in your literals, as long as they don't appear in the front or at the end. In other words, there must be some digits on both sides of the underscore, and these underscores are completely optional because Python ignores them. They can be helpful in visually grouping similar digits together like in the exercise. Arguably, the first literal value is easier to read than the second one. Right off the bat, it says, write a program which indicates that you should save your code as a Python script, which I'll do now, and name the file exercise one. Idle assumes we're creating a file with Python source code, so it automatically appends the dot pi extension to the file name unless told otherwise. You can see the path to your file at the title bar of the window. Now, the last point in this exercise is about printing both variables in order to reveal their current values. Printing boils down to calling the built in print function with each variable as an argument. So print num one and print num two. You can now save the file and run it in the interactive window on the left. On my computer, I can reload the module by hitting F five on my keyboard. The two numbers that appear on the screen are the result of calling the print function twice with different arguments. Notice that despite using alternative literal forms that we assign to the variables, Python prints them the same way. You can verify this by explicitly calling print with num one and num two in the interactive Python shell on the left. You see, from Python's perspective, both variables contain exactly the same numerical value. Using underscores in integer literals only makes a difference to programmers like you who read the source code. A 54. Floating Point Numbers: In this lesson, you'll learn how to represent numbers using Python's floating point data type, which is the most suitable for numbers with fractional part. As with integers, you can create floating point numbers using their literal form. The only difference between an integer literal and a floating 0.1 is that a floating point literal must have a decimal point to separate the whole part from the fractional part. You don't even need the trailing zero to determine a floating point number as long as you include the decimal point in your literal. Similarly, you can skip the leading zero if your number is a fraction like 0.42. Floating point numbers in Python support the same grouping of digital as integers with the help of the underscore character. As you can see, it's possible to express the same value such as 42 using different data types in Python. The difference is how they represent it in your company's memory and how much space they take, which in turn affects the performance and precision of various operations. In addition to this, you can define floating point literals in Python using scientific notation, which is sometimes known as exponential notation or the E notation. The idea behind it is to collapse the repeated zeros in a really big or really small number and only focus on the significant digits. For example, you can write the same number as 4.2 times ten to the power of seven. The letter E, which can either be lowercase or uppercase, stands for the exponent. The exponent itself must be an integer, but maybe negative, just as the number in front of it. Such as a notation may appear strange or inconvenient, but it can sometimes make handling big or small numbers easier in arithmetic operations. You might have seen the E notation on handheld calculators, which use it to represent numbers that wouldn't be able to fit on the screen otherwise. If you don't like this notation, you can format your floating point number using a fixed number of decimal places such as eight to reveal all zeros. Like with integers, you can create floating point numbers in two ways. You can either use their literal consisting of digits and the decimal point, or you can call the built in float function. When you call the function without any arguments, it returns to a floating point number equal to zero. Note that this is different from an integer zero. However, in most cases, the function will accept a single argument, which can either be a string or a number such as an integer or another float. That's convenient for converting other data types to floating point numbers. You'll also want to use the float function to define a few special values that don't have literal representations in the floating point number data type. In those cases, you'll pass a particular string value as an argument to the float function. Two of them are positive and negative infinity. These are useful as unbound upper and lower bounds when you search for a maximum or minimum value, for example. Conveniently, you can compare infinity to regular numbers, which gives sensible results. The third special value in the floating point data type is called not a number or NAN. You can use it to explicitly indicate a missing value. However, it's more commonly used by Python itself to signal an undefined mathematical operation, such as dividing infinity by another infinity. There's one interesting quirk about not a number, because Python follows the IE 754 specification for the floating point arithmetic. Not a number is never equal to any value, not even itself. Another thing that's different about floating point numbers when you compare them to integers is that they have a fixed limit. If you try to find a value bigger than the allowed maximum value, you'll end up with infinity. How do you know what's the maximum value? Well, in practice, it doesn't really matter because the range of a floating point number is so enormous that it will be more than enough in most cases. Though if you really want to find out, then you can use the following instructions. In this case, the maximum value is about 1.8 times ten to the power of 308. Just remember that this number is set in stone because various Python interpreters can have different limits, depending on the platform that they're built for. To sum up, you can create floating point numbers in Python using their literals. That must contain a decimal point. At the same time, you don't need the trailing or leading zeros in those literals, leaving only the decimal point in place. You can specify floating point literals using the scientific notation known as the E notation, which lets you express really big or really small floating point numbers in a concise way. The second way of defining floating point numbers and Python takes advantage of the built in float function. When you call the function with no arguments, it'll return a floating point number equal to zero. However, you are almost always going to call it with one argument to convert another data type into a floating point number. Specifically, you can convert a string composed of decimal digits and a few special characters such as the minus sign, or you can convert an integer or even another floating point number. There are also a few special floating point values that you can obtain with the help of the float function. They are the negative infinity, positive infinity, and not a number. Okay, now that you know about integers and floating point numbers, it's time to learn how you can use them in arithmetic expressions in Python. 55. Arithmetic & Comparison Operators: Hey, everyone. This is Andreas. And in this lecture, we're going to learn about arithmetic operators, and we will do a dozen examples to understand them fully. So fire up Shell, and let's get started. Operators help us to perform the usual mathematic operations on variables. Arithmetic operators in Python include addition, subtraction, multiplication, division, floor division, also called integer division, modulo, exponentiation, unary positive and unary negation. I've included a PDF file with a nice table with the operator, an example, the meaning and the result. You can open it from your resource files. Here are some examples of these operators in use. A equals ten, B equals three. Addition A plus B. The result is 13. Subtraction, A minus B. The result is seven, multiplication, A, multiply by B. The result is 30. Division, A, divide by B. Enter. The result is 3.333, et cetera. The operator of the division is a slash character. The result of a standard division is always a float, even if the dividend is evenly divisible by the divisor. Floor division. A, floor division B equals three. The operator of the floor division is the double slash. The result of floor division is the quotien which A is divided by B, round into the next smallest whole number. When the result of floor division is positive, it is as though the fraction portion is truncated off, leaving only the integer portion. When the result is negative, the result is rounded down to the next smaller or greater negative integer. Modulus, A, modulo B equals one. The operator of modulo is the percentage character. The result of modulo is the remainder when A is divided by B. Exponentiation. A, exponent B equals 1,000. The operator of the explanation is the double asterix. The result of exponentiation is A raised to the power of B. In programming, the equal sign is known as the assignment sign. It means that we assign the value based on the right side of the equal sign to the variable on the left. Also, the statements A equals B and B equals A have very different meanings in programming. For example, open the idle editor and type the following code. Let's run the program with F five or for menu. We have to save it first. And look at the results. A equals 20, and B equals 20. Although A has an initial value of ten declared on the first line, the third line A equals B assigns the value of B to A, hence changing the value of A to 20, while the value of B remains unchanged. Crucial is the precedence of math operators. The order of operations of Python math operators is similar to that of mathematics. The exponent operator is evaluated first. The multiplication, division, floor division, and modulus operators are evaluated next, from left to right. The addition and subtraction operators are evaluated last, also from left to right. You can use parentheses to override the usual precedence if you need to. Let's jump to the interactive shell to do some examples. The result is 13 because the multiplication is evaluated first. Now let's put five and two into parentheses. The result is 28. Because the parenthesis has the highest precedents, let's explore another example. The result is three because the parenthesis has the highest priority. So this equals three, and this equals five, and the final result is three. Don't worry about the precedence of math operators. It's Python's job to evaluate parts of expression. If you have any questions about basic operators, please ask it. I'll be more than happy to help you. Thanks for watching. 56. Logical (Boolean) & Chained Comparison Operators: Hello, guys, Whatsap? In this video, you will learn how to use the three most critical logical operators in multiple chain comparisons. So let's jump to the lesson. If you want to compare Boolean values, there are three Boolean operators and or and naught. The logical operators not or and and modify and join together expressions evaluated in Boolean context to create more complex conditions. Here is the table you can also find as a PDF file. Let's explain these operators one by one. The and operator returns true if all conditions are met. Else, it will return false. For example, the statement, three greater than one and five greater than four will return true since both conditions are true, but three greater than one and five less than four will return false since one of two conditions is false. The or operator returns true if at least one condition is met. Else it will return false. The statement three greater than one or five less than four will return true since the first condition three greater than one is true. The non operator returns true if the conditions after the t is false, else it will return false. The statement not four greater than five will return true, since four is not greater than five. So the no operator simply evaluates to the opposite Bolein value. An exciting feature of Python is the ability to chain multiple comparisons to perform a more complex test. Comparison operators can be chained together to be arbitrary. For example, type five greater than three, greater than one, and enter. It's true because Python checks first if five is greater than three and then if three is greater than one. Let's do another example with boolean expressions that use comparison operators into the interactive shell. One less than three and three less than five. And Enter. This is a syntax error. Why? Because I typed and in capital, which is wrong. Let's change it and enter again. It's true because both conditions inside the parentheses are true. I hope you understand the boolean operators. Do your examples at home to fully gasp these. Thanks for watching, and I'll see you in the next lecture. Bye. 57. Floating-Point Representation Error: Hey, everyone. In this lesson, we'll learn about the representation error, which affects the precision of floating point numbers in virtually every programming language, including Python. Before exploring floating point numbers, it helps to take a step back and think about fixed point numbers, which provides one of the most straightforward ways of representing real numbers in computers. The idea behind fixed point numbers is to allocate a specific number of digits for the whole part and the fractional part. Therefore, the placement of the decimal point as well as the total number of digits are known upfront and never change. The biggest problem with such a representation is its storage inefficiency, which limits the available range of values that you can use. Notice how much space remains empty by getting filled with zeros in these examples. Floating point numbers, on the other hand can adapt to the size of the number they represent. In floating point representation, the decimal point can float around to the left or right to accommodate various number sizes. That way you can use the available space more effectively without wasting memory. Really big numbers, such as the speed of light, don't usually need a lot of precision. So it's probably okay to allocate more memory for the significant digits while trading off the fractional part. Conversely, smaller numbers like the size of an atom will benefit from increasing the number of fractional digits by floating the decimal point to the left. As long as you're okay with trading of precision for a number's magnitude and the other way around, then you'll be able to store an enormous range of numbers on a relatively small amount of memory. The bigger the floating point number, the lower it's precision. At the same time, smaller numbers tend to have a greater precision. Now, you know that floating point numbers owe their name to the way they're represented in a computer's memory. They are essentially scientific notation in the binary system with a few additional frills, which makes them exponentially efficient in terms of memory use. Unfortunately, the price for such a representation is losing the ability to express some numbers exactly, which can lead to very surprising results, like the one you can see on the current slide. Have a look at a few examples in IDL. When you type 0.1 plus 0.2 in Python, you get a result that's pretty close to what you'd expect, but not exactly right. The reason for such a strange outcome is because the two numbers you're trying to adding up don't have an exact representation on the floating pointed data type, which is only an approximation of the real numbers. By default, Python only shows the most significant digits of a number. To reveal the remaining ones, you can format your number requesting, say, 100 decimal digits. However, the flow data type keeps up to just about 55 digits. If you request more digits, then Python will pad the number with zeros on the right as there's not enough information. Now, where do all of these seemingly random digits come from? Without getting too technical, you must remember that computers keep all numbers in the binary system using just ones and zeros rather than the decimal system with ten digits 0-9. When you convert one tenth or two tenths to the binary system, then you'll end up with a reoccurring binary string that repeats itself infinitely. It's a familiar problem that you'll face in the decimal system too. When you try to represent one third, for example, the result is 0.3 reoccurring because computers don't have an infinite amount of memory. At some point they just have to crop off the binary string and round the results to the nearest representable value. On the other hand, as long as you stay within the realm of the binary system, you'll be able to represent a number exactly using a floating pointed data type. For example, a quarter is a power of two, so it has a finite binary expansion. Same with one half. When you add them together, you'll get an exact result without any rounding errors. To reiterate, a floating point number is usually just an approximation of the real number, kind of like the lossy compression in JPEG images, for example. Don't worry if this is making your head spin. In most engineering applications, the floating point representation error remains within acceptable bounds, and the results are satisfactory. However, in scientific or financial calculations, the rounding error becomes noticeable. In those cases, you should look into other numeric types, like the decimal type mentioned earlier in this course. Okay. With that out of the way, it's time to take a closer look at the math functions and number methods in Python. 58. Math Functions and Number Methods: In this lesson, you'll learn about the most common functions that let you work with numbers in Python. You'll also discover some useful behaviors exhibited by integers and floating point numbers. Without further ado, let's dive right into it. The first function that you may come across when crunching numbers in Python is the round function. By default, it takes a floating point number and returns the nearest integer. For example, passing 2.3 as an argument will round the number down and return two. On the other hand, a number like 2.7 will get rounded up. Things get more unexpected when your digit ends in five. This is known as a tie because the distance to the nearest whole number is exactly the same whether you round up or down. Python follows a strategy which ties like this are resolved by rounding to the nearest even number. In this case, that number is two. However, in the case of 3.5, the closest even number is four. This is a choice by design to minimize the impact that rounding has on operations involving lots of floating point numbers. Another interesting fact about round function in Python is that you can optionally pass a second argument to it, specifying how many decimal digits you want to round two. For instance, if you have an approximation of Pi, then you can say round it two, three decimal places. Notice that you're getting a floating point number as a result this time because five was the last digit in this example. It means there's a tie. Instead of rounding to the nearest even integer, however, Python will look at the last but one digit to decide about the rounding direction. In this case, two is the closest even number. However, this doesn't always work right. When you try rounding a number like 2.675 to two decimal places, you'd expect to get 2.68 as the result because eight is the closest even number. But when you actually run this code, you'll notice that Python rounds down instead of up. It's not a bug in the round function itself, but rather the result of that floating point representation error you learned about in the previous lesson. Okay. The next function related to numbers in Python that you may want to use is called abs, which is short for absolute value. It takes a number and returns its size without the sign. For example, the absolute value of 42 is 42. At the same time, the absolute value of -42 is also 42. You can call the apps function on integers as well as floating point numbers. Either way, you'll always get the positive value of a number. However, when you call the ABS function on a complex number, then you'll get the so called magnitude of a complex number, which is calculated using the corresponding formula. You'll take a closer look at complex numbers in one of the upcoming lessons. These are the most important use cases for the ABS function in Python. Finally, the third and last function that you'll learn about in this lesson is the power function. It provides a more explicit way of raising a number to the given power when compared to the double asterix or exponential operator you learned about before. The power function takes two arguments. The first one is the base or the number to be raised to a power. And the second argument is the exponent or the power to which the number is to be raised. As with the exponential operator, you can use negative or fractional exponents and bases. While both methods of calculating the power of a number in Python work mostly the same, the power function accepts an optional third argument as long as all three arguments are in integers. It's a shorthand notation for the modulo operator on the result of a power such as this. You can write this more compactly, passing the third value as an optional argument. Before closing the elation, it's worthwhile to mention that the numbers in Python expose a few useful methods, just like strings do, which you might remember from an earlier section. For example, you can check if a floating point number contains an integer value with no fractional part by calling it is integer method. Notice, however, that in order to call a method in Python, you need to use the dot operator, which also happens to be the decimal point in floating point literals. To avoid this ambiguity, you can wrap your numeric literal in parentheses. Remember that a numeric literal without a decimal point represents an integer. Alternatively, if you want to be more explicit, then you can assign your number to a variable. And call the method on the variable rather than the literal. In this case, 3.14 is not an integer, but three point oh is. Another useful method available on floats is as integer ratio. Which returns a pair of integers whose ratio is exactly equal to the original float. In this case, the numbers are rather big, but you can try something more like three quarters to get a ratio comprised of smaller numbers. Integers also have a couple of helpful methods. What of them can tell you how many bits you need to represent a number in the binary system. For example, a string consisting of binary digits 10, one, zero, 10 represents the decimal number 42. So you need at least six bits to faithfully express the same number in the binary system. You can confirm this by calling the bit length method on the number 42. There's also a similarly named bit count method, which will tell you how many of these bits are actually turned on. The original bit string has three ones and 30, so the return value is three. To recap what you've just learned, Python comes with a few built in math functions for working with these numbers. It has the round function, which rounds a floating point number to either the nearest whole integer or up to the given decimal places, which you can't specify as the second argument of the function. Ties are resolved by rounding to the nearest even number, but the floating point representation errors sometimes interfere with the expected rounding direction. The AB's function returns an absolute value of a number or the magnitude of a complex number. The power function performs largely the same mathematical operation as the exponentiation operator in Python, but it also provides a shorthand notation for calculating the modulo of the resulting power. You will also learn that the floating point numbers in Python expose a few methods, such as the I integer method, which checks whether the value is a whole number or not. The as integer ratio, on the other hand, returns a pair of integers whose ratio is equal to the floating point number. Integers also have their methods. For example, you can tell how many bits you need to represent them in the binary system or how many of those bits are lit up. Next up, you are going to learn how to format numbers as strings when you want to display them along with other text to user. 59. Numbers Formatted as Strings: In this lesson, you'll learn how to print numbers in style. Often, you'll want to combine your numbers with some additional text before presenting it to the user. For example, you may want to insert the price of a product into a prettified placeholder in a templated message. Traditionally, there have been many ways to format numbers in Python. For example, you can call the format function, which you've seen before in this course, to reveal the decimal digits of a floating point number. However, most programmers today use Python's formatted string literals or F strings, which look simpler and offer even more functionality. You can create a formatted string by prefixing your normal string literal with either a lowercase or uppercase letter F. For the most part, it'll work like a regular string, so you can type your message there. For example, this product costs $3.90. However, unlike a regular string, an F string lets you additionally specify one or more value placeholders to be filled at a later time. Say you wanted to reduce your message across many products with different prices. You can declare a helper variable with a product's price and then replace the concrete value in your F string with a placeholder by using the curly brackets and inserting the name of your variable. It worked nicely. Notice, however, that the trailing zero in the product's price got eaten up. Fortunately, those curly braces support a simple formatting language that you can use to alter the appearance of the value in the final formatted string. For example, to show the price using exactly two decimal places, you can add an optional format specifier in your placeholder. The colon separates an expression to evaluate such as a variable from the format specifier. In this case, the specifier is 0.2 F, which rounds the numbers to two decimal places. The letter F tells Python to display the price as a fixed point number. If a price gets bigger, you can then insert commas to group the integer part of the larger number by the thousands. Another useful feature of the formatted strings in Python is the ability to format numbers as percentages. For instance, if you have a fractional number like 0.91 23, then you can have Python automatically show it as a percentage rounded to the requested number of decimal places. Y The formatting mini language is powerful and extensive. While you've only seen the basics so far, here are a few more examples. You can stop the video now and take a look at them or check the accompanying PDF slides later. All right. In the next lesson, you'll revisit complex numbers in Python. But before that, let's do an exercise to fully grasp the lesson. 60. EXERCISE: Show a Percentage: You are almost at the finish line when it comes to formatting numbers in Python. In this final exercise, you're going to format a decimal fraction as a percentage with no decimal places. You got this. I have faith in you. 61. SOLUTION: Show a Percentage: When you divide two by ten, you get a floating point number with one decimal digit. You can format this as a percentage by using the percent sine as the format specification. If you've been following along, then you can guess how to request zero decimal places. That's right. You prepend a.in zero to the percent sine. You can use the same syntax in an F string literal for a more compact syntax. Okay. Well, this exercise wasn't too difficult, it's time to move on to another section of this course in which you'll interact with the user. Thanks for watching. 62. Complex Numbers: Alright. In this lesson, you'll go over some of the basics of working with complex numbers in Python. So let's dive in. Because complex numbers are rarely used outside of the domains of scientific computing and computer graphics, they were only briefly mentioned before in this section. At the same time, feel free to skip this lesson if you have no interest in working with complex numbers. Python is one of a few programming languages that provides native support for the complex numbers. You can think of a complex number as a pair consisting of the real part and the imaginary part. There are two ways to create complex numbers in Python. You can either call the built in complex function with those two parts passed as arguments or you can use a special syntax to define a complex number literal. Notice the letter J next to the second number, which indicates the so called imaginary unit. Mathematicians usually use the letter I to denote an imaginary unit, but Python follows a notation used by engineers to avoid confusing it for a lowercase letter L or a digit one that might appear in your code. When you drop the imaginary unit, then your complex number literal becomes just regular arithmetic expression, which adds two numbers. You can slap the imaginary unit to either of those two numbers in a complex number literal to indicate that the imaginary part. When you only have the imaginary numbers in your literal, then Python will add them and create a complex number without the real part. But it's still a complex number. You would typically assign a complex number to a variable such as Z. Using the letter Z for a complex number is a historical convention dating back to Carl Friedrich Goss. Just like integers and floating point numbers, complex numbers have a few interesting attributes and methods in Python. For example, you can get the real and imaginary components of a complex number using its real and imaginary attributes. Notice that the real and imaginary parts are stored as floating point numbers even when you define a complex number in terms of integers. You can also calculate a conjugate of a complex number by calling its conjugate method. A conjugate flips the sign of the imaginary unit. In fact, all numbers in Python, including integers and floating point numbers have the real and image attributes as well as the conjugate method. That isn't surprising from a mathematical standpoint because complex numbers are a superset of real numbers. For ins and floats, the real attribute and the conjugate method will return the number itself, while the image attribute will always be zero. Complex numbers support all the arithmetic operators that you learned about except for the integer division and the modulo operator. Otherwise, you can add two complex numbers. You can subtract them. Multiply. And divide them or raise one to a power. But you can't use the floor division. Nor can you calculate the remainder of a division, which is only defined for whole numbers. To sum up, you can define a complex number using either the built in complex function or the complex number literal with the letter J glued to the imaginary part. You could also access your complex numbers, attributes and methods to get the real part, the imaginary part, and to calculate the conjugate. 63. The Remainder (% Modulo) Operator: In Python, the percentage symbol is the remainder operator. This is known as the modulus operator. The remainder operator performs division, but instead of returning the quotient, it returns the remainder. The following statement assigns two to leftover. Let's type leftover equals to 17. Type the perfect symbol, three. Now let's print the leftover variable. If I run the code, the result will be two. This statement assigns two to leftover because 17/3 is five with a remainder of two. The remainder operator is useful in certain situations. It is commonly used in calculations that convert times or distances, detect odd or even numbers, and perform other specialized operations. To better understand the remainder operator, we will create a program that gets the number of seconds from the user and converts it to the number of the seconds to an hour, minute and seconds. For example, it would convert 11,730 seconds to 3 hours, 15 minutes and 30 seconds. And here is the program output that we're going to create. Now it's time to pause the video and give that a go. Alright, how did you get on? I really hope that you gave this a good go. Let's do the exercise together and write the code. First of all, I'll write some comments. Comments are an important part of programming. They allow you, the programmer to explain each part of what your code does. In the next line, I will create a variable called Total seconds. I want to get a number of seconds from the user. Converts the value to a float. And then assigns it to the total seconds variable. I'll leave an empty line, and in line four, I'll add a comment. Get the number of hours. Enter. I have a total seconds from the user, and I want to convert them into hours. Let's name the variable hours. There are 3,600 seconds in an hour. So this statement divides the total seconds by 3,600. Notice we use the integer division operator. This is because we want the number of hours with no fraction part. Now it's a great time to get the number of remaining minutes. I'll use the variable minutes. First, I will use the integer division operator to divide the total seconds by 60. This gives us the total number of minutes. Then I will use the modulus operator to divide the total number of minutes by 60 and get the remainder of the division. The result is the number of remaining minutes. The next step is to get the number of remaining seconds. Et's name the variable seconds. There are 60 seconds in a minute. So in this statement, I will use the modulus operator to divide the total seconds by 60 and get the remainder of the division. The result is the number of remaining seconds. The last step is to display the results using print statement. A First, I will print the hours. Then the minutes. Last, I'll print the second. Now it's time to run the code. Python is waiting for the user to insert the seconds that they want to convert. I'll type 11,730 seconds. They are the same with the output. That way, it's easier to compare the answer. It works great. I hope you understood the importance of the remainder operator. If you have questions, please let me know. Thanks for watching. 64. Reading Numbers with the input Function: The input function always returns the user's input as a string, even if the user enters numeric data. For example, suppose that you call the input function. Type the number 72 and press the enter key. The value that is returned from an input function is the string 72. This can be a problem if you want to use the value in a math operation. Math operations can be performed only on numeric values, not strings. Fortunately, Python has built in functions that you can use to convert a string to a numeric type. These two functions are INT and float. For example, suppose that you're writing a payroll program, and you want to get the number of hours that the user has worked. Look at the following code. The first statement gets the number of hours from the user and assigns that value as a string to the string value variable. The second statement calls the INT function passing string value as an argument. The value referenced by the string value is converted to an INT and assigned to the hours variable. This example illustrates how the INT function works, but it is inefficient because it creates two variables. One to hold the string that is returned from the input function and another to hold the integer that is returned from the INT function. The following code shows a better approach. This one statement does all the work that the previously shown two statements do, and it's created only one variable. This one statement uses nested function calls. The value that is returned for the output function is passed as an argument to the INT function. This is how it works. It calls the input function to get a value entered at the keyboard. The value that is returned from the input function, a string is passed as an argument to the INT function. The INT value that is returned from the INT function is assigned to the hours variable. After this statement executes, the hours variable is assigned to the value entered at the keyboard converted to an INT. Let's look at another example. Suppose you want to get the user's hourly pay rate. The following statement prompts the users to enter that value with the keyboard, converts the value to a float, and assigns it to the pay rate variable. I This is how it works. It calls the input function to get a value entered at the keyboard. The value that is returned from the input function, a string is passed as an argument to the float function. The float value that is returned from the float function is assigned to the pay rate variable. After this statement executes, the pay rate variable is assigned to the value entered at the keyboard converted to a float. To better understand all of these, let's make an exercise. Suppose you want to write a program that asks for the user to enter his or her name, the age and the income, then displays the value the user entered. Here's the program output. Pause the video now and complete this challenge. All right, how did you get on? I really hope you gave this a good go. Let's do the exercise together and write the code. Let's add the comment line first. Line two prompts the user to enter his or her name. The value that is entered is assigned as a string to the name variable. Line three prompts the user to enter his or her age. The value that is entered is converted to an INT and assigned to the age variable. Line four prompts the user to enter his or her income. The value that is entered is converted to a float and assigned to the income variable. Let's leave a blank line and add a comment at line six. At line seven, we display the message. Here is the data you enter. Line eight displays the name that the user entered. Line nine displays the age that the user entered. Line ten displays the income that the user entered. Yeah. The INT and float functions only work if the item that is being converted contains a valid numeric value. If the argument cannot be converted to the specific data type, an error known as an exception occurs. An exception is an unexpected error that occurs while the program is running, causing the program to halt if the error is not properly dealt with. For example, run the program and enter XYZ as age. Here is the error known as exception. I hope you understood how to read numbers through the input function. Thanks for watching. 65. Numbers and Math (SUMMARY): Welcome back, everyone. In this section, you learned all about working with numbers in Python. You saw that there are two basic types of numbers, integers and floating point numbers, and that Python also has built in support for complex numbers. First, you saw how to do basic arithmetic with numbers using the plus minus multiplication, division and floor division operators. You learn how to write arithmetic expressions and the best practices in PEP eight for formatting arithmetic expressions in your code. Then you learn about floating point numbers and how they may not always be 100% accurate. This limitation has nothing to do with Python. It's a fact of modern day computing related to the way that floating point numbers are stored in a computer's memory. Next, you saw how to round numbers to a given decimal place with round and learn that round rounds ties to even, which is different from the way that most people learn to round numbers in school. You also saw numerous ways to format numbers for display. Finally, you learned about Python's built in support for complex numbers, and we did a bunch of exercises to fully understand the topics. I want to thank you for watching, and I'll see you in the next one. 66. CHALLENGE: Calculating a Percentage: If you are writing a program that works with the percentage, you will have to make sure that the percentage a decimal point is in the correct location before doing any math with the percentage. This is especially true when the user enters a percentage as input. Most users enter the number 50 to mean 50%, 20 to mean 20%, and so forth. Before you perform any calculations with such a percentage, you have to define it by 100 to move its decimal 0.2 places to the left. Let's step through the process of writing a program that calculates a percentage. Suppose a retail business is planning to have a store wide sale, where all the prices of the items will be 20% off. Have to ask to write a program to calculate the sale price of an item after the item is subtracted. Here is the algorithm. One, get the original price of the item. Two, calculate 20% of the original price. This is the amount of the discount. Three, subtract the discount from the original price. This is the sale price. Four, display the sales price. Be mindful that the output must match the example output precisely. And when you hit Run, this is the outcome you're looking for. Now it's time to pause the video and give that a go. All right, how did you get on? I really hope that you gave this a good go. Let's do the exercise together and write the code. In step one, we get the original price of the item. We will prompt the user to enter his data on the keyboard. In our program, we will use the following statement to do this. Notice the value entered by the user will be stored in a variable named original price. A in step two, we calculate the amount of the discount. To do this, we multiply the original price by 20%. The following statement performs this calculation and assigns the result to the discount variable. In step three, we subtract the discount from the original price. The following statement does this calculation and stores the result in a sales price variable. Last, in step four, we will use the following statement to display the sales price. Run the program, and let's put a random original sales price. And here's the 20% discounted sale price. Great. I hope you managed to create the program on your own. If you have any questions, let me know. Bye. 67. CHALLENGE: Calculating an Average: Determining the average of groups of values is a simple calculation. Add all the values and then divide the sum by the number of values. Although this is a straightforward calculation, it's easy to make a mistake when writing a program that calculates an average. For example, let's assume the variables A, B, and C each hold a value And we want to calculate the average of those values. If we are careless, we might write a statement such as the following to perform the calculation. Can you see the error in this statement? When it executes, the division will take place first. The value in C will be divided by three. Then the result will be added to A plus B. That is not the correct way to calculate an average. To correct this error, we need to put parentheses around A plus B plus C as shown here. Let's step through the process of writing a program that calculates an average. Suppose you have taken three tests in your computer science class and you want a program that will display the average of the test scores. Here is the algorithm. One, get the first test score, two, get the second test score, three, get the third test score. Four, calculate the average by adding the three test scores and dividing the sum by three. Display the average. Be mindful that the output must match the display output precisely. And when you hit Run, this will be the outcome you're looking for. Now it's time to pause the video and give that a go. All right, how did you get on? I really hope you gave this a good go. Let's do the exercise together and write the code. Let's add first some comments. In steps one, two, and three, we will prompt the user to enter three test scores. We will store those test scores in variables Test one. Test two. In test three. In step four, we will calculate the average of the three's test scores. We would use the following statement to perform the calculation and store the result in the average variable. Last in step five, we display the average. Run the program. Enter the first test score, for example, 90. Enter the second test score, for example, 80, enter the third test score, for example 100. The average score is 90. I hope you understood how average works in Python. Thanks for watching, and I'll see you in the next lesson. 68. CHALLENGE: Converting a Math Formula to a Programming Statement: Suppose you want to deposit a certain amount of money into a savings account and leave it alone to draw interest for the next ten years. At the end of ten years, you would like to have $10,000 in your account. How much do you need to deposit today to make that happen? You can use the following formula to find out. The terms in the formula are as follows. P is the present future or the amount that you'll need to deposit today. F is the future value of what you want in the account. In this case, F is $10,000. R is the annual interest rate. And it's the number of years that you need to plan to let the money sit in the account. It would be convenient to write a computer program to perform this calculation because then we can experiment with different values for the variables. Here is an algorithm that we can use. One, get the desired future value, two, get the annual interest rate. Three, get the number of years that the money will sit in the account. Four, calculate the amount that will have to be deposited. Five, display the result of the calculation in step four. Now it's time to pause the video and give that a go. Alright, how did you get on? I really hope you gave this a good go. Let's do the exercise together and write the code. First of all, I'll write some comments. In the next line, I will create a variable called future value. I want to get the desired future value from the user. Converts the value to a float and then assigns it to the future value variable. I leave an empty line and in line four, I'll add a comment. Get the annual interest rate, Enter. In the next line, I will create a variable called rate. I want to get the annual interest rate from the user. Converts the value to a float and then assides it to the rate variable. I'll leave an empty line. Now let's add a comment. A then I'll create a variable called years. Convert it to an integer and ask from the user the number of years the money will grow. Now it's started to convert the formula to a code line. Calculating the amount needed to deposit. So, present value equals to future value. Divided by 100% plus the annual interest rate. All this to the power of years. The last step we need is the value in the present value variable. Now it's time to run the code. Python is waiting for the user to enter the desired future value. Let's type 10,000. Then I'll enter the annual interest rate. Let's type 0.05, which is 5%. Finally, I'll enter the number of years, type ten years. And the result is this. You'll need to deposit the amount of $6,139 and a lot of decimal numbers. It works great. I hope you understood how to convert a math formula to a programming statement. If you have questions, please let me know. Thanks for watching. 69. Dates and Times: Dates and times are items that most people worked with quite a bit. We make appointments in plan events for specific dates and times. Most of our day revolves around the clock. So it's a good idea to look at how Python deals with interacting with dates and time, especially storing these values for later use. As with everything else, computers understand only numbers. The date and time don't exist. Working with dates and times as one of the biggest challenges in programming between dealing with time zones, daylight savings time, and different written date formats, it can be tough to keep track of which days and times you're referencing. Fortunately, the built-in Python datetime module can help you manage the complex nature of dates and times. Technically, this act is called importing a package. And you'll learn more about it in the next lessons. To get the current time, you can simply type important date, time, date, time point, datetime point. Now, you see the full date and time information is found on your computers clock. You may have noticed that the date and time are a little hard to read in the existing format. Seeing that you want to just get the current date using the string command in a readable format type. Now it's much better. Datetime provides three classes that make up the high level interface that most people will use. Datetime. Date is an idealized date that assumes the Gregorian calendar extends infinitely into the future and past. This object stores the year, month, and day as attributes. Datetime, not time is an idealized time that assures that there are 86,400 seconds per day with no leap seconds. This object stores the hour, minute second microsecond and z info, time zone information. Datetime dot datetime is a combination of date and a time. It has all the attributes of both classes. First of all, you have to import the three main classes from DateTime using the following code. Now you can use some methods to create daytime instances. There are two methods that don't require you to use integers to specify each attribute, but instead allow you to use some other information. Day-to-day creates a datetime point date instance with the current local date. Datetime point now creates a datetime point daytime instance with the current local date and time. Let's take a look at some examples. I will use date point today and date-time point now to create instances of date, datetime, and time objects, each instance is stored in a different variable. Today is a date instance that only has the year, month and day. Now is a datetime instance that has the year, month, day, hour, minute, second and microseconds. As you can see, working with the dates and times and programming can be complicated. Fortunately, you rarely need to implement complicated features from scratch these days, since many open-source libraries are available to help out. This is definitely the case in Python, which includes three separate modules in the standard library to work with dates and times. Calendar outputs, calendars, and provides functions using an idealized Gregorian calendar. Datetime supplies classes for manipulating dates and times. Time provides time-related functions where dates are not needed. With the time command you can use to obtain the current time, you can get different values for each of the components that make up date and time using the day, month, year, hour, minute, second and microsecond values. But it's out of the scope of this lesson. You've learned the fundamental concept surrounding date and time. It's time for you to apply your new found knowledge in the real-world applications. Thanks for watching. 70. What is a List: Hi everyone, this is Andreas, and in this lecture you will learn what lists are and how to start working with the element in a list. Lists are one of Python's most powerful features that allow you to store sets of information in one place. So what is list? A list is a collection of items in a particular order. You can make a list that includes the alphabet letters, the digits from 0 to nine, Names, colors, whatever you want. You can put anything into a list. Lists contain complex objects such as functions or classes or even modules. The items on your list don't have to be related in any particular way. Also, a list usually contains more than one element. Python square brackets indicate a list in individual elements in the list are separated by commas. Let's make an example. Open the editor and start typing. We will make a list. Let's name is Apple products with four elements. Now we will print the list. Python returns its representation of the list including square brackets. You can also declare a list without assigning any initial value to it. You can type Apple products equals two square brackets. This is an empty list with no items in it. You have to use the append method to add items to the list. We'll learn about the append method later. The elements of the list can be accessed by an index. To do that, you name the list and then inside a pair of square brackets, you use an index number, like what I'm showing right here, that allows access to individual elements within the list. The indexing for that list is 0 based. So if you have a list such as this with these six elements, the indices start with 0 and we'll go up to five. For example, right in the shell. The result is iPhone because 0 is the first value of the list. Now type. And the result is iCloud because index three is the fourth value of the list. If you try to access index that is beyond the scope, you'll get the index out of range. Also, slicing is also available to. Slicing is an indexing syntax that's going to exact a portion from your list. So in this example, if a is your list than inside the square brackets, you will have to index numbers separated by a colon, and it's going to return a portion of that list that we'll start with position m and go up to, but not including index n using that same example from before. And if you took a 225, you get three objects in the middle, starting at index two and going up to index four, but not including five. A shorthand is available by omitting the first index. Your slice is going to start at the beginning of the list and go up to the second index. If you omit the last index, it's going to extend the slides from the first index and go all the way to the end of the list. And if you were to omit both indexes, it's going to return a copy of the entire list. And unlike with a string, it's a copy, not a reference to the same object. It's possible to add a third index after an additional colon. That third index indicates a stride, but it's also sometimes called a stamp. So in this example, if you add a slice that went from 0 to six with a step of two, you would return the object at index 024. Alternatively, you could access the values of a list from the back. The last item in this list has an index of minus one. The second last has an index of minus two and so forth. Right? And the Python answers iCloud because this the, the last item. Also you can assign a list or part of it to a variable type. So the variable products become iPhone, iPad, Mac Air, iCloud. Now if you type, the result is iPad comma MAC air, because you assign items with the index one to index three minus one. The notation one to three is also known as a slice. Whenever we use a slice notation in Python, the item at the start of the index is always included, but the item at the end is always excluded. In other words, the notation 1-2-3 refers to the items from index two, index four minus one, which is index three. There is also a more complex slice notation which includes a third number known as the stepper, but we'll skip it for now. An important function is to append if you want to add items to a list, for example, with that code line, you can add the value iPod to the end of the list, print the list and see the result. If you want to remove items from a list, you'll use the delete statement. Suppose you want to delete the item iPad, which is in position one. Type. Enter an iPad doesn't exist. Lists are crucial in Python programming. It's a feature in Python that we're going to see several times. And it's crucial if you're going to create programs and projects in Python. In the next lecture, we're going to dive deeper into lists. If you need anything to ask, I'll be more than happy to help you. Thanks for watching. 71. Working with Lists: Hello everyone. Today we are going to continue working with lists. So let's see some more functions. When you work with a list. If you want to combine two lists, you'll use the extended function, open the editor and write the following program. Run it, and look at the new list. Great. To better understand how it works, let's copy the program code and paste it into Python Tutor.com. Click on Start, visualize your code now. And it's like the Python version three. Paste the code and click the button and visualize execution. Looking all work step-by-step. If I press the forward button, I'll move to the next step and see the right sides output. The first line creates the Apple products one list with three elements inside iPhone, iPad, and iPod with index 012. Pressing the forward button executes the second line of code. It creates the Apple products to list with three elements, iCloud, iOS, and Air Mac with index 012 executing the third line, Apple products one is extended with Apple products to list components. So if I print list one, the output will be these six components. Pretty straight forward, right? Close the website. Okay? Now suppose you want to check if an item is on a list type. False, of course, office is not on the list. True, iOS is n, the list. To add an item to a particular position, we will use the insert function. Let's make an example, adding office inside the Apple products one list. Two is the index number, enter and print the list again. Very nice. Remove function, removes an item from the list, requires the value of an item as the parameter. Let's make an example. Type and enter, print an Air Mac were removed from the list. Finally, if you want to sort a list alphabetically or numerically, you'll use the sort function type. And we have a sorted list. Of course it's not the best list to understand if it's sorted or not. Please practice these functions and if you have any questions, please let me know. Thanks for watching and I'll see you in the next lesson on how to make numerical lists. 72. Making Numerical Lists: Welcome to this lesson and thanks for making this so far. Now let's move on to how to make numerical lists. Lists are ideal for sorting sets of numbers in Python provides several tools to help you work effectively with lists of numbers. Once you understand how to use these tools effectively, your code will work well. Don't forget that to store a set of numbers, we have a lot of applications from keeping track of a player's high scores to store temperatures, populations, et cetera. Python's range function is beneficial and makes it easy to generate a series of numbers. The range function generates a list of numbers and has the syntax range start and instep. If you wanted to make a list of numbers, you can convert results of range directly into a list using the list function. When you wrap a list around a call to the range function, the output will be a list of numbers. Let's make an example. Open the editor and type. Run the program. The new list one to nine appears on the screen. Notice that if the step is not given, a list of consecutive numbers will be generated like the above list, the end value must be provided. However, one weird thing about the range function is that given n value is never part of the generated list. To print the numbers one to ten, you should use range one comma 11. We will learn how to combine loop functions with range and create more complicated lists in later lectures, like a list of the first ten square numbers. Thanks for watching. 73. Printing Lists: Python provides a lot of ways to output information. Let's see just a few of the most basic methods for outputting lists. Take the following code into the editor. Here I tried to list with four car companies inside. Now let's print the list. This example uses the splat operator. It's the asteroid symbol, also called the positional expansion operator, and an assortment of other interesting terms to unpack the list and send each element to the print method one item at a time. The sep argument tells us how to separate each of the printed outputs, relying on a new line character. In this case, run the code and see the result. Python output the list one item at a time. Now remove the print line and add the following line in the code. This code line takes two lines of code and places it on just a single line. It also demonstrates the youth of the r just method, which right justifies the string. The for loops are an important element of Python language. And I have a whole section dedicated to loops, run the code. Look at that. It aligned the content with the right margin. Okay, now replaced the last line of code with the following one. In this case, the output is formatted with the dot format methods with accompanying text and the result doesn't include every member of cars. The 01 entry represents placeholders for the value supplied from cars. Run the code to see that it appears with 0 entry, which is Toyota, and the entry one which is BMW. Thanks for watching. 74. Tuples: Tuples are identical to lists in all respects except for a couple of the following notes. Tuples are defined by enclosing the elements in parenthesis instead of like lists using square brackets. It looks something like this. The other major thing is that tuples are immutable. So why would you use a tuple instead of a list? When you're executing programs with tuples compared to lists, the execution will be faster when you're manipulating the tuple. This is probably not going to be noticeable when you have a small list or small tuple. But if these are the large arrays of information, you'll start to see a performance difference. There are times when you don't want your data to be modified. If you have values as part of the collection and their mentor remained constant for the life of the program, using a tuple is going to guard against any accidental modification. And I know Python dictionaries are not the focus of this lesson. You'll learn that the keys in order to create a Python dictionary require that there are an immutable type. So in that case, you would need to use something immutable like a tuple instead of list. If you're looking to use a sequence for the key to define a tuple. Instead of using square brackets for a list, your objects are going to be contained within parentheses. Here's t, which is a tuple. And accessing t, my indexing works the same in introducing slicing. And you can see here it returns a tuple, even doing strides. And one of you use the favorite negative stride. And you can see it here returning in the parenthesis, these tuples and just note, yes, you're still using the same indexing style of square brackets. So what's so different? Well, you can't modify it. So if you're going to try to take index two and assign it to something, you're going to raise this exception of a type error. Tuple object does not support item assignment. If you were to create several objects here, and they can be again of different types, and you were simply going to list them out and put a comma between each one. You'll see that comes across as a tuple. And in fact, if you were going to start an end parenthesis with nothing in there and check the type on it. What you would have there as an empty tuple. Now what happens though, if you are trying to create a singleton tuple? You say T equals just the number two within your parenthesis. Well, you can see here T doesn't have the parenthesis around it. And if you look at its type, it's just an integer. Since parenthesis is are also used to define operator precedence for expressions, python will evaluate the expression of just two in the parenthesis as simply the integer two and create an INT. If you really want to tell that it's a singleton, You will have to do an extra step, which is to include a trailing comma that then would be considered a tuple. It's probably rare that you'll need to define a singleton tuple. But if you were to see it in an example, now you're ready. Next up, we're going to dive a little deeper into the tuple assignment with packing and unpacking. 75. Tuple Assignment, Packing, and Unpacking: In this video, I'm going to show you the tuple assignment through packing and unpacking. A literal tuple containing several items can be assigned to a single object, such as the example object here, T. Assigning that packed object to a new tuple, unpacks the individual items into the objects that the new tuple, with unpacking the number of variables on the left has to match the number of values inside the tuple. Let me have you explore that with some code. As you saw in the previous video, you can create a tuple just by typing the objects into a set of parentheses, and then that will pack them all in there into that single object. Again, you can access them via index. Here's an interesting idea. You can create another tuple of objects, in this case S1, S2, S3, S4, and could assign it to the tuple that you created. A moment to go, t. Now S1, S2, S3, and S4 will have unpack that tuple during that assignment and place them into the appropriate objects. Now it's important that they have the same number on both sides of that assignment. If you try to assign it to S1, S2, S3 equal to t, you are going to raise an exception here as a value error, there are too many values to unpack. It was expecting three on this side and t, as you know, has for so again, here's t. And what if you went with too many? Well, in this case, it was expecting to get five, but T only provided for packing and unpacking could be done in one statement if you wanted to. And here they are. We doing assignments like this. There's a handful of situations where Python will allow you to skip the parentheses. And the same with the unpacking. You can even do something like this where both sides don't have parentheses. Even creating that Singleton. It works the same whether the parentheses are included or not. So if you have any doubts as to whether they're assigned, go ahead and include them. Tuple assignment allows for a bit of idiomatic Python. Frequently when programming you have two variables whose values need to swap. It's necessary to store one of the values into a temporary variable. In most programming languages while the swap occurs, it would look something like this. So you create a variable temp, assign a into it, assigned B into a. And then say B equals temp. And there you've swapped the two. So again, you're making a temporary variable that holds a, taking b, assigning it into a, and then be pulling that temp back into it by reassigning it again. That's the swamp. But in Python, the swap can be done with just a single tuple assignment. Here you're going to say a comma b equals to b comma a. And you can see that the swap has occurred. That's it for today. I hope you enjoyed the lesson. If you have questions, please let me know. Thanks for watching. 76. Working with Dictionaries: Hello students, this is Andreas, and in this video tutorial, you'll learn about dictionaries, which is a great way to access an organized data. If you managed to combine dictionaries and lists, then you'll create a data structure in Python. So let's get started. A dictionary is a collection of related data pairs. Dictionary keys must be unique within one dictionary, you cannot use the same name twice in our example. Also, we use curly brackets when declaring a dictionary. Dictionaries are dynamic and can be nested. A dictionary can contain other dictionaries or lists. A dictionary contains its key value pairs within curly brackets. Go ahead and open up your Python shell, and let's work on some examples. So let's go ahead and define a dictionary and put some names here with the weight of each of them. Open the curly brackets and start typing the key value pairs, name and wait. The colon separates each key from its associated value. And remember that we separate key pairs values with a comma. Close off our dictionary with curly brackets and hit Enter. You can simply call your dictionary by typing the dictionary name and enter. A quick note here, like a Python version 3.9, dictionaries will display in an order in which they are defined. This behavior does not exist in earlier versions of Python, so it may return to a random order. You can retrieve a value from a dictionary by specifying its key in the square brackets like this. And if you specify a key that is not a dictionary, you get an expression. So adding an Andrew to your dictionary is just a matter of assigning a new key and a value. So if we add Allen as our key and the kilograms, you can see that Alan has been added. If you want to update an entry, you just need to assign the new value to the key. To delete an entry, you just type the delete the devil statement and specify the key. And John will be gone. Here I have made an intentional error. Can you find it? So I tried to delete John with the J letter and capital, but inside the dictionary we define it with a small J, as you can see. So be careful here, key-value pairs are case-sensitive. Something else to know when you're working with the dictionaries. And this can be confusing when you're starting out. If you work with list and you know that you can access item lists with an index number. You cannot treat dictionaries of lists. You won't be able to access values from an index number like so. You get an exception. This is because Python is expecting a key related to that point. You can use energizers as keys. So if I start a new dictionary here, and in this case we'll be able to access values in a dictionary with a 0 or one keys, not an index. Defining a dictionary using curly brackets and a list of key value pairs. It's fine if you know all the keys and values in advance. But what if you want to build a dictionary on the fly? You can start by creating an empty dictionary which is specified by empty curly brackets. Then you can add new keys and values one at a time. Once the dictionary is created in this way, it's values are accessed the same way as any other dictionary. Retrieving the values in the sublist or sub dictionary requires an additional index or key. You can use dictionaries for a wide range of purposes because there are so few limitations on the keys and values that are allowed. Thanks for watching. 77. Sets: Welcome back everybody. In this lesson we will learn about sets. They are a useful data structure that allows you to do some complex operations more effectively. So what is a cent in mathematics is set is a well-defined collection of distinct objects. The set of even positive numbers less than ten would be 2468. The set of perfect squares less than ten would be 149. The intersection of these two sets would be the number for. One is a set in Python. Python's built-in set type has the following characteristics. They are unordered, the elements are unique and duplicate elements are not allowed. And a set itself may be modified, but the elements contained in a set must be hashable. So a mutable object is a type of object that can be modified after it was created. Hashable objects, on the other hand, are a type of object that you can call hash on. All immutable objects are hashable, but not all hashable objects are immutable. Python can only include hashable objects. So some examples that you've probably seen immutable objects are tuples, strings, integers, and booleans. This is because these objects can be modified after they are created. And then hashable objects sort of encompasses all immutable objects. Lists and dictionaries are on hashable. Let's see some examples. So let's look at strings. We can create a string like this. And we can see that strings are indeed immutable. Let's try to actually mute. So if I tried to add a character or change the first letter to another character, both are a type error. The same goes for integers. We can verify that strings and integers are both hashable by calling the hash method on them. So hash on S will not error, but it will give us a number. And this number just represents the hash of s. Lists and dictionaries are on hashable, which means it calling a hash on them gives us an error. There are two ways to define a set in Python, you can use the set function. For example, we can pass the list apple and banana, which will convert that list who does set with two elements. Notice that the order is not exactly the same as the list we passed in because the sets are unordered. Let's see what happens when we pass in a dictionary. It will turn the keys of the dictionaries into a set. We can also pass in a string that is, split the string into characters. And if there are duplicate characters, it will not include those ones because sets cannot contain duplicates. For example, we can use the list function with the same string, keeping the same order of letters and the duplicates. The second way we could define a set is by using curly brackets. If we want an empty set, we could use a set like this. Sets are really cool because they can contain any hashable value and the same set does not have to include the same type of value. So I can have a string of boolean and then a tuple. And that will work. Oops, true is with capital T. Great. Let's try to pass a non hashable value and see what happens. So lists are not hashable and this is an error. So y cents, when sometimes you only care about unique values and you don't need your data to be ordered. That's the apparent difference between sets and tuples or lists. You can also do some cool operations very quickly. But the main reason that we use lists is that they are very, very fast. What I mean by that is that you can check for membership almost instantly. Thank you so much for watching. And if you have any questions or comments, please leave them in the Q. And a. Udemy form. 78. If Statements: Hi everyone. In this video tutorial, you'll learn how to write conditional tests, which allows you to check any condition of interest. You'll learn to write simply if statements. And you'll learn how to create a more complex series of if statements to identify when the exact conditions you want are present. The block following the if statement will execute. If the statements condition is true, the clauses skipped if the condition is false, an if statement could be read as if this condition is true. Execute the code. The if statement consists of the keyword, the condition a colon, and starting on the next line, a block of code. The structure of an if statement is the following. And this is the flow diagram. Let's make some examples, open the editor and write the following code. Python requires the formatting of blocks with indentation. It's very picky about whitespace and indentation. Save the program first, run the code and see the result on the screen. Python prompt the users to enter a number between 12. To do that, we use the input function. Keep in mind that the result is stored as a string. Now if you type one, the program will execute the first print statement. Maybe type two, the program will execute the second print statement. For all other values, the program will print you did not enter a valid number. Great. Now let's talk about an incline if an incline if statement is a simpler form of an if statement and his ideal if you only need to perform a simple task. The syntax is the following. For example, go to the previous program and delete all the code lines except the first one. Then type the following print function. If we run the program, we will get the same result as the previous, but with a lesser code line. In the next line, I'll show you many different examples of the if statement in an application. Thanks for watching. 79. EXAMPLES of Using the if Statement in an Application: You can use the if statements several ways. In Python, a relational operator determines how a value on the left side of an expression compares to the value on the expressions right side. Ever makes the determination and outputs a true or false value that reflects the expressions true value. For example, six equals to six is true while five equals to six is false. The following steps show how to create and use an if statement. First of all, let's define a variable called my value type. This stamp assigns a value of five to my value. Notice that it uses the assignment operator and not the equality operator type. This step creates an if statement that tests the value of my value by using the equality operator. The word if is highlighted in a different color than the rest of the statement. Type. And enter twice. If you press Enter twice in a row without entering any texts, the code block is an ended and the output is this phrase. If I change the variable's value to ten and rerun the same code, no execution will be done. Also if I change the variable's value and after if to 15 and execute the code, no execution will be done. Sometimes you want to perform more than one task after making a decision, as long as the next line is indented, it's part of the if statement. When the next line is out dented, it becomes the first line of a code outside the if block. A code block consists of a statement and the tasks associated with that statement. I'll put two print statements to understand how it works. Enter twice. Each line you type is part of the current ifStatement code block. And if you press Enter twice in a row without entering any text, Python executes the entire code block to make multiple comparisons. If you create various conditions by using relational operators and combine them to use it and logical operators. For example, take the following code inside the Python editor. Run the code and type three is a value. The if statement contains two conditions. The verse states that the value must be greater than 0. You could also present this condition as a value greater or equal than one. The second condition states that the value must be less than or equal to five. Only when value means both of these conditions will the if statements succeeds and print the value the user typed? If I take ten, the application doesn't output anything because the number is in the wrong range. Let's change the code to provide an alternative action when the condition for an if statement is false. Notice that the else cause ends with a colon, just as the if statement does. If you receive a coding error for a mere application, make sure that you check for the columns precedence as needed. Run the code and type ten. This time the application outputs the error message. Now let's try to create a menu selection of a restaurant. The restaurant offers pastor pizza salad and panna cotta for sweet. After you choose one of the items the server brings it to you. Creating a menu selection requires something like an if else statement. But if using the LIF cause, the LIF cause is a combination of the else clause and a separate IF statement. The following steps describe how to use the if, e l i f statement to create a menu. In each case, choices compared against a particular value to create a condition for that value, if none of the options is correct, the else clause is executed by default to tell the user that the input choice is invalid. Now I'll run the code. Python waits for me to insert a number, printing the message, select your favorite menu. I'll put the number three and the message appears, you chose salad, obviously because three is the salad menu. The decision-making process often happens in levels. For example, when you go to the restaurant and choose pasta, you have made a first-level decision. Now the server ask what type of past you want. For example, a bull and yeas are a carbonara. This selection becomes a second level decision making decisions in levels with each level relying on the decision made at a previous level is called nesting. Developers often use nesting techniques to create applications that can make complex decisions based on various inputs. The most commonly used multiple selection techniques is a combination of if and if else statements. This form of selection is often called a selection tree. The following code shows how to create a selection tree. Delete the previous code, and start typing. Type a number between 15. Let's type three. Type a second number. Now, let's put in five. The result is 15, because three times five gives us 15. I'll run the code again and put five as the first number, and ten is the second number. And it prints the message incorrect second value. So it works great. If you attempt to provide a value outside the requested range, you see an error message. The error message is tailored for either the first or second input value to know which value was incorrect. As a homework exercise, try to create a restaurant menu using nested Decision Statements. Thank you so much for watching. And if you have any questions or comments, please leave them in the Q and a Udemy forum. 80. For Loops: Hello students. Until now we learned that the if statement, but what if you want to execute a block of code only using a certain number of times, you can do this with a for loop statement and help the range function. And you'll learn a new function called enumerate. So the for loop executes the block of code repeatedly until the condition in the for statement is no longer valid. In Python, anything can be looped over, such as a string, list or tuple. This is also called a terrible. The syntax is the following. And this is the flow diagram. Let's do an example, fire up shell and start typing. In this program we have a list of seasons with four items. The statement for years in the seasons loops through the seasons list and it assigns each member into the variable year season. When we run the program in First Signs winter to the variable year season, then prints the value winter. After that, the program continues looping through the list until the end of its list is reached. If you want to display the members index in a list, you can use the enumerate function. Let's go with the second line and run the program again. You can see the index beside it. Every item is on the list. If you have any questions, please post them on the discussion board. For loop is a fundamental concept and I want you to understand it fully. Thanks for watching. 81. EXAMPLES of Using the for Statement: The best way to see how a for loop works is to create one. We will make an example that uses a string for the sequence. The for loop processes each of the characters in the string and turn until it runs out of characters. Take the following code into the editor. The example begins by creating a variable letter numb to track the number of letters that have been processed. Every time the loop completes, letter num is updated by one. The for statement works through the sequence of letters in the string and Dreze, and it places each letter in turn in letter. Let's run the code, save it first, the letter one is a nth, letter, two is n, and so on. The program stops when it prints the last letter of the name, and that is the letter S. The brake clause makes breathing out of loop possible. However, you don't merely place the break clause in your code. You surround it with an if statement that defines the conditions for issuing a break. In the following example, we will let the user provide a variable length string. When the string is longer than eight characters, the application stops processing it. Let's delete the previous code and work on some examples. Run the code and type John. The name has less than eight characters and prints it. But if I type Alexander, the application stops processing it. And here's the message. The string is too long. Sometimes you want to check every element in a sequence, but don't want to process certain elements. The break laws simply enter the loop so you don't use it in this situation. The break laws alternative that many developers use is the continue clause. As with the brake clause, that continue clause appears as part of an if statement. However, processing continues with the next element in the sequence rather than ending completely. In the following example, The code refuses to process the letter D, but will process every other letter in Andreas is name. Press F5 to run the code and see the result. There is no letter D inside the word. The Python language includes the second sort of the continue clause. The past clause works almost the same way as the continue clause does, except it, it allows the completion of the code in the if statement block in which it appears. Edit the code and use the past claws instead of continuing and rerun the code. Using the past clause allows for post-processing of an unwanted input. If I change the position of the print statement, I get different results. Python has another loop clause that you won't find with other languages. The else clause makes executing code possible if you have no elements the process in a sequence. For example, type the following code. Let's run the code, putting in a word, I'll type my name Andreas, and the output is the letters one-by-one. Now I will run the code without typing something and the else clause is executed typing the message, the string is blank. 82. While Loops: Hey everyone. In the previous lecture we learned the four loop, which executes the block of code only for a certain number of times. In contrast, the wild loop runs as long as or while a certain condition is true. For example, you could use a while loop to count through a series of numbers. Let's see it in action. Let's take a look at the flow diagram first. Now let's open the idle editor and run the following code. Run the program and it shows the numbers from 0 to three. In the first line, we start counting from 0 by setting the number variable to 0. The while loop runs the program as long as the numbers less than four and prints each number with the num plus one statement, we add one in every loop. The last statement prints the message to show us that the program has terminated. So Python repeats the loop four times and total, sometimes a loop can be infinite. The loop becomes an infinite loop if the condition never becomes false, you must use caution when using while loops because of the possibility that this condition never resolves to a false value. This results in a loop that never ends. Such a loop is called an infinite loop. In the above example, if we delete the num plus one statement, the conditional test, nonetheless than four will always execute to true and the while loop will run forever, printing a series of zeros like this. If your program gets stuck in an infinite loop, press control plus c or just close the terminal window displaying your program's output. To avoid writing infinite loops, test every wild loop and make sure that the loop stops when you expect it to. It is beneficial to run a program code as long as the user wants by putting most of the program inside a while loop, we'll define a quit value and then we'll keep the program running as long as the user has not entered the quick value. Let's write the following code. And let's run the Python code. I forgot the colon here. At first, Python displays the prompt and waits for the user to enter their input. Whatever they enter is stored in the myText variable and printed on the screen. After that, Python re-evaluates the condition in a while statement. As long as the user is not entered the word quit, the prompt is displayed again and Python waits for input. When the user types quit, Python stops executing the while loop and the program ends. Thanks for watching. 83. Break and Continue: Welcome to this lesson and thanks for making it this far. In this lecture, you'll learn to statements that can be used inside loops. There, the break and continue keywords. Sometimes you may want to exit the entire loop with a specific condition is met. To do that, we use the break keyword, the break statement in Python terminates the current loop and resumes execution at the statement just like the regular breakdown and see, the most common use for the break is when some external condition is triggered requiring a hasty exit from the loop. The break statement can be used in both while and for loops. Let's type and run the following program to see how it works. Without the break keyword, the program should print the numbers from five to one with the break keyword, the program ends prematurely at number two. This is because when the number reaches the value of one, the break keyword causes the loop to end. Notice that we used an if statement within a while loop. This is a widespread practice in programming and a robust feature as we continue to the course. This is also known as a nested control statement. Another keyword for loops is the continue keyword. The continue statement in Python returns a control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. It can be used in both while and for loops like break. To understand it better, we'll replace the break command with the continue. Run the program. Unlike the previous example, the continue rejects the if statement and moves the control back to the top of the loop. Also the rest of the loop after the keyword is skipped if we had code, of course. Finally there was a past statement which is a no operation. The past Dave and helps create a code block but is no longer required. It's not so useful and you have to know simply what it does. Nothing more. If you don't fully understand, don't worry, we'll create a project that includes both statements. Thanks for watching. 84. PROJECT: Guessing Game: We're going to create a game where the computer chooses a number and the player guesses it. In the guessing game, Python thinks of a random number. The player assumes the number. The first step is to get a text from a user by using the input statement. Let's start typing in the editor. The variable prompt is pointing to a literal. The literal name is between the parentheses. I capture what the user types with a variable named players guess input returns a string, whatever the player types, even if it's just a number, you're going to get a string from input. To compare the guesses, you need to convert the players gas into a number. Your game needs to check whether the guess is the same as the computer's number. Say that the computer has come up with ten. To compare the variable, players guess to the number you need to store the value in a variable called computers underscore number. Let's take the variable at the start of our program. When you can compare the guess with the answer, you can print a response from the player. The I N T built in takes a string that has a whole number and changes it into something Python recognizes as a number. Remember whenever you're coding, the colon means that a new code block is about to follow on the line after the colon and every other line in the block, you need to start with four spaces. What happens if the player guesses the wrong answer? The else keyword changes the operation of the if keyword. It's always executed when proceeding. If code block isn't executed, let's type, run the code and type in. The code block works fine. Now we have to show players whether their guess is too high or too low. Using the we will put in the LIF block between the program and the if statement. So all the lieth the message wrong. Guess again, and I'll replace it with the two high. Run the code and type 20. The message to high appears on the screen. You still need to set up something that the computer keeps asking if the player doesn't guess the number. You need to do this by putting the code that asks for the players guess and test its value while the loop. Then using the break statement, when the correct answer is given this, let's you break out of the loop. Let's edit the code. Here. We will break the loop. The loop statement allows you to exit any loop that Python already is in. Regardless of enclosing loops condition. If you have a loop inside a loop, the brake applied through the loop level that the brake appears in, in our example, it breaks the inner loop, the if loop. To break the outer loop, you need to be in the outer loop's code block. Now, how do you get Python to think of a number, the random integer feature, right handed these from the Random module, it gives you a random number between two figures that you put in the parenthesis that follows randint. The number will include the lowest or highest number. If you want a number between 110, use random.random one to ten. The random module comes with Python, but unlike the built ins that isn't loaded automatically, the random module is part of python standard library. If you need it, you must import it. Why can't Python just automatically load everything? Because it would make programming boring. Everytime you ran a program, you'd need to weigh wall it found in loaded all the modules in the standard library. Besides giving you access to the standard library, the important statement also allows you to use module that someone else has written called third-party modules. To use those, you have to download them and install them on your computer. I have a whole section with modules later in the course. So add these two lines of code from the start. I edited the code line with the computer's number variable and put in a number from one to 50. We have finished our guessing game and are ready to test it, run the program. It works great. Congratulations, you have just created your first game using Python programming. Keep in mind that you can write commands in your code as a short explanation of what the code is supposed to do. 85. Using if Statements with Lists: Hey guys, what's up? In this video, you'll learn how to use if statements with lists. You can easily combine a list and an if statement. The best way to understand the combination is through an example. The following example, to find the list of shopping in a supermarket. Open the text editor and start typing. At first we define the list with our shopping list when the program is waiting for the user to type the product he wants. If the requested item is on the list with the available items, Python prints a message that the product is available. The else block prints a message telling the user that this type of product is unavailable. So from the above example, we have managed to solve a problem combining if statements and lists. Thanks for watching. 86. Using for Loops with Lists: Hey everyone, in the previous lecture we learned about the for loop. We use for loops to execute a block of code a certain number of times. I want to show you now the combination of for loops with lists. Let's open the Python editor and start typing the following program containing a list of doctors in the hospital. Technically a for-loop repeats the code block once for each value in a list. For instance, if we run it, this program prints the available type of doctor one-by-one. Look at the result. In the first line, we have a list of the available doctors in the hospital. Then with the help of the for loop, we print the message in this hospital, there is this doctor specialty. This is a simple example of how we can combine a list with a for-loop. Thanks for watching. 87. Using a while Loop with Lists and Dictionaries: Hello students and welcome back to the course as we'll continue to learn how to combine a while loop with lists and dictionaries. Using while loop with lists and dictionaries allows you to collect, store, and organize lots of input to examine and report. Later. In this report, we first ask the user to enter a password. If the password is correct, the application will open, but if the password is wrong, a message will appear asking to enter the password again. Let's run the program and put in a password. For example, 1234. Python lets us know that the password is wrong and asks us to try again. Now I'll type four aces, which is the correct password. Copy the program and paste it into the Python Tutor website so we can visualize it. Select Python three and paste it there. Pressed the button, visualize execution. The first line is a simple message asking the user to enter a password. Then in the second line, Python is waiting for the user to type a code. The code is stored in my code variable. In the third line, we have a dictionary with the right password inside four aces. Then the loop begins while the variable my code is not equal with the right password, print a message that the code is wrong, and asking again with the code, if the user types the code correctly, a print message appears with texts correct, and the program is terminated. So we can see that combining wild loop with lists or dictionaries can create powerful programs. Don't forget to use this website. It's a great practice, especially for absolute beginners. Thanks for watching. 88. Creating Stacks Using Lists: A stack is an array or a list structure of function calls and parameters used in modern computer programming and CPU architecture. Like a stack of plates at a buffet, restaurant or cafeteria, elements in a stack are added or removed from the top of a stack is a last in, first out, or FIFO order. The process of adding data to a stack is referred to as a push while receiving data from a stack is called a pop. This occurs at the top of the stack. The stack pointer indicates the stacks extent adjusting as elements are pushed or pumped to a stack. When a function is called, the address of the next instruction is pushed into the stack. When the function exists, the address is popped off the stack and execution continues at that address. Unfortunately, Python doesn't provide a stack as a collection. However, it does provide lists and you can use a list as a perfectly acceptable stack. The following steps help you create an example of using a list as a stack. In this example, the application creates a list and a variable to determine the maximum stack size. Stacks usually have a specific size range. This is admittedly a tiny stack, but it serves well for the examples needs. Stamps worked by pushing a value onto the top of the stack and popping values back off the stacks top, a function in Python and defined by a def statement. In this program, I have defined three functions. The display stack, push and pop. We'll learn everything about function isn't in a later section. So be patient for now. The pushing pump functions performed these two tasks. The code adds display stack to make it easier to see the stack content is needed. Len is a built-in function in Python, you can use the len to get to the length of any given string, array, list, tuple, dictionary, etc.. The remaining code exercises in the stack demonstrates its functionality by pushing values onto it and then removing them. For main exercise sections, tests, stack functionality, run the code and look at how Python fills the sack with information and then displays an on-screen. The stack currently contains three values, 123, press enter. The application attempts to push another value onto the stack. However, the stack is full so the task fails. Press enter again. The application pumps of value from the top of the stack. Remember that three is the top of the stack. So that's the value that is missing. Enter again, and the application tries to pop more values from the stack that it contains, resulting in an error and a stack is empty. It's a good exercise to visualize the execution from Python Tutor.com step-by-step. Thanks for watching. 89. Searching and Sorting Lists: The ability to search a list is essential if you want to make maintenance tasks more manageable. The following code helps you create an application that demonstrates the ability to search a list for specific values. Take the following code into the editor. The example begins by creating a list named Apple products that contains Apple product names. It also creates a variable named Apple products select to hold the Apple products name that the user wants to find. The amplification enters a loop where the user is asked for an Apple product name placed in Apple products. As long as this variable doesn't contain the word quit, it continues a loop that requests input. Whenever the user inputs an Apple product name, the application asks the list to count the number of Apple products out currencies. When the value is equal to or greater than one, the list does contain the Apple product and inappropriate message appears on screen. On the other hand, when the list doesn't include the requested color in alternative message appears on screen. Let's save and run the code. Python asks you to type on Apple product name, type iPad Enter, and you see a message telling you that the iPad does exist in the list. Now type iMac and you see a message telling you that the iOS doesn't exist. Type quit, and the application ends. The computer can locate information in a list no matter what order it appears in. Longer lists are easier to search when you put them in a sorted order. However, the main reason to put a list in sorted order is to make it easier for the human user to see the information list contains. We will make an example that begins with an unsorted list. It then sorts the list and outputs it to the display. The following code demonstrates how to perform this task. The example begins by creating an array of Apple products. The Apple products are currently in unsorted order. The example then prints the products and the order in which they appear. Notice using an argument for the print function to ensure that all products and trees remain on one line, making them easier to compare. Sorting the list is as easy as calling the sort function after the example calls the sort function that prints the list again so that you can see the result. Run the code. This is a name error because this item is different than this item, capitalize the first letter. So let's change this also. I'll leave a space inside double quotes. Run again, and Python outputs both the unsorted and sorted lists. You may need to sort items in reverse order at times to accomplish this task, you use the reverse function. The function must appear on a separate line. So add the following code line here. Rerun the code and see the products in reverse order. Thanks for watching. 90. Looping Through a Dictionary: Hey guys, what's up? In this video, you'll learn how to do a loop through a dictionary. Okay, let's jump into action. As you already know, a dictionary can contain key value pairs. Dictionary can have a few entries, but sometimes they contain large amounts of data, maybe millions of pairs. That's why it's beneficial to loop through a dictionary. The following example that I'm going to write has a dictionary with usernames and passwords of three users. I want to print all the information stored in the above dictionary using a for loop type the following code. Let's examine the second line code. The for loop needs to variables that will hold the username and password in each pair. You can choose any name you want for these two variables. After these two variables, we use the method items which returns a list of key value pairs. The for-loop stores each of these pairs in the two variables provided. In the next line we put the username and the password, the backslash n. The first print statement ensures that a blank line is inserted before each key value pair in the output. Now see the result in the Python shell. We could copy the program and paste it in Python Tutor.com if we wanted to see it in action step-by-step. Great. Thanks for watching and I'll see you in the next video tutorial, happy learning. 91. Replacing the switch statement with a dictionary: Most programming languages provide some sort of switch statement. A switch statement provides for Elegant menus types, elections. The user is several options, but is allowed to choose only one of them. The program takes some course of action based on the user selection. Here is an example of another programming language. Unfortunately, Python doesn't come with a switch statement. However, by using a dictionary, you can simulate the use of a switch statement. Let's take the following code to demonstrate the required technique. Each of these functions defines a task associated with selecting a color option on screen. Only one of them gets called at any given time. Let's continue with typing the dictionary code. This code is the dictionary. Each key is like the case part of a switch statement, the value specify what to do. Finally, let's type the user interface is part of the example code. Begins by creating an input variable selection. Then it goes into a loop until the user enters a value of three. During each loop, the application displays a list of options and then waits for the user input. When the user does provide input, the application performs a range check on it. Let's run the code. Python displays the menu waiting for you to select an option type 0 and enter the application which tells you that you chose red and then displays the menu again. Now type three and press enter. The application ends. As always, you can visualize your code step-by-step using Python Tutor.com. Thanks for watching. 92. Working with the Counter Object: Sometimes you have a data source and you simply need to know how often things happen, such as the appearance of a specific item in the list. When you have a shortlist, you can simply count the items. However, when you have a long list, getting an accurate count is nearly impossible. The counter objects, let's you count the items quickly. Let's do an example that creates a list with repetitive elements and then counts how many time those elements appear. Type the following code. To use the counter object, you must import it from collections. The example begins by creating a list. With repetitive numeric elements. You can easily see that some elements appear more than once, like number one, the example placed into the list into a new counter object, list counter. The application prints a list counter in various ways. The first output is the counter as it appears without any manipulation. The second output prints the individual unique elements in my list and the number of times each element appears. To obtain both the element and the number of times it appears, you must use the item's function as shown. Finally, the example demonstrates how to obtain an individual count from the list using the get function. Run the code and Python outputs the results of using the counter object. Thanks for watching. 93. What are Functions: Functions are a simple way to group actions with them. You can do some groups of actions repeatedly without having to retype all the code functions. Let you explain what does y and function let you reuse your code. To use a function. You must one to find the function itself and to invoke or call the function. Here's a simple example that rewards your Hello World program using a function open Python shell window. Press Enter twice to return to the command prompt. It doesn't do anything. Now you must call the function to make it run. Python will call the function if you write the function's name followed by parentheses, a function's code block is the line following the def statement up to but not including the next line that's indented the same as the def statement. When the Python reaches the end of the function, it skips back to the spot where the column occurred, back there with the parentheses. The rules for naming a function or a lot like the rules for naming a variable. They must start with a letter or an underscore. They should be lowercase. They can't have numbers. They can be any length, but keep them short. They can't be the same as a Python keyword. Functions have a special kind of comment called a doc string. The primary purpose of a docstring is to explain what the function supposed to do. This means that someone looking through your code will understand what the function is doing without figuring out the code itself. To create a docstring, add a string literal enclosed in triple quotes as the first line of the function's code block. Like our example, functions are extremely useful and powerful tools in the programming toolbox because they allow you to separate your program into meaningful blocks. In the next lecture, we are going to explain some built-in Python functions. Thanks for watching. 94. Built In Functions: Hello students and congratulations, you've made it this far. Now you are familiar with loops and probably started to create your own small projects. In this video tutorial, we will learn some of the most useful built-in functions in Python. Let's get started with the len function. The len function counts the length of a word. So you can pass the len function of a string value or a variable containing a string. And the function evaluates the integer value of the number of characters in that string. Let's do some examples in the shell. Type. The result is five because there are five characters in the word hello. Another example. First, the program is asking the user to enter its name, type your name, and press enter. Then Python counts the character of the name and shows the result. Great. If you want to make a list of numbers, you can convert the result of a range directly into a list using the list function. The range function makes it easy to generate a series of numbers. Then you can use the list function to convert that same set of numbers into list. Okay, let's see it in action type. We made a list of numbers from one to nine. Finally, some built in functions that help us calculate simple statistics like minimum, maximum and some, I've already made a list called num. Let's type. The result is one. Of course. The result is nine. The result is 45. There are dozens of built-in functions in Python, but don't worry, you'll learn only the useful ones. Thanks for watching. 95. Defining your Function: Welcome back everybody. A handy feature of Python is defining your functions and using them throughout the program. Create your function's. Yes, that's right. Here is the syntax for defining a function. Now let's explain the syntax in detail. The def statement tells the program that the code from the next line is part of the function. Return is used to return an answer from the function. Once the function executes the return statement, the function will exit. If your function does not need to return any value, that return statement is unnecessary or you could write return none. Now let's define our first function, open idle and type. In line one, we type the heading contains deaf and the name of a function, parentheses and finally a colon. The next line forms the function body. Now run the program. The whole definition defines the meaning of the name my_function, but it does not do anything else. The definition itself does not make anything be printed yet. That's why you can't see anything and visibly in shell after Idol finished executing a program, however, its version of the shell remembers function definitions from the program. Now in the shell Enter. Python goes back and looks at the definition and then executes the code inside the function definition, and of course prints the message. Let's try something different now. Type. Nothing happens without parentheses. It identifies the function code is the value and give the location in memory of the code. All right, now a function using the return statement. In this program, we define a function with two numbers and return the sum of these numbers. Type in the shell. Enter. Can you guess why we had this syntax error? The answer is simple. We didn't press enter twice after this line, so we didn't actually define the function sum two numbers. Let's rerun the function. Ok, now type. Of course the result is 11. I hope that we got a glimpse of how to define our functions. Thanks for watching. 96. More Built In Functions: Welcome back everybody. In this lesson we'll look at five built-in functions that are commonly used by Python programmers. I'll describe what they do and how to use them, and then show you examples of how they can help in your programs. The ABS function returns the absolute value of a number, which is the value of a number without its sign. For example, the absolute value of ten is ten and the absolute value of negative ten is ten. To use the ABS function, simply call it with the numbers or variable as its parameter like this. You might use the ABS function to do something like calculate an absolute amount of movements of a character in a game, no matter in which the direction that the character of traveling. For example, say the character takes three steps to his right, positive three, and then ten steps to his left, negative ten or minus ten. If we didn't care about the direction positive or negative, the absolute value of these numbers would be 310. You might use this in a board game where you roll two dice and then move your character or maximum number of stamps in any direction based on the total of the dice. Now if we store the number of steps in a variable, we can determine if the character is moving with the code below. We might want to display some information when the character is designed to move. In this case, we'll just display character is moving. If we haven't used the if statement might look like this. As you can see, using ABS makes the statement look just a little shorter and easier to understand. The name Bool is short for Boolean. The word programmers use to describe a type of data that can have one or of two possible values, usually either true or false. The bool function makes a single parameter and returns either true or false based on its value. When using bool for numbers, 0 returns false while any other number returns true. Here's how you might use bool with various numbers. When you use bool for other values like strings, it returns false if there's no value for the string, in other words, the keyword none or an empty string. Otherwise it will return true as shown here. The bool function will also return false for lists, tuples, and maps that do not contain any values are true when they do. You might use bool when you decide whether a value has been centered on. For example, if we ask people using our program to enter the year they were born, our if statement could use bool to test the value they enter. The first line of this example uses input to store when someone else enters on the keyboard is the variable year. Pressing Enter on the next line without typing anything else, stores the value of the Enter key and the variable. On the following line, the if statement checks the Boolean value of the variable after using the rstrip function, which removes any spaces in Andrew characters from the end of the string. Because the user didn't enter anything. In this example, the bool function returns false because this if statement uses the not keyword. It is a way of saying, do this if the function does not return true. And so the code prints, you need to enter a value for the year of your birth. On the next line. The eval function, short for evaluate, takes a string as a parameter and runs it through it as if it were a Python expression. For example, Eval Print, Wow, will actually run the statement print. Well, the eval function works only with simple expressions such as the following. And the eval function is often used to turn user input into Python expressions. For example, you can write a simple calculator program that reads equations entered into Python and then calculate slash evaluates the answers. Since a user input is read as a string, Python needs to convert it into numbers and operators before doing any calculations. The eval function makes that conversion easing. In this example, we use input to read what the user enters into your variable, your underscore calculation. On the next line, we enter the expression five times 20, perhaps your age multiplied by the number of weeks in a year. We use email to run this calculation and the result is printed on the final line. The exact function is like evil, except that you can use it to run more complicated programs. The difference between the two is that email returns a value, something that you can save in as a variable where as exact as not. Here's an example. In the first two lines we create a variable with a multiline string containing two print statements and then use executor on the string. You could use exact, run many programs at your Python program reads in from files, really programs inside programs. This can be quite useful when writing long complicated applications. For example, you could create a robot's game. We're two robots move around a screen and try to attack each other. Players of the game would provide the instructions for their robots. As many Python programs the robots gain would read in these scripts and use exact run. The range function, as we've seen before, is mainly used in for loops, to loop through a section of code a specific number of times the first two parameters given to arrange or called the start and the stop. You saw the range of these two parameters in the earlier example using the len function to work with a loop. The numbers that range generates begin with the number given as the purse parameter and N with a number that's one less than the second parameter. For example, the following shows what happens when we print the numbers that range creates between 05. The range function actually returns a special objects called an iterator that repeats an action of a number of times. In this case, it returns the next highest number each time it is called. You can convert the iterator into a list using the function list. If you then print the return value when calling range, you'll see the numbers it contains as well. You can also add a third parameter to range called step. If the step value is not included, the number one is used as a step by default. But what happens when we pass the number two as the step? Here is the result. 97. Global and Local Scopes: The scope is something that is initially difficult to understand when starting programming and globals, locals and vars allow you to understand the scope a little better. This is best demonstrated in the context of a program. So here you can see a program with a being equal to one being equal to the string global and c is equal to the string another global. But as you may know within a function, the same variable names can be redefined with different values and they won't refer to the same actual variable. So here defining a function where a is being set to two, b is being set to these string local. And then those two values will be printed out. Meanwhile, in our Main's scope, we will print out the values of a and B. Then call the function, which will print those values out, having to find local values of them. And then we're going to print a and B again to see whether or not they've been permanently altered while in function. Let's see that program running. You can see here that were in the global scope. So that's this line here. And there we have the local versions of a and b being printed out. Then once we're back in the global scope, a and B are back with values that we would expect there. Now sometimes it's difficult to know what variables have been defined or available to you in any given scope. This example is a fairly simple program, but understanding what's going on is a more complicated program and that can be more difficult. One function which is particularly useful is vars. If we print out vars, It will show what variables are available in this scope, and it will print them out in the form of a dictionary. Running the program. You can see that we've printed out vars, the available variables in this local scope, R, a is equal to two and b is equal to Local, which is what was printed out. However, if we take that code from this line, so exactly the same thing. Print vars. If we put that here after we're back in the global scope, you'll see that there are more values available. So here we have this much bigger dictionary values. But the most important thing is for us at this point, is that a is equal to one, B equals global, and C has a value of another global. So different values are available depending on what the scope we're in. As you've seen, these are the vars that are available in the global scope. And instead of printing, vars, can print using the function globals, which gives us the global scope variables at any point. So here you can see it gives the same output because the vars are the global vars when printed out in the global scope. However, I think this might muddy the water slightly because it's a different function. It doesn't illustrate the difference in those variables available in the function. And the global scope are the same because you could print globals out while inside the function. So if that gets printed out while inside the function. So if we move globals to be printed inside the function, you can see that these are the local variables and these are the global variables. If this is printed out, you can see it exactly the same time. The global value of a is one and b is global, whereas a is 2x and B is local. So that can get a little bit confusing. But it's certainly really useful to be able to print out vars because you can understand what variables are available to you at the point in that scope. And if you're unsure what scope of function is running in, you can use vars to understand what's going on. But there is something else that also muddies the water slightly, which is if we point out See, it's not defined within this function. So if we can't find it in the local scope, it will then see the value of it from the global scope. So if we run that, you can see that despite the fact that it's not defined in the local scope, sees accessible from the global scope from line three, because it's not defined within that function. This is something you need to spend a bit of time getting your head around. But once you understand it, it will help with your understanding of what's going on generally. But it's easy to tell yourself up in knots, mainly if you use the same variable names inside a function as outside a function. So the local a is different from the global ei, which is why can get confusing. And it's a good idea not to name your local variables with the same name as a global variable. 98. PROJECT: Improved Guessing Game (version 2) - PART 1: All right, let's talk about how you can improve your guessing game project. We learned about functions, so we're ready to apply them in this project, you can take that knowledge and convert your project and guessing game so that it uses functions. The first step is to add a module don't shrink at the start of the file to explain what the program does, we can use triple, double quotes at the beginning and end of the docstring. Now we're ready to update it and make use of a function. Let's name the function as do guess round. We will create a function stub for do guess round. Now, what is the stub function? If you know that you're going to need a function, but aren't sure about the details. You can use the pass key word and leave the code block to be filled in later. An empty function like this, a stub lets you define the function. It will fail if there is no code blog, but we'll work out the details later. It's mainly a place holder to help you organize your thoughts. If you include the docstring, then you don't need any path statement. It's probably been reviewed, include the docstring, indent the code to make it part of the function code block. Now you can add a line at the very end of the program to do the guess round function. Let's run the program. Obviously there is a problem. The game doesn't restart. Can you work out why? Right? We need to add a line that calls the do guess round function from inside the loop. Let's try again. Now the program restarts. Look at that every time the game restarts, the computer's answers exactly the same. And that's not how the game should run. The computer should choose a different number for each round. Let's stop the code with control plus c. Because the number is the same each time. It's probably an issue with how it's stored or chosen. Think about how the path of Python follows it when it flows through this code and where the number choice occurs concerning this flow. Tried to work out why. Now let's solve this logic problem. The program keeps guessing the same number because of an issue with the random Rand INT function location. The program goes through these steps when you run the program, one executes the import, two chooses a random number, three assigns a value to a prompt for defines a function, but doesn't execute it yet. Five starts a loop. Six repeatedly calls the function from inside the loop without choosing a random number. When it calls the function, the random number is not chosen again, the same numbers chosen each time. You can fix it by putting the code, choosing the number inside the function. You can generate the round by adding print statements to clarify when a new round has begun. You do this by putting the code of print statements in a while loop. Also, delete the Dugas round function from inside the loop. Adding a new line, choosing a random number inside the function solves a logic problem. If that's all you are going to do, you will delete the first reference to computers underscore number. You don't delete it because I want you to notice two things. First, the program seems to be working as if there are two variables named computers number. Second, even though the new values keep getting assigned to a variable named computers number inside the function. Those assignments don't change the value outside the function. Run the program. Now to see it happen. It works fine. Stop the code with control plus C. Here is an excellent example of a variable scope that we discussed in a previous lesson in the earlier code. And the name computers number is used more than once. There's one inside the function that do guess round and one defined in main. But never do the two shall meet. It's like they're in different dimensions. What happens to one in one dimension doesn't happen to the other. In fact, each time the function do guess round is called. The variable is a different variable, but it has the same name. The program doesn't remember the value it had last stand, the function was called variables that define inside a function are called local variables. This means that when you're choosing the name of a variable inside of your function, you don't need to remember the names of all the other variables you've ever used. Part1 of guessing game has finished. Study again what you've done until now, and if you're ready, let's move to part two. Thanks for watching. 99. PROJECT: Improved Guessing Game (version 2) - PART 2: Now it's time to spruce up your game a little by adding a score and an easier way to quit, you can't expect your user to know about control plus C, the program will be changed. So that sort of keeps track of the number of rounds the user has played and the total number of guesses made from which the average number of guesses can be calculated. For tracking rounds, the first step is to add a variable called total rounds to the main program. Then you have to increment increase by one total rounds in the main parts while loop. For tracking guesses, the first step is to add a variable called total guesses. In the Dugas round function. The program keeps track of how many guesses had been made while in the function. Name part of the program can't get to the variables within the function. They are local to that function. We will name this variable number of guesses to get the value back to the main part of the program. They are returned by the return keyword and stored in a variable called this round. A running total of guesses is capped by adding this value to the variable total underscore guesses. This is then used to calculate the average number of guesses per round being the total number of guesses divided by the total number of rounds. The flow build-in is used to fourth Python to use decimal rather than integer arithmetic. Some of the print statements in the while True loop had been changed and some have been added to give the user some more information about the round. Run the program to see that it works. Cool. Now stop the program and return to the editor. This is the end of part two. Please practice what you've learned and then continue on to the final part of our Python guessing game. 100. PROJECT: Improved Guessing Game 3 (version 2) - PART 3: Welcome back everybody. In the final part of the project, we will think of a solution when a user can quit the program by typing the letter Q. So let's dive in. Users don't usually want to quit something by accidentally typing something. So instead of quitting immediately, a routine asks the user to confirm the quit. The default answer will be yes. First we'll create the function to confirm the quit. Let's see the steps one by 11 create a constant confirm equipped message to use as a prompt to confirm the Quit, to create a function called confirm quit and then confirm quit function, ask the user to confirm by typing why using input, the players ask for input and the response is stored in a variable called confirm. Confirm with the user typed is n, then the confirm quit function returns false. That means the program should abort war stumped. Confirm is anything else including the user pressing enter without pressing any other key or even a capital N, then the function will return true, confirming that the user wants to quit. The function defaults to confirming the quit rather than aborting it. This assumes that most times your user really does want to quit the game. Now we will continue to define a constant quit underscore text to hold the letter Q, which is what the user should press if they want to quit. You can have them do a guess round return number that never will be a valid number of guesses. Something like minus1 is ideal since the number of guesses can never be negative. You could also choose a number like 100 thousand on the assumption that no one will ever make that many guesses. My preference is minus1. Then define a constant quit program that you're do guess round function will return if the user is quitting, assigned the value of minus one to quit. Azure new constants after import random in the do guess round function at a check to see whether the user has typed q rather than a number. If they have called the confirm quit function to confirm. If the call to confirm quit returns a value of true, then quit. Make the code block return quit program. This leaves the function and returns the value of minus one. If not, make the code block continue, make it the only line in the code block. The continue keyword makes a loop restart at the top of the loop's code block, depending on the type of loop, this may also mean the loops counter is incremented. Your new code should go after the input line. Each time a player guesses, the guess is compared to see if it is the same as it quit underscore text. That is q. If it is, then the player is asked to confirm by calling the confirm quit function. If it is confirmed, then do guess round exit, returning the value of minus one, which is stored in the quit message consonant. It isn't the user typed Q by mistake continues, skips the rest of the current iteration of the loop and restart a new iteration. Since the player's guesses in a number, it's Q, you'd get an error. For this reason, the rest of the loop needs to be skipped. The last thing to do is back in main, check whether the value quit program has returned to the variable this round. If it is due this one, generate a stance message to print because the code is incrementing this round because it expects the player to guess correctly. It needs to be decremented when the quit program code is returned. Before you calculate the players stance, calculate the players average number of guesses per round. The total guesses divided by the total number of rounds. To break out of the while loop. At the end of the program, print the status message for add some print statements at the end to print out the statistics. Overall in the main part of the program. Each time Python returns the Dugas round function, it sees if equip program value has been returned. If it has, the program prepares some messages to be printed on the exit and prints out of the main while loop. After the messages are printed, the end of the file is reached in the program ends. I'll take a quick look at that program now. So it's time to run the final program. Let's play three rounds. I forgotten the total round. Let's click. Run again. And it works great. Now I want to give you two challenges and I want you to try and find the answers. But first you have to watch the lessons and study the section dealing with errors. Let's run again the program and without any guesses, pressed the q to quit, confirm with yes. And look at the rounds. Total rounds are 0. You can't divide with 0, of course. The second challenge is the following. Run the program again and instead of a number, press a letter is a guessing number on an enter, we have a value error because the program accepts only integers. You will find both solutions to the challenges if you want the lessons of section dealing with errors. Wow, you've done a lot. Please do your homework, try to solve the project on your own. Then you'll gain skills and learn new areas of Python you didn't know before. And it can give you great confidence and being able to approach more difficult problems further down the line. If you have any questions, I'd be more than happy to help you. Thanks for watching. 101. Dealing with errors: Most application code of any complexity has errors in it. Humans write applications in humans make mistakes. However, errors can occur that don't provide you with any sort of notification. This section tells you about various kinds of mistakes and what to do when your application encounters them. Most developers call application error exceptions, meaning that they're the exception to the rule. Because exceptions dual current applications, you need to detect and do something about them whenever possible. The act of seeing and processing and exception is called error handling or exception handling. To properly detect errors, you need to know about error sources in y errors had been in the first place. When you do notice the error, you must process it by catching the exception. Seeing an exception means examining it and possibly doing something about it. Sometimes you call it, detects an error in the application. When this happens, you need to raise or throw an exception. You see both terms were used for the same thing, which simply means that your code encountered an error it couldn't handle. So a pass the error information onto him into another piece of code to manage. In some cases, you can use custom Error message objects to pass on the information. Even though Python has a wealth of generic message on objects covering most situations, some situations or special. You need to know how to handle exceptions locally. Send them to the code that called your code. When do create special exception so that every part of the application knows how to handle the exemption. Python provides the final clause which always executes even when an exception occurs. You can place code to close files or perform other central tasks in the code block associated with this clause. When an error happens, people commonly say that an application has a bug in it. Bugs are simply coding errors that you can remove using a debugger. A debugger is a special kind of tool that lets you stop or pause application execution, examine the contents of variables and generally the application to see what makes it tick. Errors fall into well-defined categories that help you to predict to some degree when the end where they'll occur. The two principal types are arrows that occur at a specific time and errors that are a specific type. Arrows are occur at a specific times. The two major timeframes are compile time and runtime. A compile-time error occurs when you ask Python to run the application. Before Python can run the application, it must interpret the code in, put it into a form that the computer can understand. If the instructions you write lack needed information. Python can't perform the required conversion. Fortunately, compile-time errors are the easiest to spot and fix. Run-time. A runtime error occurs after the python compiles the code that you write and a computer begins to execute it. Runtime errors come in several different types and some are harder to find than others. You know, you have a runtime error when the application suddenly stops running and displays an exception dialogue box. Understanding the error types helps you to locate errors faster, earlier and more consistently resulting in fewer misdiagnosis. The trick is to know where to look with this in mind, Python in most other programming languages breaks errors into the following types. Syntactical, semantic, and logical. Syntactical errors, generally the easiest, a logical error is typically the hardest. In the following lectures, we will examine each of these error types in detail. Thanks for watching. 102. Common Syntax Problems: When you encounter a syntax error for the first time, it's helpful to know why there was a problem and what you might do to fix the imbalance intact in your Python code. In this lesson, you'll see some of the more common reasons that syntax errors might be raised. Whether that's due to a typo or a misunderstanding of Python syntax. And most importantly, how you can fix them and avoid them entirely in the future. There are several cases in Python where you're not able to make assignments to objects. Some examples are assigning two literals and function calls in the following code, you're going to see a few examples that attempt to do this and the resulting syntax error track backs. So here we're going to try and to assign five to the length of hello. Now, as you can see, that has generated a syntax error saying that it can't assign to a function gall. Here's another example. Can't assign to literal. The example here both trying to do the same thing, assigning to a string or an integer to literals. The same rule is true for other literal values. Once again, the traceback messages here indicate that the problem occurs when you attempt to assign a value to a literal. One thing to note here is that the examples in the shell are missing the repeated code line and the carrot pointing to the problem and the trace back. The exceptions and track backs that you see in the shallow or different from when you execute the code from a file. If this were the code, you are in a file, you get the repeated code line and cared pointing to the problem as you saw previously. So this kind of misuse of the assignment operator is the kind of thing. Certainly I can say I do more than I shouldn't admit to. It's often been done because I forget the extra equal sign when I'm trying to perform a comparison. So seeing this first example corrected, does what I actually wanted, which was to check that the length of hello is equal to five. And you can see that it returns the value true. Most of the downwind Python tells you that you are making an assignment to something that can't be assigned to. This is the thing to check first that in fact you should be making a comparison. Python keywords or a set of protected words that have a special meaning in Python. These are the words that can't use as identifiers, variables, or function names in your code. They are part of the language and can only be used in the context of Python allows, There are three common ways that you can mistakenly used keywords, misspelling a keyword, missing a keyword, or misusing a keyword. If you misspell a keyword in your Python code, then you'll likely get a syntax error. For example, here's what happens if you spill the keyword for incorrectly. The message reads syntax error, invalid syntax, but that's not very helpful. The traceback points to the first place where Python could detect something was wrong. To fix this sort of error makes sure that all of your Python keywords are spelled correctly. Another common issue with keywords is when you miss them all together. Once again, the exception message isn't that helpful, but the traceback does attempt to point you in the right direction. If you move back from the carrot than you can see that in the keyword is missing from the for loop syntax. You can also misuse a protected Python keyword. Remember the keywords are only allowed to be used in specific situations. If you use them incorrectly, then you'll have an invalid syntax in your Python code. A common example of this is the use of continue or break outside of a loop. This could easily happen during development when you're implementing things and happen to move logic outside of a loop. Here, Python does a good job of telling you exactly what's wrong in this example, the method break outside of the loop helps you figure out exactly what to do. If this code were in a file in Python would also have the carrot pointing it right to the misused keyword. The misuse of continue follows a simple pattern of generating a syntax error with a different message. Another example is if you attempt to assign a Python keyword to a variable or to use a keyword to define a function. When you attempt to assign a value to a pass, or when you attempt to define a new function called pass, you'll get a syntax error and see the invalid syntax message. Again. It might be a little harder to solve this type of invalid syntax in Python code, because the code looks fine from the outside, if you call, it looks good, but you're still getting a syntax error, then you might consider checking the variable name or the function name that you want to use against the keyword list for the version of Python that you're using, the list of protected keywords is changed with each new version of Python. For example, in Python 3.6, you could use a weight as a variable name or function name. But as a Python 3.7, that word has been added to the keyword list. Now if you were to use a weight as a variable or function name, and this will cause a syntax error if your code is running on Python 3.7 or later. Another example is this print, which differs from Python two versus Python three. Print is a keyword in Python 2x, so you can't assign a value to it in Python three, however, it's a built-in function that can be assigned values. You can run the following code to see the list of keywords in whatever version of python you're running. A keyword is also providing the useful is keyword function. If you need a quick way to check the path variable, then you can use the following code. This code will quickly tell you if the identifier that you're using is a key word or not. Often the use of an invalid syntax in Python code is a misread or mismatched clothing, parenthesis, bracket, or quote. These can be hard to spot an exceedingly long lines of nested parentheses or longer multiline blocks. You can spot mismatch or missed quote With the help of Python's tracebacks. Here are the traceback points to the invalid code, where there's a T and a single quote after our previous closing single quote. To fix this, you can make one of du changes. Firstly, you can escape the single quote with a backslash is seen in the example here. We can already see that the shell is highlighting this code appropriately. So it looks like it's going to be OK. Python is happy with it as well. The second option is to surround the entire string in double quotes instead, as seen in the example below, let's see that in action. Once more, you can see that the shell is highlighting this appropriately for a string. So it appears to be happy with what we've done. So is Python. Another common mistake is to forget to close a string with both double quoted in single quoted strings. The situation and tracebacks will be the same. This time the carrot in the trace back points right to the problem code. This syntax error message EOL while scanning the string literal is a little more specific and helpful in determining the problem. This means that the Python interpreter got to the end of the line, the EOL, before an open string was closed. To fix this, close the string with a quote that matches the one you use to start it. In these cases, the first would be with a double quote, the second would be with a single quote. Quote missing from statements inside an F string can also lead to invalid syntax in Python. Here the reference to the ages dictionary inside the printed F String is missing the closing single quote from the key reference. 103. Become a Bug Bounty Hunter: Bugs are an integral part of programming. Once you've moved beyond the simplest program that you create, you will no doubt encounter this. It can be a frustrating part of the learning experience, but you'll find often that is the most rewarding experience that will teach you the lessons you need to know the boast. Remember, nobody creates code without bugs. The key to finding bugs. Methodical. It's no use just randomly trying to change things. It's better to try and get in the mind of what the computer is trying to do and seeing if it is really doing what you think it's doing. Many has been at the time when it is looks like it's doing what I think it is, but actually I've looked at the details of it and maybe have gotten lucky. And actually it's much less than what I had originally planned. We're going to look at two ways of solving the issues. Firstly, the old-school way favorited by Guido van Rossum, who was using print statements. So now that you're going to see that in action. And also you may will spot the bug that's present in it. But the idea is really going to create a program that is simple to understand rather than create an hysteric difficult to find bug. Don't worry, you'll have plenty of those to deal with later on. So you're going to see a simple number guessing game. The computer's going to think of a number between 110, then the user has to guess it, and then the computer will tell the user whether they got it right or not. So here comes the code. I'm going to import the random library to allow us to generate a random number. Print a message for the user, create the random number. And now we're going to let the user input their guests and assign that to the guest variable. Now we are going to check their guess is the same as the number. And if it is, we will tell them that they are right. And if it is not, we will tell them they were wrong. There we go. The program is complete and now you're going to see it in action. So I'm just going to keep it running until the bug makes itself known to us. And there after the first time, sometimes many more times than you had expected. But that's the nature of randomness. We see our bug, it saying, sorry, the number was five, not five. So up to this point, you might have thought your program was working fine. You could have shown it to somebody and been happy about it. And then somebody's going to say Hang on a minute. It said the number was five, not five. What's the problem there? So what we need to do is to use a print statement to help us find out what the problem is. I'm going to insert one here. And now we're going to need to rerun the program. In this case, what we just printed out isn't going to help us too much because it's not the representation, that's the problem. It's the actual information. So let's look a little deeper. Here. We're going to look a little deeper at this and look at what the type of number is and guess. And there we see the problem. The problem is that our number isn't deny and t because it's been created randomly by a dot rand INT. But our guess is an SDR or a string. And when we print STRS or ion Ts out, they look identical to us on the screen. You may have noticed that this wouldn't be the case if you're doing this kind of work in the Python shell. So it's important to realize that print may not always show you all the information you need to find subtle bugs such as this. But it can be a really useful and quick method to find out what's going on when a program is running. So in this case, to fix this particular bug, the input needs to now be turned into an INT. Now this would fall if the user types something which could be turned into an INT. But in this case we'll just leave it as it is to be nice and clear. So now we run the program again and we can see that they are both INT. And if I run it enough times to get the guess right. Finally, we get to a point where the guess was five and the number was five. And we can see that the program works as intended. Having seen printing action next PDB, the python debugger. So on screen you can see the buggy number guessing program from the previous session. And we're now going to import PDB to allow us to use it to debug this program. So I've imported PDB at the beginning and at the point where I want PDB to take over the execution of the program, I put the following line. I'll also delete the code lines I've attached. So as you can see, the program will run normally until it gets to this point. And then we'll be able to take over step-by-step execution. And it'll allow us to look inside the program as it's still running in memory. So we get to enter the number normally, but as you can see, it looks quite different. The PDB line at the left shows us that the PDB has taken over the execution of the program. Now it's really easy to forget where you are in the program. So one of the key instructions is to use i for the list. We can see that it's showing us a section of the program in this case saying we're at line seven. And the next instruction is going to be to guess if equals number. But what we can do right now is looking at what's in the computer's memory. And it's much like a normal Python shell. If I type, we can see the value of a number. If i type, we can see the value of a guess. And straight away this is worked a little better than print because it's indicating to us that this isn't an INT, it's a string. So with this one command, we've already found what the problem is. Whereas with print, we needed to delve deeper and manually print out this type of variables in question. But let's let this program move on. And we can do with C For continue. As you can see, it runs to the end. It's illustrating that it works normally. And because this is a small simple program, that's what we need to do. Now if we put trace in a different place, we could cheat. Let's take a quick look at that. So now I've put it before and I need to put my guessing so I can cheat. I can look inside the computer's mind, see what it's picked, and then put that number in, which we'll sometimes be useful to allow you to not have to run the program ten, 15-20 times, et cetera. Let's see what the number is. So now I can continue. It's asking for inputs. Now again, this is really easy to fix as you've seen in the previous video. But the idea of this was to give you an idea of how to use PDB. But also the PDB is a really flexible thing because you don't have to type out a load of print statements. You can just affectively pause time, look around the computer's memory and work out what's going on without having to put 20 print statements in. You can step through the program and examined variables each time it comes around. 104. Basic Exception Handling: Hey everyone. In this lesson we are going to cover how you can handle errors using try and except. So let's get started. Python provides a vital feature to handle any unexpected error in your Python programs. Your application should always catch the exception and handle it before the user sees it. To handle exceptions, you must tell Python what to do so and then provide code to perform the handling tasks. The try and except statements is excellent for handling errors. It is a control statement as it controls on the program proceeds when an error occurs. Here is the syntax. Type, the following code. The program attempts to execute the statement erythema ten divided by 0, which is impossible. So the remaining of the try blocks is ignored and the statement is in the except block is executed instead of the predefined error message for each of the different types of errors. If you want to display the message, you can use the as keyword after the error type. For example, to display the default value error message, you write. E is the variable name assigned to the error. This is an example of using the predefined error messages and catches on any unexpected mistakes. For a complete list of error types in Python, you can refer to this website. If you want to display more specific error messages to your users, depending on the error, you can specify the error type after the exempt keyword. Now let's work on some other examples. The code within the try block has its exceptions handled. In this case, handling the exception means getting the input from the user by using the INT input calls. If an exception occurs outside the block, the code doesn't handle it. The except block looks for a specific exception, in this case, value error. When the user creates a value error exception by typing jam instead of a numeric value, this exception block is executed. The else block contains all the code executed with a try block code is successful, does not generate an application. The remainder of the code is in this blog because you don't want to execute it unless the user does provide valid input. When the user provides a whole number as input, the code can then check it to ensure that it is correct. Run the code and type Jim instead of a number between 15. The application displays an error message. Now rerun the code and type 20 instead of a number between 15. The application outputs and unexpected range error message. Exception handling doesn't weed out range errors. You can create an exception handling block in Python that's generic because it doesn't look like a specific exception. Sometimes you may need a generic exception. Let's make an example using an except clause without a specific exemption attached to it. The result is that this except clause will also catch any other exception that occurs. The code detect specific errors first and then uses fewer specific handlers only when necessary. Run the code and type Jim. 105. Handling Multiple Exceptions: Most applications can generate multiple exceptions for a single line of code using a single except clause to handle various exceptions works only when a common source of action fulfills all the exception needs. Otherwise, you need to handle each exception individually. The following example shows how to handle multiple exceptions by using a single except clause. Type the following code into the editor. Note that the except clause now supports both a value error and a keyboard interrupt exception. These exceptions appear within parentheses and are separated by commas. Run the code and type Alan. Enter. The application displays an error message, re-run the code and press control plus c, the same error message. Run again and now type 20 and press enter. The application displays the second error message. When working with multiple exceptions, it's usually a good idea to place each exception in its own except clause. This'll approach allows you to provide customer handling for each exception and makes it easier to know precisely what rent wrong. Of course, this approach is also a lot more work. Let's make an example of how to perform exception handling by using multiple except clauses. Type the following code into the editor. Each exam clause handle the different exemption. You can use a combination of techniques except clauses handling just one exemption and the other except clauses handling multiple exceptions. Run the code and press control plus c. Look at the message. Now run again and take 20. The error message change to the value you type is incorrect. One strategy for handling exceptions is to provide the exact except clauses for all known exceptions and generic except clauses to handle unknown exceptions. Look at the exception, a hierarchy that Python uses at this web address. In the following example, we will use the base exception, which is the upmost exception, then the keyboard interrupt exception. And then we will use the specific ZeroDivisionError exception, take the following code into the editor. The code begins by obtaining two inputs, value1 and value2. The first two except clauses handle unexpected input. The third except clauses raised when the result of an arithmetic operation is too large to be represented, or a number divided by 0. The fourth except clause handled specific math exceptions like dividing by 0. If anything goes well within the application, the else clause executes, which prints the operations result. Run the code. Python asks you to type the first number, type Udemy, and as expected, Python displays a value error exception message. Run the code again and type five is the first value and 0 is the second value. Now you can see the arithmetic exception and the error message. Here. I wanted to say that this arithmetic exception is not so useful, but I typed it for learning purposes. Let's delete these code lines and run the whole code. Now you can see the 0 division error run again and press control plus C. This is the keyboard interrupt exception. So in this lesson I have provided exact except clauses for most of the cases. If you have questions, please let me know. Thanks for watching. 106. Raising Exceptions: In some situations your application must generate an exception. This act is called raising or sometimes throwing the exception. Let see some common scenarios in which you can raise exceptions in specific ways. Let's see how you raise a simple exception that it doesn't require anything special. The following steps simply create the exception and then handle it immediately. This code shows you how raising an exception works at its most basic level, run the code in Python displays the expected exception txt. Python provides flexible error handling in that you can pass information to the caller, the code that is calling your code, no matter which exception you use, the following code shows that you can modify the output so that it does include helpful information. The value error exemption, it usually doesn't provide an attribute name for a common name for string error. But you can add it only by assigning a value to it is shown when the example raises the exception and the except clause handles it as usual, but obtains access to the attributes using e. You can then run the e dot square. Remember, to obtain the added information, run the code and Python displays and expanded value error exception. As you can see. 107. How to Debug in IDLE 2021: A bug is an unexpected problem in your programming. They can appear in many forms and some are more difficult to fix than others. Some bugs are tricky enough that you won't be able to catch them just by reading through your program. Luckily, Python idle provides some essential tools that will help you debug your programs with ease. If you want to run your code with the built-in debugger, then you'll need to turn this feature on. To do so, select debug debugger from the Python idle menu bar. In the interpreter, you should see the debug on appear just before the prompt, which means the interpreter is ready and waiting. When you execute your Python file, the debugger window will appear. In this window, you can inspect the values of your local and global variables as your code executes. This gives you insight into how your data is being manipulated as your code runs, you can also click the following buttons to move through your code. Go. Press this to advance execution to the next breakpoint. You'll learn about these in the next section. Step, press this to execute the current line and go to the next one. Over. If the current line of code contains a function call, then press this to step over that function. In other words, execute that function to go over to the next line. But don't pause while executing the function unless there is a break point out. If the current line of code is a function, then press this to step out of the function. In other words, continue the execution of this function until you return from it. Be careful because there is no reverse button. You can only step forward in time through your program's execution. You'll also see four checkboxes in the debug window. Globals, your programs global information, locals, your programs local information during execution. Stack, the function that run during execution, source, your file in the idle editor. When you select one of these, you'll see the relevant information in your debug window. Breakpoint is a line of code that you've defined as a place where the interpreter should pause while running the code. They will only work when debug mode is turned on. Make sure that you've done that first. To set a breakpoint, right-click on the line of code that you wish to pause. This will highlight the line of code in yellow is a visual indication of a set breakpoint. You can set as many breakpoints in your code as you like. To undo a breakpoint, right-click the same line again and select Clear breakpoint. Once you've set your breakpoints and turned on the debug mode, you can run your code as you would normally. The debugger window will pop up and you can start stepping through your code manually. When you see an error reported to you in the interpreter python, I will let you jump into the offending file or line from the menu bar. All you have to do is highlight the reported line or the number of filenames with your cursor and select debug. Go to the file slash lines in the menu bar. This will open up the offending file and take you to that line that contains the error. This feature works regardless of whether or not debug mode is turned on. Python idle is also providing a tool called a stack viewer. You can access it under the debug option in the menu bar. This tool will show you the track bar of an error as it appears in the stack. And the last line of the exception that Python idle encountered while running your code. When it unexpected or interesting arrow occurs, you might find it helpful to take a look at that stack. Otherwise, this future can be difficult to parse and likely won't be useful to you unless you're writing very complicated code. 108. Rock, Paper, Scissors OVERVIEW: Welcome to rock-paper-scissors, a command line game. In the next lessons you'll learn about writing a command line rock-paper-scissors game, handling user input, looping for multiple games in a row, creating functions to group code, using dictionaries to store rules and replacing constants with Ina objects. A quick note about versions. All code in the lessons was tested using Python 3.9. There isn't much in here that is first and specific. Any interpreters starting with Python 3.4 will work just fine. The common path to becoming interested in programming is through the love of video games. This makes writing your own game or logical place to start when you're learning to code. Graphical games have extra things to learn because you're dealing with withdrawing to the screen. Command line-based games are the perfect entry way. You get to write some code player game, but not to be buried under a bit of belittling or vector math. If you've never played before, rock-paper-scissors is a two-person game often use to quickly decide who goes first and a board game, who gets the first slice of pie? Ronnie, simple decision. Each person counts to three, shakes their fist and then makes a symbol. This is called throwing. The symbols make the three ways circle each symbol beating the other one. The choices are and make a fist show rock, rock smashes Scissors, make a palm to show paper, paper covers rock, or show two fingers. Careful where you're pointing those in Britain to make the scissors, scissors cut paper. To build a text-based version of the game, you'll need to take user input, randomly choose a computer's throw and compare who one. Next, I'll show you how to get input from users and then loop to create a repeated play. Thanks for watching. 109. Rock, Paper, Scissors With Python Input and Loops: In the previous lesson, I gave an overview of the game. In this lesson, I'll show you how to get input from users and then use a loop to create a repeated play. The simplest form of the game service by taking the user's choice, having the computer choose a random response, then displaying the results of the user. Let's see some code to do just that. Log into your account. Here you'll start with writing the code. The first bit of code you're going to tape is import random. This loads the Python module named random. This module contains functions that allow for randomly selecting between choices and numbers. You'll use it to choose the computer's response to the player. Speaking of choices, you'll want to specify what the choices are. In the next line, you'll declare choices, a list containing the strings, rock, paper, and scissors. Next you're going to type a line that prints a challenge to the player. So type print parenthesis, double-quotes, make your throw. Close double-quotes and parenthesis. Next, you have to think of a way that requests a player response. This is done with input function. The built-in input function takes a string that is used to prompt the user and returns whatever the user typed in. The user's choice will be stored in the variable named user choice. You shouldn't just accept any random thing from the user. You want to make sure it's a valid choice. So you will use the IF function. So type if user choice in choices. This line verifies that the user typed in one of these items in the choices list. If it is, then the next line randomly selects the computer's response. The random modules choice function takes a list and randomly chooses one of the items in the list. The selection is returned and in this case is stored in the computer's choice. Next, we're going to type a command line that contains a print statement showing the results to the user. Type print open parenthesis, and press Enter. If you haven't seen in f string before, it's a way of creating a template that Python will fill in. An f string is prefixed with the letter F, hence the name. Then it looks for brace brackets. Those are the curly ones inside the string. Values in the brace brackets are replaced with their corresponding variables. In this case, the user choice and the computer choice values are inserted into the stretch. Press Enter. The whole thing is then put into the screen by the print function. Since IF function check for valid values, you'll want to tell the user if they didn't choose something valid. In the next line inside this else clause, tell the user what they typed and tell them it wasn't a good choice. Let's see the game in action. Here. I'll run the script into rock, and it tells me that I chose rock and the computer through scissors. Let me run it one more time. This time, I'll enter lollipop. No, not a valid choice. Each time you want to play the game, rerunning the command is a lot of work. Not that much, but you can still make it easier. What about asking the user of the throat down again? To do this, you'll need to wrap all the game logic in a loop. After the result is shown, prompt the user if they want to play again. Let's modify the code. The first step is to add an infinite loop. After the list choices with a while loop. The while statement loops until the condition associated with it is evaluated to be false, is true, will never evaluate to false. This loop goes on forever. The next chunk of work is the previous code, but embedded inside the loop. So I'll press a tab before each line of code we spoke about indentation in Python and why it is so important. Just to remember, indentation is the leading whitespace, spaces and tabs before any statement in Python. The reason why indentation is important in Python is because Python treats the statements that have the same indentation level, statements that have equal or no whitespace before then as a single block of code. Once Around has been played. This process, the user, if they want to play again, Let's call it variable again. Then you'll add an input prompt. If the user wants to play again. I am going to add a new line that checks the users answers and sees if it matches M. For now, the dot lower method is called on the answer before it is compared. This method will return the lowercase version of the string it is being called upon. That way if the user inputs capital N, it will be turned into a lowercase n before it is compared. If the user indicates no, then the break statement is called. The break statement breaks you out of the surrounding loop. In this case, the code would continue to the next line. If the user type anything by n, It is assumed they meant yes. In this case, the code inside the loop continues here you will add an empty print, which will display a blank line. After that, the execution continues back to the top of the while loop, asking the user to make their next thrill. Just because it is flight, the code says goodbye to the user after breaking from the while loop. Here is the new modified code in all its glory. Let me run the code. I'm going to enter a choice this time, albeit paper. It shows me what both the computer and I picked and then prompts. If I want to go again, I'll TBS and the game continues. Let's choose paper again. Now I think I'm done. See, isn't it nice that it said goodbye, just bringing the choices isn't good enough. In the next lesson, I'll show you how to say who won. 110. Rock, Paper, Scissors With Python How to Determine a Winner: In the previous lesson, you guys started by writing the initial code for rock paper scissors. In this lesson, I'll show you how to add code that declares the winner in each round. Just showing you the choices that the user made in the right of computer choice feels like a bit of lightweight. Let's add some code to say who won. You'll need to encode the logic for each situation of x beats. Why? We're rock smashes scissors, paper covers rock and scissors cuts paper. As the logic for determining who one kind of goes together, it would be best to put this inside of a function. You might even name it something meaningful. You'll start to modify the previous code with the winner determination logic inside of it. It is good practice to group related bits of code together and functions. This allows reuse of code through multiple calls to the function and the clarity of reading your code. After the list of choices, you're going to add a new line that declares the show winter function. It takes two arguments. The first is named user choice and the second computer choice. In the next line, you're going to check if the user and the computer chose the same value. If SIL, the user choice is the same as the computer choice. Then in the next line, the program prints that there was a tie and both users chose the specific selection. The next line you will add else-if, which will only run if the user and the computer chose different values. This line checks if the user chose rock. If they did, there are two sub cases. The computer chose scissors and therefore the user one. The computer chose paper in the computer one. Remember, if the computer is chosen rock, you wouldn't get here is that bit of logic is caught by this line. The next step is to add an e Lyft Line, which is similar to this line, but for paper. Similar logic is contained with the else-if block processing the win and lose conditions for paper. Then you do it again versus IRS and its associated win and lose conditions. Finally, if anything but rock, paper, or scissors was typed, it is caught by the else clause. By typing this line of code. In this case, the user is told that their throat was bad. The code in the wild loop is pretty close to before, just with the new line that calls the show winner function. Delete these lines of code, we don't need them. Let's type the new code right here. You're all set to play now, let's run the game. All type ROC. Be play again. Rock one more time and you get the idea. A large if-then else blog like I just demonstrated, can be a bit hard to read. It only gets worse the more conditions you have to compare. These kind of code is so common that Python 3.1 L has a new keyword structure called pattern matching. This is a bit new of a syntax in Python that displays a series of choices based on a pattern. This structure will allow you to write large if then else blocks with fewer lines of code. If you're used to switching statements in other languages, it's a custody of that. There was some debate over the pattern matching statement, but however, you might feel about it until Python 3.10 is out, you're stuck with if then else or are you. Let me show you a wave using data structures in your code helps simplify the amount of coding logic and reduce the size of the if. Then else block. We're going to add two new dictionaries, beats and messages just after the choices list. Let's take the first change in the previous program, which is the introduction of beats dictionary. This dictionary is storing the what beads, what conditions. Each key of the dictionary is, period against the list of things that beats. You'll understand why use the list in the next lesson. This line encodes the fact that rock beats scissors paper beats rock and scissors beats paper. You could simplify the message to the user by changing the language to say x beats y. Instead of having the specifics of rock smashes scissors. But instead the verb describing the winning action inside another dictionary called messages. Each key in this dictionary is a tuple describing what beats, what. The first one says that when rock beats scissors use the word smashes. This can be simplified by just having the winning item B, the key to this dictionary. But the next lesson adds some complexity that this prepares for. The next line encodes that paper covers rock, and in the next line, scissors cuts paper. Let me scroll down a bit. When the game's rules encoded in dictionaries, the code for show winter becomes a little simpler. Line 1819 are the same as before checking for the Thai condition. But now you'll have to change the chunk of the if-then else previously the check for bad data was done at the end of the function. I will move it up here. Let's delete the lines from 20 to 36. The DOD keys method on the beats dictionary returns a list of all the valid keys. User choice is not in that. It means that it wasn't a valid choice. The else block that starts on line 22 now contains all the who'll be is what logic? This line, I'll do a Boolean comparison checking if the computer's choices in the list of things that are BY, by the users choice. If the user chose rock, the key rock is applied to beats. Returning the list containing just scissors. If the computer chose scissors, then there is a match and the resulting Boolean comparison is true. These values stored in user wins. The next line then evaluates the Boolean called user wins. The user did win than they look at the appropriate verb in the messages dictionary using the user and computer choice tuple as the key for the choices of rock and scissors, the result will be smashes. With the verb, ready to go. All that is left till is the user is the good news. This f string shows the user's choice, the computer's choice, and the associated verb. Note that inside the brace brackets for the user's choice, there's more than just the variable there. An f string allows you to call methods on string objects that don't capitalize method returns a new string with the first letter capitalized. This will make the beginning of the sentence look right. Of course, the user doesn't always win. The else clause does the mirror logic. As the computer is one, the verb is looked up using the reverse of the tuple in the previous block. Then the user is told the bad news. Code is a bit shorter than the large if then else block from the previous lesson. It might not even be worth it in this case, but when the game gets more complicated, you'll have saved a lot of work. Not much to see here that you haven't seen before. The code was refactored, but the end result is supposed to be the same three-way decision-making is just not complex enough. Congratulations, you've just finished coding a game in Python. You now know how to create rock-paper-scissors from scratch. And you're able to expand the number of possible actions in your game with minimal effort. Writing games is the fun way to get practice writing code. In this project, you're implemented a text-based version of rock paper scissors. You ask the user for input and validated it, looped or code to allow repeated plays added to show winter function to determine who won and simplified your show winter function by replacing some conditional logic with a data representation stored in the dictionary. I hope you found value in this project. Thank you for your attention and I will see you in the next lesson. 111. What Is Object Oriented Programming (OOP): Hi everyone. I want to welcome you to our lesson on object-oriented programming in Python three, this is one of the biggest and most important subjects in all of the programming. And as you can see, we have a lot to cover. This series will provide you with a basic conceptual understanding of the object-oriented programming so that you can take your Python programming skills to the next level. To fully appreciate the subject, we have to first understand why we needed programs or overly complicated things. And there's a 100 different ways that you can define what a program is formal. Still, basically all programs or set of instructions for manipulating data in some meaningful way. When I teach Python to kids, I always have them write a program that calculates how many days old they are. And that's a great example of a program that follows these three steps. First, the program has to ask the user for their birth date. That's the data it's going to accept. Then it manipulates the data by subtracting the current date from the user's birth date. Finally, the program displays the result of this calculation on the screen. That's a great starter program, but it's very trivial. How do we manage large programs with lots of data to keep track of like a video game. As you might have guessed, that's where object-oriented programming comes in. Object-oriented programming, or OOP for short, is a quite common programming paradigm. In formally, this means that it's a specific way of designing programs, like a style that's widely used in software projects. Not every program should be written with that. Oop, but many are. And lots of languages supported. A lot of the Python code you interact with on a daily basis will be written using OOP. Understanding this is a fundamental part of becoming a gripe Python programmer. It opens the door to creating really cool software. At the heart of OOP is the idea that a program is composed of lots of individual objects. You can think of these objects is entities or things in your program. Oftentimes they are like the nouns in your project, such as the person, a house, an email, or any other entity like that. These objects are like little bundles of data that are passed around throughout the life of your program. For example, a person might have properties like name, age, and a home address. This is the individual data that the object stores throughout its life in the program. When we create this person object, we'll make sure to give it a name and age and an Address. Objects also have behaviors. These are the actions that the object can take. Our person should be able to walk, talk, and breathe, for example. Frequently, these behaviours will be needed to be referenced in the properties of the object. For example, if we make our talk behavior print the name and the age of the person, then our person object would need to know what its age and name is. Those properties we gave it earlier before. If this all seems a little bit confusing right now, don't worry, when I started programming, this was the first real hurdle I ran into. And it just took some dedication and practice until I finally understood it. We'll make heavy use of objects throughout the rest of these lessons. And you'll love the feeling you get when it just clicks for you. In the next video, we'll learn how to define our own objects using Python classes. I'll see you there. 112. Classes in Python: Welcome back to our video series on object-oriented programming in Python. In the last video, we learned what object oriented programming is and what problem it solves. Now let's take a look at how we can define our own objects in Python programs. To create our own objects, we use Python classes. Classes are used to create objects practically as many unique objects as we want. They also define a type. For example, take a look at this code. My underscore name equals to Austin. Here we create a new variable called my name with a value of Austin. Behind the scenes to variable is actually referencing an object. The type of object is STR, short for string, which is built on Python data type that you've probably used before. Python defines a string is a class and in order to create this type of object of STR, we instantiated the STR class to instantiate a class or to create an instance of a class, just means to create an object from that class. You have here the word instantiation thrown around a lot in programming. So just remember, it means to take a class and to create an object from that class. To make this a little bit more clear, I'm going to use one of my favorite analogies. Let's say we're writing a program that creates doors. We'll start by creating a class for a single door. This class here is like the blueprint for which we build all of our door objects. The class will specify some properties and behaviors. Remember, each of our door objects will have these and there'll be independent to each door object. A door could have properties like height, paint color, and whether or not it's currently locked. It could also have behaviors like open, close, and toggle lock. We've defined a door class, but we've also just defined a new type we can use in our program. Let's create a door object with a height of 50 inches, painted orange. And we'll just say that we build it, it's unlocked. Here. We've just instantiated the doors class. Remember, that means we've created an object type of door from our doors class. And we aren't limited to just creating one. Just like how in the real world we can build lots of doors from a single door blueprint. We can initiate many door objects from our single door class. Here I've instantiated one more. Notice that each of these door objects is unique. They have both different heights and colors and each of them can be either locked or unlocked at anytime. We can change the paint color of a single door and that doesn't effect the rest. These objects are all independent and they didn't rely on the class anymore. The class just tells Python how to create the objects. Here's a question. Can you think of any scenarios where classes and objects could be used in a real-world program. In the next video, I'll give you some examples and then we'll learn about how classes are actually built in Python. 113. Class and Instance Attributes: Welcome back to our object-oriented programming in Python. In the last video, I asked the question, we're going to use classes and objects in real software. I came up with two examples, video games in web browsers. For a video game, we might define an enemy class at Holt properties like the name of the enemy, their current health and their power level. For behaviors they might be able to attack, take damage, and finally, if their health is low enough, declared defeat. Video games are a great example of complex object oriented software design. They are built with lots and lots of classes and then they rely on one another in some way or another. The web browser you're using right now can also be designed with OOP. Individual dams can each be their own objects instantiated from the tab class. The properties could be the title text, whether or not the tab is currently the one being viewed and also the webpage the tab is showing. For behaviors we could have clothes and reload. Now, look at each of these properties carefully. I think the title text is being represented as a string and whether or not the tab is open. Well, this could be a boolean, true or false. But what time should our webpage property B, there's no data type built into Python that can store everything about a webpage. So here we can actually create a separate class called page with its own properties and behaviors. As you can see, the properties of a Python class aren't limited to built-in data types in Python like INT and SDR. Our own custom pages like page can also be used as properties of other classes. When we instantiate a class TAM below, we also have to provide it with a page object to store, just like we have to provide it with an STR object for the name. The point of this exercise was to show you to think of software as a collection of objects that interact with one another. In my experience, the hardest part of learning OOP is not actually learning the concepts themselves, but learning how to design a software in terms of OOP, planning out your software project often takes a lot longer than actually coating it. It's something that can challenge both new and the season developers. As you know by now, a class defined both the properties and behaviors of its object. So now let's actually write one. To define a new class, we start with a keyword classes followed by the name of the class. Easy enough. And well, we haven't really learned how to define properties are behaviors in Python. So let's just write paths. This is a special keyword that tells Python that this is an empty class. Before we can add properties to our class, we have to learn about how they work in Python. First off, properties are actually called attributes in Python. These are two types of attributes, instance attributes and class attributes. Instance attributes are what we've seen before. These are the attributes that are independent to each object like door color, or the height. In the previous example. In this example, our dog classes to instant attributes, name and age. This def underscore, underscore, init, underscore, underscore. This is a very special function that belongs to our class. This is called the initializer, and it's sort of similar to a constructor. If you've ever seen that in another language, we don't actually call this function ourselves. Instead, Python will automatically call this function when we instantiate the class. In other words, this function is used to construct a new objects from the class. The object of the initializer is to provide our object with initial attribute values. You can see this initializer takes three parameters, self name and age. When we instantiate the dog class, you'll need to pass the values for name in age, and then this function will assign the new objects those values. Self is a very special keyword, and the fact we have to include it in our parameters is one of those little Python corks. We don't pass a value in for self when we create the object. Instead, self is used to refer to the current object being created during instantiation. So when we say self.age equals age, we're saying take the value of age, we pass in and assign that to the new objects. Don't age attribute, and the same goes for name. Remember before how we said each object has its own independent values for its attributes like how one door can be orange and another one gray. Well, that doesn't actually have to be the case. This is where class attributes come into play. Unlike instant attributes, which are independent for each instance of the class, class, attributes are the same for every instance. Think of it like this with instant attributes, we could paint one door a new color and it wouldn't affect the colors of the other doors. However, if we make the color a class attribute and we set it to yellow, then all doors would be yellow by default when they are instantiated. This is just a default value for the class. This doesn't mean that we have to instantiate all of our doors. Changing the color of one door will change all of them. If you're thinking static right now, this is a little bit different. In the example of the dawn class, species is defined outside if the initializer function, which means that it's a class attribute. This means that every dog we instantiate will by default be a mammal. And we can't change that when we create a new Dog object. In the next video, we'll start programming our dog class and we'll see how class instantiation works in Python. 114. Adding Attributes to a Python Class: Welcome back to our series on object-oriented programming in Python. In the last video, we learned how Python classes can define both class attributes and instance attributes to better understand how classes are instantiated. Let's head over to the Python shell. All right, so I'm here in the Python shell and I'm going to start by creating a new class Dog. And I'll just write pass, which will tell Python that we want a blank object. Now I will simply call dog-like this. Python will instantiate that and it will actually tell us the memory address of our new Dog object. That's this fancy-looking number right here. Now let's create another dog object. Do you think that this new object will share the same memory address as the first one? Or is it going to be different? If we press here, you'll see that this new object has a slightly different memory address. This is because each incident of our Dog class is unique. Sure, both objects are created from the same class, but they're still different objects in memory. If we actually fill down our class with the initializer, we could assign different attributes to each object. And just to drive this point home, I'll create two new dogs and I'll store them in variables a and b. So at this point, a and B are both variables that point to objects in memory, objects and type dog. We can easily check if they're the same object by using the double equals operator. And if I press enter, we will see that they are not a and B pointed different dog objects, even though both objects are blank. And to prove that both of these variables are type of dog, I'll use Python's built-in function L, Give it a as an argument. As you can see that this variable is pointing to an object that was instantiated from the dog class. Now let's finally build a real dog class and create some real dog objects. I'm here in the Python idle, and I'm going to start by defining a new class called dog. Next, I'll type species equal to mammal. This is going to create a class attribute for our dog. This means that every new dog we create is going to be a mammal by default. But now I want to write some unique instance attributes. So I'll add in an initializer to the class by typing out my init function. And now we'll require three parameters, self, name and age. Remember, we don't actually supply a value for self, but we do need to do something with these names and age parameters. So all tell Python that we want to assign them to a new object being created. Here, self references to current object being created. So self.name equals name, means to assign the name parameter to this dog's name. And that's it. We've created our dog class. Let's actually use it down. We'll create a new variable called Tommy. And this is going to point to a dog object. We create a new object by typing the class name followed by the parenthesis, almost as if it were a function. When we do this, Python is actually going to call the initializer behind the scenes. And so will we need to supply our name and age arguments. So here all make the name Tommy and we'll give him an age of five. Next, let's make another dog named Lily, and we'll give it an age of seven. Congratulations, if you've been following along, you've just created an instantiated your first-class. Right now we have two dogs, one named Tommy with an age of five, and the other named Lily with an age of seven. But how do we actually access the data inside of these objects? To do that, we can use the access modifier, which in python is the dot. So I'll type a print statement. I'll say blank is blank and blank is blank. And then I'll call the DOD formation function on this string, which will allow us to populate these blanks. Because we have four blanks, will need to pass in the Don format function for arguments. So I'll pass in tommy dot name, Tommy dot, age, lily, don't name Lilly dawn age. These are going to access all of the attributes in both of our objects. Next look, see if both dogs have the mammal attribute. I'll type if Tommy dont species equals the string mammal, then I want to print blank is blank. Then just like before, I'll fill in these blanks with Tommy's name and Tommy species using the dot format function. Alright, let's run code. And the above side here we can see exactly what we were expecting. Tommy is five and Lily is seven, which is from our first print statement. And then because Tom is a mammal, we also saw that Tommy is a mammal printed to the screen. Now let's change things up a bit. After we create a dog's new objects, let's change their attributes. So I'll move up a few lines and I'll type Lily dot h equals to eight, and then Tommy done species equals to mouse. Now pause this video and take a look at this code and think about what it's going to print. All right, let's take a look. Now we see the Tommy is five and Lily is eight. That's because a change Lily's age after we created the object. And notice that we don't see Tom is a mammal anymore. That's because we change Tommy for being a mammal to a mouse. And again, we did that after we created the object. When we assign a value to these attributes, the initializer wasn't used and that's only used when we create new objects, not modify their attributes. Also, if you notice here, both Doug objects are completely independent of one another. Even though they came from the same class. Even though I change Tommy for being a mammal to a mouse, Lily is still a mammal. And that right there is just scratching the surface of the power of object-oriented programming. In the next video, we'll take a look at instance methods, which is the fancy Python way of saying class behaviors. I'll see you there. 115. Adding Methods to a Python Class: Welcome back to our series and object-oriented programming in Python. In the last video, we created this Dawn class here, and we printed some information about each of our dog objects on the screen. If you remember, we created door objects that could be open, closed, and logs. I call these behaviors just to demonstrate the concepts. But in Python, these are actually called instance methods. A method is just basically a function that belongs to a class. It's using the exact same way as a function, except like the initializer, we must include a self parameter. Let's actually create some instance methods. First, we need a way for the dog to report its attributes and a nice formatted way. We'll create the new instance method called description. And remember that we need to include the self parameter here. And now we'll type return a blank is blank years old, and we'll use the handy format function to fill in those blanks passing in the self.name, self.age as the arguments. Notice here, how we are not directly printing to the console. Instead, we have this method for returning a nice formatted string with a dance attributes baked into it. So we'll need to print out manually later on. Next, we should add a way for the dog to speak something. So let's create a new instance method and we'll call this one speak. This will take the cell parameter just like before, but I want her job to be able to say whatever we tell him to. And let's add another parameter called sound. This will need to be provided when we call this method later on. Finally, we will return a formatted string where the dog dot name says the sound that we pass in just like before. Now let's delete all of this old code from the last time and we'll create a new Dog object called Tommy with the name of Tommy and an age of six. Just like with attributes, we can use dot to access instant methods to. Now you might be tempted to write Tommy dot description here. And while technically that's not wrong, that wouldn't actually output anything to the console. That's because we have the DOD description method returning a formatted string rather than directly printing it. And so this code here will get that formatted string, then do literally nothing with it. If we want to actually see it, will need to pass the return of this method call into the print function. Next slot to use our speak method will write print Tommy, don't speak, and then we'll pass in graph, graph. And now if we run the code, we'll see that on the right we have Tommy is six years old, followed by Tommy Says graph, graph. As you can see are instance methods work and they can access both attributes that belong to the current object as well as new data we pass in the form of a method parameter. Let's create one more instance method that will be called every time the dog celebrates birthday. We'll move back into our classes here and we'll call this new method birthday. Now in the method body, I'll type in self age plus one, which will increase the dog's age attribute by one. In other words, every time this method is called, the dogs internal age attribute will increase by one. So now at the very bottom, I can say Tommy dot birthday and then can print oh, Tommy DOD description again. Notice how we didn't have to put a birthday method call inside the print function. This is because the birthday function doesn't actually return any data that we can print. It just changes the internal age attributes from our dog. So now if I run the code, we can see the Tommy is six graph graph and now Tommy is seven years old. At this point, we're almost at the end of our OOP tutorial, but I have to warn you, the last part can be a little bit difficult to grasp if you don't already have at least a basic understanding of everything we've covered so far. I would strongly suggest practicing these concepts by creating your own Python classes and then instantiating them. Remember, a class can be practically any noun. So look around and see if you can model something in your code and ask yourself some questions about when you design your class, what attributes as the object have to all objects have the same value for that attribute by default? Or are they all knew from the time they are created? What behaviours does the object actually exhibit? And how might these behaviors changed the attribute of the object? If you're really up for a challenge, create a class where one of its attributes is actually another custom type you define, just as we did with the tab class storing a page object. If you can do that, then you should definitely have a solid grasp on this material and you'll be all set to move on. And on the other hand, if you're still struggling with this, don't feel bad at all. Like I mentioned at the very beginning, this is a very difficult concept for lots of new programmers to grasp, including myself. It requires you to think about your software in a way that's probably completely foreign to you. And this is not something that's easy to master. If you're confused about something or you just forgot it, it's a good idea to re-watch earlier parts of the section. Give yourself lots of time to practice. And once you feel that you've gotten a grasp on the concept, come back and learn about the last concept called inheritance. Thanks for watching. 116. Introduction to OOP Inheritance: Welcome back to our series on object-oriented programming in Python. In the last video, we learned about instance methods which are used to represent the behaviors are objects have the whole idea of classes creating objects, little bundles of associated data and actions is a really powerful thing. But it's also susceptible to bad coding practice called dry. Dry stands for don't repeat yourself. This says that when we write code, we should avoid copying and pasting the same chunks of code whenever possible. If you're running non-trivial Python programming and you find yourself copying and pasting attributes and instant methods between a lot of different classes. That means it is probably time to rethink how you're designing your software. Take a look at this example. Let's say we're writing a program that's supposed to construct, maintain lots of different people. As you can probably guess, each person is going to be an object. But here's the cabin. We can have general people objects, and then we can have special type of persons called a baby. A baby can do everything a regular person could do, except it might do things a little bit differently like talking. In addition, it also might have some unique behaviors that are general person doesn't have, such as the ability to take a nap whenever it wants. Being a baby sounds great. As you might have guessed, we're going to need two different classes here, one for the person and then one for the baby. You'll notice here that both of these classes are the exact same, but the baby class now has one more behavior called nap. Now we could design our software this way and it would work fine. But remember, a baby has to be able to do everything a more general person can do, albeit a little differently sometimes. This means that our baby class is going to have the exact same instance methods that a person class has in most of those methods are going to look the exact same. But now what happens if we want to make a change to the Person class? If we change the action from something like jumping to spinning, then we also have to change the baby's action methods as well. And if we add another class like adult or teenager, then we'd also have to maintain those two. Copying code might make things easier in the moment, but it can make our software really difficult to maintain later on, especially as it grows. To solve this problem. Let's take a step back and think about the relationships that exist between these two classes. I think that you would agree that a baby is a person, right? That's why it shares the same behaviors as the Person class. So what if there were a way that we can make the baby class automatically inherit every attribute and instance method from the person, but then modify them a little bit to fit the baby class needs. Then we could even add our own behavior like nap that would be exclusive to the baby class. This right here is called object inheritance. And if used right, it makes managing a lot of similar classes a lot easier. Inheritance allows us to make one class, the child class, or the derived class, or of another class called the parent class or the base class. In Python, the child class automatically inherits every attribute and instance method from the parent class. But we can also redefine certain attributes or methods. So if we want our baby object to speak differently than a person object would. We can do that? If we want our baby object to have the ability to nap, we can do that too. And if we need to make our person spin instead of jump, we can modify the person class and the baby class that will automatically pick up with those changes. There's no need to edit code in more than one place. To understand inheritance, Take a look at this chart on the right. And at the very top of the chart is object. In many languages, Python included object is the parent class of all classes in the language. This includes building classes like the INT or the STR, as well as any custom classes that we create. In this diagram, you can see that baby inherits from Person, which in turn inherits from object. As we'll see later on, Python sees any baby object we create as also a person and an object. 117. Inheritance Example: Welcome back to our series on object-oriented programming in Python. In the last video, we learned about the idea of inheritance, which allows us to define a child class that automatically inherited attributes and methods from its parent class. Now let's see how inheritance works in action. So I'm hearing by Python editor and the first thing we're going to do is define a new class called Person. I'll see the description equals general person, which will be our only class attribute. Now we'll create our initializer method and it'll give it parameters of name and age. As usual, we'll set the attributes equal to these parameters. Now I wanted to find a few behaviors that every person will have. I'll create a new instance method called Speak, and the only parameter being self. And I'll make this printout of my name is blank and I am blank years old. Then to fill these gaps, I'll use the format function and I'll pass it in the self.name. Self.age is arguments. Next, I want our person to be able to eat whatever food we give them. So I'll say here, def, eat self food, semicolon, and then I'll print out a blank, each blank. And to fill in those blanks will pass in self name as well as our self food parameter. Lastly, let's give our person the ability to perform an action. So I'll create one last instance method called action. And when that's called, all say blank jumps and I'll pass in self named to fill the blank. Alright, so now that we've got our general Person class, let's create a subclass called baby. To do this, I'll type in baby just like before, but then I'll put in some parentheses. Inside of these parentheses will need to clarify what the parent class of baby will be. So we'll type in person. And now technically if I were to write paths in the class body, then our baby will be usable, but they'll do the exact same thing that person would. So we want to change that. First, I'll redefine our description class attribute. I'll set it to equal something to like baby, and that should work. This redefining here is called overriding because any baby object we create will use a specific description instead with a description inherited automatically from the person class. To do this, I'll type def speak with self as the parameter. And then I'll say print Mama, which is just some baby givers than I came up with. This way where we call speak method on a baby. It will say this g gibberish instead of whatever the parent class would have said. Lastly, I want to give these babies and exclusive functionality. Let's give the baby the ability to nap whenever it wants. All say def, nap with a perimeter of self. And then I'll write print blank, takes a nap. And in place of the blank, I'll say self name. Now, any specific baby object that we create will have the ability to nap, but a more general personnel object will not. All we have to do is to instantiate these classes and put them to work. I'll create a new person object called person, and he will have a name of John in an age of 30. Then I want to call all of this instance methods of the person. So I'll type person dot speak in person dot eat. And we'll give him fish. And finally Person.all action to see him jump. Now let's create a baby object called Baby. I need to supply a name and an age to the initializer for the baby. But if you look, baby doesn't actually have an initializer. That's because it automatically inherited from the person class. Remember, this baby is also considered a person and as such, it needs to fill out the instant attributes of the person as well. So we'll give this baby a name of Van ISIL and an age of one. Then we're going to call the same instance methods of our baby object. I'll print out both of the descriptions of our person and the description of the baby. Let's run the code. This whole exercise shows us how we can define a child class or a derived class that automatically inherits everything from the parent class or the base class. We can override attributes and methods like description and speak. And we can even extend our child class to add new functionality like we did with the NAT method. Just to make this even clearer, I'm going to move to a new line and type person dot. If you remember, the Don is like the access modifier which allows us to access attributes and call methods of an object. Since this object is a person, notice how intellisense it doesn't see the NAT method. That's because it's specific to the child class and as such, only child objects have it. However, if I delete this and I changed to baby and I hit dot, you can see that we have access to everything defined in the Person class as well as the specific Net Method. But now what if we're told that we need to make a change to the action method, maybe now we want both people to spin around instead of jumping, rather than having to modify code in several different classes. All we have to do now is to change the word jumps to the word spins in our person class. Now if we run this code, you'll notice that both John and bands are spinning instead of jumping. And we didn't have to make a single modification to the baby class. This is one of the reasons why inheritance is so powerful. Remember how earlier I said that behind the scenes, Python sees every object as the type object. Well, now that we have our classes coded, I can show you that that's true. To prove that a baby is a person, I'll print out the result of this special function called is instance. This function will tell us the specific object is a specific type. This function takes two arguments, so I will pass it in the baby object for the first and want to check if the baby object is an instance of person. If I run the code here, you'll see that on the right side we see true. And that's because a baby is a person, the baby object of the type baby, but also the type of person because it inherits everything from the person class. Now let's see if our baby object is of type object. I'll change the word person here to lowercase object. And if we run this code, we will see that our baby is in fact an object. Because baby is a person and person inherits from object. Therefore, baby inherits from object to like I mentioned before, every class in Python inherits from object. And we actually don't have to write that inside the class declaration. The reason for the object class even existing is beyond the scope of this tutorial. But for now, just know that our baby objects are technically seen as a baby, a person, and an object. And that is somewhat of a brief introduction to inheritance. We didn't cover everything, but this gives you a general list of how inheritance works. As you can see, inheritance can be extremely beneficial, but if it's not used correctly, it can be more of a headache than anything else. Inheritance is one of the fundamental pillars of object-oriented programming, but it's not the only one. And there's even more to inheritance that we didn't cover here. But this tutorial is focused more on the fundamental principles of OOP rather than any specific features of inheritance, polymorphism, encapsulation. O p is a huge topic and that's hard to master. But hopefully now you have at least a basic appreciation for how large software is designed with classes and objects. In my opinion, programming becomes a lot more fun with the understanding of OOP. Because you can move beyond writing trivial programs like a number guessing game, and move on to writing real software using frameworks and libraries like Django and map plot lib, happy coding. 118. Scripts, Modules, Packages, and Libraries 2022: Python uses a lot of fancy terminology that you may not be familiar with if you're new to programming or if you come in from a different language. Before python, my background was primarily in c pounds and Microsoft's dot NET Framework. I remember trying to learn Python, but being kind of confused by all these buzzwords. My goal in this lesson is to clear some of this up so that it's not as confusing for you later on. Python script is best defined as a Python file that contains commands and logical order. For this to be considered a script, the program needs to do something, really, anything when it's run through the Python interpreter. To better understand this, take a look at these two programs. Both programs contain a function that will return the sum of two values. However, only the program or the right will actually call that function and print its result. The file on the right is intended to be run directly. So we can see that it's a Python script. On the other hand, the program on the left doesn't look like it's actually meant to do anything. Running that file will not produce any sort of output since the function is never been called, It's not intended to be run directly. The file on the left is better classified as a module. That's because we can import it onto other files to utilize its classes, functions, variables, and other members. It's defined. I'm going to change the program on the right so that instead of defining the add parentheses function, we import it from module on the left. This has the effect of making the addition function on the left accessible to the script on the right. So long story short scripts are intended to be run directly, whereas modules are meant to be imported. Script often contains statements outside of the scope of any class or function. Whereas modules to find classes, functions, variables, and other members for use in scripts that important. The word scripts and modules are often used interchangeably. So be aware that you might see other people use them in ways that don't strictly follow these definitions. Packages are a collection of related modules. A package can be an individual Python module, but they're most often a collection of multiple related modules that come bundled together. This here is the date util package which allows for performing advanced data-related operations. It's bundled in a folder called date util. Inside there are a bunch of individual modules, as well as folders containing other modules which can be imported into your Python scripts. These are modules because they don't do anything interesting on their own. When you import one into your own script, nothing really happens. You have to use something defined within the modules, such as a class function or a variable. This special Intel file tells Python that this is a package potentially containing more modules nested within subfolders. We can't talk about libraries without mentioning Python Standard Library. The Python Standard Library is a large collection of modules and packages that come bundled within your installment of Python. That means that you don't have to download them from anywhere. You can just import them into your scripts and start using them right away. Date util is an example of a standard library package, but there are also others like e-mail and JSON. The key takeaway here is that a lot of this to some extent is subjective. Scripts are runnable Python programs that do something when executed. Modules or Python files that are intended to be imported into scripts and other modules so that they're defined members like classes and functions can be used. Packages are a collection of related modules that aim to achieve a common goal. Finally, the Python standard library is a collection of packages and modules that can be used to access built-in functionality. In an ideal world, you'd import any necessary modules into Python scripts without any issues. Unfortunately, that's often not the case. In the next video, you'll get an introduction to modules, and I'll show you how to write a module. Thanks for watching. 119. Writing a Module: In this video, you'll get an introduction to modules by writing a short module of your own. There are three different types of modules in Python. Module can be written in python itself, but modules can also be written in C and then loaded dynamically at runtime. And then there's also built-in modules that are intrinsically contained in the interpreter itself. And you may have already imported a few of them in the past, such as math or importing random dateline. For this video, I'll have you try the first option, writing a simple module in Python itself. Let me have you try out this and an editor. First of all, let's make a new file and name it mod dot PY. Mod dot PY is a standard Python file. Inside of it you are going to create a string objects with small List and define a function. Let's just call it print_i. Pretty takes an argument called ARG and print the print using an F string. There was an argument statement that the F equals the arc that you're entering in, calling the variable in the F shrink. Then make a class. I'll have you call it capital classy. There's your classy class. And right now that class doesn't really do anything. It just passes, save the file and run it. What you can do then from the Python shell is type in import. Since you were in the same directory where you created the file, you can say import mode. Okay, what did this do? By importing mod? You've imported all the objects that were part of that code. You could say, OK, well, what is it? Mod dot a will mob don a. Is that lyse created earlier for mod dot S. Well, that's a string. If you wanted to use printing, you could say, okay, model.predict is now available also. The argument is What is up in print_i prints out that the ARG equals two what is up? And you can make a new object called x using MOD dot classy. What is x? Well, x is a classy object from the module mod. Cool. So now you have access to all these different objects by importing that module, allowing for a lot of reusability of code. Now that you've been importing something, in the next video, you'll focus on where the interpreter searches for those files that you're importing. 120. The Module Search Path: In this video, you're going to explore the module search path. So where you can import a module from. When the interpreter executes the import statement, it searches for that file. In your example here, it was math.pi. It's going to search for that and holistic directories, the possibilities or the current directory, meaning where the import script was run from. And it also searches in the Python path environment variable, which has a list of directories. When you install Python, there's a set of directories that are configured as part of Python's installment. Also, when you import from building modules, that's where the code is coming from. And there is a way to see all of those, to see this list of directories. Let me show you that in code inside the Python 39 directory, there's a math.pi file. If you saved your math.pi file in that directory, you can type import in mod. The math.pi file is right there. Great. So now Ahmad don a is available, MA dot S is available. Ok. If you wanted to see all those places that can be imported from. Currently, there is a tool called the SYN module that is part of the library that you can import. And that can show you the current Python path and the directories that were set up in Python that was installed, import SY S, which is a module that includes system-specific parameters and functions that you can access. And one of those is syst dot path. So syst dot path will show you a list. Oops, I forgot the dot. Hopefully you can see that here with the square brackets that these are all the objects your interpreter is going to search for when you type the word import and then search for a particular module that you're importing. This is the default directory that you're in, current directory. So it would search right there. Then from there, it goes into a version of Python that you installed. I'm going to exit out of here. So those are all the locations that you could save a file, either in the current directory or in any of these other directories that you see after running syst dot path, what if you want to add locations for it to be able to import? That is a possibility to, to prove this point. I am going to make this not be the current directory. Now if you were to type import and then mod, it's going to say that schedule is not found, it's currently in that directory or in any of the other locations that if we import sys and use this.tab, not in any of these locations that import is searching within. So where should you be putting your module file to make sure that your script that you're using the import command from confined it. You have a few choices. You could put it in the same directory. The input script is written in, which is considered a usually the current directory. You can modify the Python path environment variable, or you could put it in one of the directories already in that Python path. You can also put it in one of the directories that are configured as part of your Python installment. Now, there's one other solution that can be done at runtime. In that case, you could actually modify the SIS path list. To do that, you're going to use an append a statement, just like you would depend to any other list. So in this particular case, from the set path, you can append. And as an argument, you're going to enter in a raw string. So you start with r and the single quote. Now you need the directory path which you can simply type in. Closing my quotation marks there, this is a name error. Can you guess why? Is because they didn't define the sys package. So let's type import dot says rerun this code line. So what did that do? Well, if you look at this syst dot path now at the very end of it, it has upended this particular location, this directory into the path. If you were to type import mod, it can now import it in. Great. One thing you need to remember though, if you were to append those locations, are those directories for you to import them in that only lasts for this particular session. So if you were to exit and start again to try to import mod, it's not available because if you import sys and use his path again, you can see it's no longer part of that list. So that would need to be part of your inputs script. Then you would add the SIS path append to the directory. In the next video, you're going to take a deeper dive into that import statement. 121. The import Statement: In this video, you will take a deep dive into the import statement. Swift forms. Can the import statement take in its simplest form? It is like what you've already used in the previous video, import and then the module's name. In that case, the module contents are not directly accessible to the color, so you need to use dot notation. The module creates a separate namespace. Let me show you what that looks like. Now you've practiced this already, but you can type import mod and then would import your module. Now the trick to that is the objects that you've already imported are not in the same local namespace, they are not in the local symbol table. So if you were to type in the letter a and then object is not available, S is not available. Print_i, any of those objects are not available. You would need to use a Don notation beginning with the name of the module first after adding the DOD. Now I can access a or you can access s or even print_i. As a note, you can import multiple modules at a time, simply including a comma between the names of each. As an alternative, individual objects from the module can be imported like this from and then the module's name import from, and then the objects names import. And then you'd use the objects names where you can use several with commas in between them. The individual objects are directly accessible to color, then they are imported directly into the color symbol table, meaning you don't have to separate namespace At that point. Let me show you what that looks like. So now those have been imported from the local symbol table. S is actually available and so is printing in the local namespace not required you to use the dot notation. There is a need to be careful though, if you were to create an object a, and let's say a has a few strings in a list. There's a. But if you were to import a from your node module, what happens to the existing local a? Well, it has been overwritten, and so this creates a collision, if you will, overwriting the existing object. So there's a need to be careful with the namespace here in simple generic names. Now it's also possible to import everything from a module at once. In that case, it will be from and then the module's name import, and then an asterisk sign. You've probably seen this before in a script or two, that this place is all the names of the objects into the local symbol table. The only thing that won't be imported as anything that begins with an underscore, keeping it private to the module itself. This isn't necessarily recommended unless you know all of the names that are not going to conflict or overwrite any existing names, you can run into some trouble. This will take all the named objects from the module into the local SymbolTable. So now classes there. The string object S. I'm going to exit again. You can also have individual objects and then have them named in alternative name that would look like this from module import, whatever the object's name is. And then as what you would like the object to be renamed, as you can do this multiple times, which makes it possible to place the names directly into the local SymbolTable. Therefore, it would avoid conflicts with existing names. You still need to be careful whatever you choose as alternative names. In this example, you still have local variables that are named a and another one named S, which is a string. Here is the two objects a and as. So if you were to import a and S from your module, it would write over these two. And what you can do is say from a mod import asking give it a new name, maybe name it as just string. And a is a list. So again, you can use this comma to do multiple imports at once. So now a is still there and S is still there. But string is where you import it. And a list is also what you import it from the module. Another possibility is to import the entire module under an alternative name. And in this case, you import module is what you'd like the other name to be. A common one would be to import pandas as pd, therefore, not having to spell it all the way out. If a module has a really long name, some people like to shorten it. You would say import mod a, mod S, and then you'd give it a different name. So name it, say my module. So now my module is here and it has a, an ass. Modules can also be imported from within a function. Let me show you what that looks like. In this last example, create a function and I'll have you name it importer. Inside the function, you could say from MOD important print_i and then use printing inside of it. So right now, MOD isn't here and print_i isn't available. But if you run importer and call that function, it imported printing from the module mod and then call it with the argument hello everyone. Next up, you'll check out the DIR function. 122. The dir() Function: This video is about the DIR function. After learning the various ways that you could import a module or the contents of your module and how that affects calling those objects. You might be interested in learning how to view the Define Names that are inside of a namespace. And that's where the DIR or the directory function comes in. It's a built-in function and it returns a list of defined names in a namespace. If you don't give it any arguments, it produces an alphabetically sorted list of all the names that are currently in the local symbol table. Let's take a look at that. When running DIR just by itself, you'll see these objects. If you were to create a new object, Make a list named wins. And if you were to run the DIR, now you'll see when there's an objects that is also available as a local symbol table. If you were to create a class name team, it's a very simple class that just passes. And you were to create the object, say, X, that is part of class team. Now if you type DIR, you can see here team, and then you can see the other objects, winds and x. So these are the objects that are now in the local symbol table. Their names are, let's import the module MOD and type in DIR. The individual objects are part of this module mod are not a part of the local symbol table. They would have to be accessed by typing mod Dante or mon dot S using notation syntax or mod dot printing. But if you were to import individual teams, would you learn how to do last time import a team you can't in import, error message appears. Now if you type DIR team, that class is there and a, that object is there, you can make an object Y of the team class. It's available. And then other ways that you could import is to import but with a different name. So you could import S and give it the name string. So now DIR would bring up string is now in that local table also, S is not, it's not defined, but string is. So up to now, you've been using the built-in function DIR without any argument. What if you do give it an argument? Well, one of the ways that you can use it is giving it the name of the inside module as an argument. Then in that case, the DIR function lists all the Define Names inside that module. If you were to import mod by itself, you can see it here, but you can't see the names of the objects that were imported when you imported mod. Those are in its own symbol table. To see those, you type DIR open and close parentheses. And then as an argument, put it in mod. It has its own team class and sign it the string function, a function print_i, and the string S along with its own name. I'll show you a little bit more about name in the next video. And the last we discussed as far as importing was using a wildcard for mod import asterix, What does that put in the directory? Well, it puts all the objects and so there's Team mod. The module is still already in there from when you import it, it before. But print_i and S and a are all now in the local symbol table. In the next video, you'll learn about executing a module as a script. 123. Executing a Module: In this video, you'll learn about executing a module as a script. Is a module also a Python script? Well, yeah, any dot py file that contains a module is essentially also a Python script. Let me have you take a look at that. If we were to open up the code for mod DOD PY, as you can see, it's very simple. What if you were to execute modified pi is a script. Is it possible for sure as long as you're in the same directory, but it's only to finding objects and then it doesn't really do anything with them. Now if you could modify it, you could print as imprint a run print_i, even define X as a classy object and then print out x. Okay? So I'm receiving, it should be a little bit more interesting. Okay, run it. So it printed the string, printed out the list, showed the argument for print_i. And then it shows that when this is running, the name of the module is main and classy object. What does that look like when you import it? Now, start the Python Shell. If you were to run import MOND, what's going to happen? It's going to run all that code. One note you might notice here, it used to save that main. Now it says mod and it outputs it. Now this is probably not what you want. You probably want when you run model and pi for to show the output. But when you import mod, you may not want this output to happen. You may want to be able to show output for testing purposes, but you may not want to have an everytime you import it. It would be much better if the output was optional. So there's something to help out. Is there something you can do if you don't want that module to generate any LPA when you're simply importing it. There was a tool that can help with this. It uses what's called a variable. Do under variables are the variables that will double underscores before their names. In this case, the gender variable is actually a name. Name will automatically be set to the name of the module when it's imported. That's different from when a Python script is run as a standalone script. In that circumstance, name is set to the string of main. So how can you use this? I'm going to exit here. Go back to my dot pi. And I'm going to change this code a little bit just before all of this starts. Create an if statement. In the if statement, you're going to use that variable that under variable of name. So if that name equals domain, which is what happened when you execute the script by itself not importing. Then go ahead and do all of this activity. I'll have you tab all this information over. So only if the name is main. So this time if you were to run math.pi and you can see that running it by itself. The name is main. And if you were to import mod, it doesn't, which is pretty neat. So again, we're going back to DIR and here is mod imported, right? But what is the current name? Well, what's running here as the main session? If you were to say, what is the mod name? Well, mod name is MOD. However, if a file run as a standalone script, name is going to be set to the string as Maine. And that's how you can use that test. Pretty neat. One reason that you may want to run the module is a standalone script is to test the contents of it. So then in this next example is all about make a new file. Call it Fact dot py. And inside fact DOD pi, you're going to define a pretty simple function that is a factorial and just call it fact again. You can set up the same conditional statement. If the current name is equal to the string main, then you know it's being executed as a standalone script. You're importing another module, the CIS or system module, and you're going to use a tool called ARG v, then allows you to use command line arguments. To be able to do some testing. You're going to set up another if statement. And here's it's looking for it's optional argument that you can add when you execute the code as a script. Then it's going to print the output of that fact function after converting this argument into an integer from a string. Save that file and to test out if you can import fact, go ahead and start a new shell session. So factors available and it takes an argument of end. Let's say what's the factorial of five? So that shows the fact works as a module. In the next video, you'll explore reloading a module. 124. Reloading a Module: In this video, I'll show you about reloading a module up to now, you can simply importing a module once, even if you were to try, a module is only loaded once per interpreter session. And that's going to work fine for functions in class definitions and importing all those objects initially. But sometimes modules can contain executable statements as well. Usually the executable statements are only for initialization, and it makes sense that these statements will only be executed the first time the module is imported. That usually okay, let me have you take a look at that. Go ahead and reopen math.pi. And inside of it, I'm going to have you go ahead and clear out this if name equals main. Just keep a simple print statement for printing AI out. In fact, modifying a little bit and use an F String. And that can show that every time this module is imported, it would print this out, right? So save this extra line. Okay, up here in the terminal. What happened if I import mod? Well, you can see it here. Initially as it imported mod, it went ahead and did the print statement inside there using the F strength. And inside here a mod Dante is available. Now what if you were to import mod again inside the same session? Nothing happens is montane stilled here? Yeah, in fact, all the objects are available. So why would it not rerun this code? Will, that's the thing. It only is going to import it once and it doesn't need to re-import it again. So it's sort of an efficiency thing. Well, what if you needed to reload this? Is it possible to reload a module? If you really needed to? There's two choices here. For one, you can restart the interpreter and you've practiced that multiple times. Or there is a module that you can import called lib, and that includes a function called reload. Let me show you what that looks like. So sometimes you may want to reload this in, especially if you've maybe changed the code and you don't want to restart the interpreter. Like maybe you've changed this a little bit and you save, and now you want to import mod. Those objects are still there and importing mod didn't print out anything. Again, if you're making changes to your module, you would need to use another tool. And that tool is something that can be imported from import lib. And inside of import libs, a function called Reload. Now that you've imported it, reload is going to reload the module and then return it again. So in this case the module is called mod two important lib dot reload Maud would actually reloaded in here. It's actually been reloaded from the source here. So now you have a handy tool that you're making changes to your module. You can reload them using import live and the functionary load. In the next video, we'll start to explore Python packages. Thanks for watching. 125. How to Install a Package in Python using PIP: Hey everyone, back in our Python course again, Python has a standard library of packages, but many developers have written their packages to extend Python's capabilities even further. These are third party packages. You can install them with the help of Python's pipe tool. This tool securely downloads and installs Python packages on your computer from HTTPS semicolon, front slash front slash PY PI.org, the Python Software Foundation website. Imagine the Python package index is some sort of free app for Python modules. Let's fire up the webpage. These are the latest updates from the Python packages or modules, if you prefer. Click on browse projects from this link and you can see thousands of packages ready to install them. Let's get back to the PIP tool. The executable file for the PIP tool is called pip on Windows and PIP3 on OS X and Linux. On Windows, you can find Pip in the following directory. While Pip comes automatically installed with Python 3.9 and on Windows as well as OSX, you must install it separately online x. Now I'll show you how to install packages from Python using Pip. I'll demonstrate how to uninstall a package that is no longer needed. Now if you're using Windows, you'll be able to install Python package by opening Windows command prompt and then typing in this command. Let's see the steps one by 1. First type command prompt in the window search box. Right-click on the Windows command prompt and then select Run as the administrator. By running the command prompt as an administrator, you will avoid any permission issues in the command prompt type CD backslash, as this command will ensure your starting point has only drive name. Press enter. Now you'll see you drive name of c, locate your Python path. The scripts folder can be found within the Python application folder where you originally installed Python. In my case, if I open Windows Explorer, the Python path is this one. So if I right-click, I can copy this address as text. Now in the command prompt type cd followed by your Python path, I can paste the address would control plus V, press enter. Now type that pip install command to install your Python package. Since in our case we would like to install the pandas package. Then type the following command into the command prompt. Finally press Enter and you'll notice that the package here, it's Panda, will be installed. You can quickly check at the Pankaj was successfully installed in Python by opening the Python idle and then running the command import pandas. If no errors appear after you press F5 to run the Import command, then the package was successfully installed, mission accomplished to uninstall a package using Pip, simply type the following commands into the Command Prompt. Do not forget to set Python path before you type in this command. Finally type y and then press Enter in order to proceed with the removal of the package. Thanks for watching. 126. Python Packages: Up to now you've only had a single module to import. But what happens is you start to build a much larger application will, that's where Python packages can come in when you're trying to keep track of a growing number of modules. Creating a package is typically the solution. Packages allow for a hierarchical structure a of the Module namespace, again using dot notation. So here's an example package structure and you'll get to play with this in a moment. At the top level, you again have a directory, And let's say that directory is named pk GY package. And inside of it, it includes mod E1 dot pi, and then it has a second module, mod two dot py. So now both of these models are inside the directory hierarchy of the package. Well, how do you import them and work with these modules? Let me have you practice inside Python directory. I already created a new directory, pk G. So here's the directory pk G and incentive in I created two modules, mode one and mode two. It open these two files. So mode one is going to have a function called load data. The load data when called, is going to print out a line of text about the module. It also has a class. This class is going to be the customer class. Mod two is going to have a function named Clean Data module, have a class also. This class will be the location class. Great. So from the shown windows, Why are the ways that you would import packages or modules from packages? Well, you can use the dot notation. In fact, you could import both of them at once. And you could create an object and x is going to be a location marking the spot, if you will. Great. So x is the location object from mod two from the package PKA G. Nice. So that's one way is just to import them. Another way would be to import individual items. So now inside of here, load data is in the local SymbolTable and is available and you can see it running. So again, you could import from the package individual items from the individual modules using dot notation. Or you could use the alternative name technique. Let's say you want to import that classification. But instead of calling a location, you want to call it primary. You could now create a new object using that class. So now y is a local object. Again, it's using the name that you gave it a primary. Another way that you have learned to import before was using the from statement. You can't directly import mode one, as you can see from this error message. But from P KG, you could import mod one. So instead of the denotation of having peak AGE first, you actually would then just use mod one. And similarly, if you wanted to, you can load from the EKG import bond T2 and then it would give it a different name. Let's say foo. Foo has cleaned data and if you wanted to, you could call that function. It's good to practice all these techniques again. Thanks for watching. 127. Create Graphics and Shapes Using Python’s Turtle Module: As we already learned, a module in Python provides useful code to be used by another program. Python has a special module called Turtle that we can use to learn how computers draw pictures on a screen. The turtle module as a way of programming vector graphics, drawing with simple lines, dots, and curves. First, to use the turtle, we will import the turtle module, used the code. Now that we have imported the turtle module, we need to create a canvas, a blank space to draw on like an artist canvas. To do so we call the pen from the turtle module, which automatically creates a canvas. Enter this into the Python shell. You should see a blank box or the canvas with an arrow in the center. The arrow in the middle of the screen is the turtle. Of course it isn't very Turtle Lake. You send instructions to the turtle using functions available on the variable that we've just created, similar to using the pen function in the Turtle module. For example, the forward instruction tells the turtle to move forward, tell the turtle to advance 50 pixels, enter the following command. Now we'll tell the turtle to turn 90 degrees with the following command. The turtle left 90 command points the arrow up. Now we'll draw a square and the following code to the lines you've already entered. To erase the canvas, canvas and puts the turtle back at its starting position. You can also use clear, which just clears the screen and leaves the turtle where it is. We can also turn our turtle right or move it backwards. We can use up to lift the pen off the page. In other words, to tell the turtle to start drying and down to start drawing. These functions are written in the same way as the others we've used. Let's try another drawing using some of these commands. This time we'll have the turtle draw two lines. First we move the turtle backwards 100 pixels with T backward 100, and then use t up to pick up the pen and stop drawing. Then with command t right 90, we turn the turtle right 90 degrees to point down toward the bottom of the screen. With t forward 20, we move forward 20 pixels. Nothing is drawn because of the use of up command on the third line. We turn the turtle left 90 degrees to phase right with T left 90. And then with the Down command, we tell the turtle to put the pen back down and start trying again. Finally, we draw a line forward parallel to the first line we drew with t forward 100, and we've drawn the two parallel lines. Also, you could use a for loop to make a square like this. Now with a few simple changes to our loop, we can create nice using the similar code, we can create various shaped from a basic square to a spiral star. As you can see by using for loops, we've made it much simpler to draw these shapes. Now let's try to draw a filled square, but first, clean the canvas to dry filled square. First, we need to define a square function that draws a square. Begin filling. Test your function by calling it with size 50 and then n filling. I hope you learn how to use the turtle module to draw a few basic geometric shapes using loops to control what the turtle does on the screen. If you have any questions, please let me know. By 128. Python's open, read from, and write to a file: Hi and welcome to this video tutorial series on working with files and Python. Throughout this section, you're going to learn pretty much anything you could ever want to know about a basic file operations in Python. And my basic file operations, I mean creating, deleting files and directories, moving them around, copying them, renaming them, working with archives, working with temporary files, traversing directory trees and getting file properties. This list goes on and on, but pretty much everything here I will cover and even some things that are not quite on this list. If you're looking to follow along in your own terminal, I would recommend that you take a look at the resources files that I've included because that will contain all of these sample directories that I'll be going through in this section organized by less than, it could be really convenient for you. So generally on each lesson I will introduce the lesson, introduced some of the functions that I'll be using. And then I'll show you a sample directory and you should look at it at your own terminal so that you can follow along. All right, let's jump in. In this lesson, I'm going to cover Python's with openness pattern, otherwise known as context manager pattern, which I think is the most important basic pattern for working with files and Python because it allows you to create and read from existing files in your file system. In order to understand the width opened as pattern, you first need to understand the open function, which is really quite simple. It takes filename and a mode, and it opens the given filename from the current directory unless otherwise specified in the mode that you pass in. And then once that file is open, that's when you can do operations in that file or you can pass it to read from it. So the basic file modes, and there are many more. But these are the three that I'll show you to start with our write mode w, which wipes the existing file content creating file that doesn't exist and allows you to write the file. There's red mode, r mode, which gives you a read only access to the files contents. And we'll throw an error if the file doesn't exist already. And then there's the append mode a, which writes to the end of the file so it does not wipe the existing file content. So zones are the three basic file modes at all explored throughout the rest of this lesson. So let's head over to the Python shell. So what I can do is say something like test.txt as a filename. And then I'll open it in write mode so that I can write to it. And so then it's created because test.txt does not yet exist. And then I need to say is so with open as and then I give this a name. Normally I find it convenient to say something like write underscore file so that I remember what exactly I am writing two in this case. Then I can say something like right file dot right. Or I can just write whatever text I want to write. I can say something like hello, this is a file. Press Enter and write function returns the number of characters written here. Let's look at Pythons main directory. Can you see this file? It's here, test.txt. You can check that file by saying with open test.txt in read mode as read file. And then I can just say print, readFile dot read, and don't read function just returns all of the contents of that file. So as you can see, this is really existing files and it does have the content. Hello, I'm a file. There's one further mode that I showed you. So I'll show you now test.txt and append mode is right file. And then I can say right file, don't raid. And I'll put a new line here so that there's a new line in the file. And I'll say, here's some more text. And then again, I'll do the exact same thing I just did here. And as you can see, I've appended to it. But if I were to open it again in write mode and then write to it, all the texts has been deleted. Let's check the file from Python's main directory. And as you can see that this is in fact true because in write mode actually just rights over everything that exists in the file already, whereas the pen mode just appends to the existing text. So that's how you can open and read from and write to a file in a couple of different ways. One last thing that I want to cover in this lesson is that it's best practice to always close the file after you open it, typing right dot close. Otherwise will be leaving this FileResource open with your operating system will interpret as needing to have that file open and it will kind of snarl up your operating system resources. So that's how you can use the width open as a pattern to create and read from and write to files. In the next lesson, I'll cover how to get the directory listing, how to look at all of the things that are in your directory that have been created. 129. Getting a Directory Listing and File Attributes: In this lesson, I'm going to cover how to get a directory listing. Simply put a list of all the things that exist in your current directory or any directory you might choose. And this is really important because pretty much any task that you want to do in Python or other programming language where you're working with files, you're going to have to do something in there where you want to look through all the files of your current directory and do something with them. Here are some basic directory listing functions throughout this series, I'm often going to show you a couple of different ways of doing the task. Then I'm going to show you how to do. So with all that said, the first function here is the OS dot list DIR, which takes in a directory name and then returns a list of files and subdirectories in that directory as a string. The slightly more sophisticated alternative is OS dot scan DIR, which returns an iterator instead of a list. That iterator is not of strings, but rather a file objects that have some properties to them, which make them a little bit easier to work with when you actually want to treat them as files. And then the path live module has a very similar paradigm to scan DIR, except it works on a path object. And I'll show you how to initialize a path object and work with it over in the Python Challenge is the second. My Python directory has a couple of subdirectories and several files in it. And each sub-directory has a couple of different files to. Okay, let's get into the code a little bit here. The first thing to do is to get some imports going, import OS. And then I'm also going to say path lib import path, just so I have all my imports up here in one place. So the first thing that you can do if you wanna get a directory listing is you could just say OS dot list DIR. And then as you can see from my handy shell, it takes in an optional path parameter. If you don't pass the path, it will just use the current directory. It as you can see if you remember from my Python directory, it has all the files and folders. But as you can see here, all of these are just bare strings and so is the string list. So this isn't super flexible. If you actually want to get information about this, you can say something like maybe OS path is file and then you could call that on a file or whatever. But you have to do all the cirriculum Kunshan to figure out some information about this file. Can you guess why it's false? It's because they didn't type the dot py extension. Let's try that again. This isn't the case with something like scan DIR. You can say something like for name and OS dont scan DIR. And that will also take an optional path parameter. You can say If named Don is File. And I'm not sure exactly why this has no underscore and this does have an underscore. I wish I could tell you more about why that is, but who knows? So that you can just get attributed directly from the object. Because as you can see. Objects are DIR entries rather than just plain strings. So the DLR entries have information within them, whereas the strings, you have to do a little bit more work as the programmer to learn that the necessary commands to actually get this information about these things. So that's something to notice here, is that the OS dot scan DIR is a little bit more object-oriented, whereas OS dot list DIR works a little bit more like a traditional Linux Filesystem. We're pretty much everything is a string and you just have to do the work on your own to figure out the information about it. So path lived takes a similar psychology, except you have to create the path as an explicit object. So DIR path equals path. And then I'll just pass in the current directory dot slash. And then you can do the exactly the same stuff that you can do with OS dot scan DIR. It's just that it'll call ITER DIR directly on the path. Then it's exactly the same thing here. As you can see, this name has a little bit of a different printing function. But this name is still an object where it has a little bit more information than just a bare string. So that's relatively useful. And all these things that you can use on any path that you like. It's not just on the current directory. So that's three different ways to get a directory listing the OS module and the lib path module. They all have their advantages and disadvantages. Os dot list DIR is really simple and easy. Os dot scan DIR and path lib dot path have a little bit more nuance and you can do a little bit more things with them. But you don't necessarily have the same kind of ease that you do with OS dot list DIR. So all things to consider now that you've got a list with the files in the current directory. But what happens when you want to actually get the attributes of those files? Like the last time they were modified or when they were created, or their size or their permissions or something like that. There are three different options for getting file information. The first is always dots stat, which takes in a path as a string and then returns a stat route result object that has a file data in it. So that stat result object is something that you can access fields of that object and get the file data. Then OS dot scan DIR and path lib dot path dot ITER DIR provide this information with the objects that they return in their iterators. So let's take a look over in the shell. Okay, file data. How do you get it? Well, let's try this. First. I just want to get the contents of this directory. And as you can see, there's a lot of files to choose from. And the first method that I look at it in the slides with the OS dot stat function that just takes in a file path, file name and gives you an OS dot stat result object. As the results, you'll have all sorts of different things, number of links to creation and modification time. Some of these will even differ by system on Windows, on Linux, on Mac, and some of these will have different values. Now I'll show you the two ways that I actually want to get this data. I could save for OBJ and OS dot scan DIR on the current directory. And then let's make a little bit more of an informative output. Let's say something like Mod time equals OBJ Darmstadt. And that's how you get the statistics for a scan DIR object. And then I can say dot STM time. And now we can see something nice like f double-quotes file OBJ dot name was last modified at. And then I could say time dot c time of the mod time. And so this should give everything a nice readable format. It tells you each filename and the time they were Last-Modified, then the path lived on Path option. Here works almost exactly the same way, except you have to create the path object first before you can start iterating through it. So that's three different ways to get statistics from files using Python. In the next lesson, I'll cover something that I haven't covered yet, which is how to create directories. 130. Making and Deleting Directories: In this lesson I'm going to come or how to make directories and even entire directory trees. As usual, there are a few different ways of doing this with the OS module. If you want to create just a single directory, you can use OS dot MKDIR make directory with the directory name, which creates a single sub-directory with a given name. Important to note that this will not create a directory and subdirectories. And if you need that, you need to use OS dot, make DEA, IRS. And then you can pass in a full path name with multiple subdirectories and it will create the full directory tree as needed. With the path lib module, you can use path list.pop dot MKDIR, which functions in essentially the same way as O S dot MKDIR, in that it will not create full directory trees either. In this lesson, I'm going to use really any specific sample directory because I'm just going to be creating directories as I need them. Let's move right on over into the Python shell. Okay, let's make some directories. Os done. Mkdir is the first and the most basic way to do this. It takes in a path parameter and then it can also take a mode parameter and then the DIR FDI parameter. So if I want to create a directory called test, that's pretty simple to do. And then I can use the list DIR to see that it's being created. Now if I wanna do something a little bit more specific, and I wanted to say something like OS dot MKDIR, test2 slash subtasks. Then you'll see that actually doesn't work because test2 doesn't yet exist. So sub-tests can't be created by MKDIR. If I need to do something like that, I can use OS dot, make DEA, IRS, which will make this directory, and then it will make all of these. It will just make everything that I need in order to get to this final directory. So as you can see, list DIR and test two are in there. Then if I call on list DIR on test two, then you can see that it has sub-tests folder just as I needed. So that's really pretty simple and Awesome. The reason that MKDIR exists in this way and the reason that it has the behavior is just to really be kind of a safety valve, a safety mechanism to make sure that you really know what's going on with your file system at all times. Make DEA IRS is awesome. But it can also cause unexpected behavior if you're the one in the directory and you make a whole chain of subdirectories and then you end up in a totally unexpected place. Whereas MKDIR is built to kind of error L before that happens. So that you can handle this. Something else to note here is that both of these will throw an exception if you try to create a directory that exist. If I say OS dot MKDIR test or a west dont make DEA IRS test, then Python will throw me a file exists error because it's trying to create something that already exists. The path lib dot path alternative, which can be accomplished this way. You can avoid that problem if you're trying to do that. So you can say something like this. A new path equals path test. And then you can say a new path dot MKDIR. And you can use the exist okay parameter and set that to true if you don't want it to throw an error if it already exists. Now the issue is with this, of course, is that it just ends up doing nothing because it doesn't make a directory because it already exists. That's definitely something important to note, is that even if you don't want that error to happen, you should probably still wind to know that something is happening there because otherwise, you could run into problems where you think you're creating something new, but really you're creating something and there's already an existing directory. So this behaviour you can eliminate if you need it, but you might not want to at all times. So those are the different ways to create directories and Python. And I think it's really simple and straightforward. Use path dot live MKDIR if you want to use more object-oriented framework, or if you only need to create one directory at a time, use OS dot MKDIR otherwise. And then if you need to create a full directory tree, would subdirectories use OS dot omega d IRS, where you can use the parent's parameters of the path lib dot path, dot-dot-dot, MKDIR option. Now let's look at how directories work. The leading directories. For deleting directories, you can use OS dot ARM DIR, remove directory, where you pass in the directory path and then you delete the single directory, or that's what the function does. It is deleting these single directory. If the directory is non-empty, then it raises an OS error because it doesn't want you to accidentally delete full directories. It wants to make sure that you've cleared them out before you delete them. Path lived on path na.rm. Dir is identical except it operates on a path object as usual. So create the path first and then call its Don RM DIR method. If you need to delete non-empty directories or an entire directory tree, you can still Shuttle. You have to import shuttle, which is short for shell you till, and then it has an RM tree function where you can call on that as the directory path and it will delete the entire directory tree rooted at this path. So if you have some subfolders inside of that directory that you're calling on, those will all be deleted two, no matter if they're full or empty. So this is kind of the nuclear option of deleting directories and Python. All right, let's delete some directories. So first, I'll show you the file system here. So let's make a first try here and just see what happens if you call OS na.rm DIR on Folder one. And of course I have to put in the strings because it needs to be the path rather than there's no variable called Folder one. So as you can see, an OS error because the directory is not empty. Because of course if I call OS dot list DIR on Folder one, it has Python files in it. So that's not going to work. If I want to actually delete something using OS dot RMD IR, I'm going to have to really quickly go to make a new directory which all call test. And then I'll have to make a list DIR to show you that it's in there. Test already exists, so we'll make a directory with name test1. So now there's test1 slash directory, and this test1 slash directory is in fact empty so it can be deleted. This might seem like an unconventional feature that you can only delete with these basic things, directories that are empty. But really it's just a safety feature. It doesn't want you to delete stuff when there might be useful files within that directory. Doesn't want you to lead them without at least thinking about what's in it. Now though, I can see OS dot RMD. And now you can see that it's back, it's gone again. Now I'll show you how you can actually delete one of these non-empty folders. For them, you'll have to import shell util, shuttle, and then you can simply say tried to delete on empty folder. Of course I couldn't. Let's make another example with one test folder. Again, the same. Now I'm going to delete a non-empty folder like modules and packages. And now if I do my list DIR here, modules and packages folder is totally gone even though it had contents in it, right? And this works even for subdirectories. This is really the heavy hitter option which just deletes everything without carrying what's in it. And this can be so useful if you know everything that's in your folder is garbage in that you can delete it. But if you don't know that, you should really be careful to try to use some of these other functions that will warn you by throwing an error if you're trying to delete something that has useful things in it. So that's how you can delete directories in Python. 131. Deleting, Copying, Moving, and Renaming Files: Now that you know how to create and list files along with their attributes, it would be great if you could delete them whenever you were done with them. And that of course, will be the topic of this lesson. Deleting files. To delete files, you have a few options as usual, with the OS module, you actually have two almost identical functions. Always don't remove and OS dot on link, both of which taken the string file path and delete that single file, not a directory, they raise a file not found in the file doesn't exist. And the reason that the two identical functions with different names is just a question of compatibility with different programming paradigms. Some people in old or kind of unix systems like to use unlink as their preferred nomenclature. Whereas some people in different systems use remove. It's just to make sure everyone's happy with the path lib module. You also have a dot on link method, but this is a method of path object. So as usual, you have to initiate that path object before you can call dot on link. So the sample directory then I'll use for deleting the thing, the files with the daughter leadings directory section of this lesson will be the same. I have a couple of sub folders with files within them, and then I just have a couple of files with the top-level sample directory. Okay, let's take a look at how this file works in practice. I'll use the OS dot list DIR to show you where I am in my file system. I have a couple of text files in here and add a couple of folders I could show you as well to estimate totally sure that these folders are what we expect to have in them. A few Python files and a few other folders have some stuff in them to. First let's try out the OS dot remove option here. I'll just call on it. And one of these top-level text files, just for fun, OS dot remove. It doesn't give you any particular output, but trust that it is work. And you can check that by again using list DIR and you can see test1 dot TXT is gone. So that's pretty good. It works just as expected. And then O S dot on link works in exactly the same way. I'll call this on test 2.txt. And as you can see, OS dot list DIR, both of these text files are gone. All I have left is a few folders. Now I am going to tell you a little bit how to copy, move, and rename files and directories. There are several useful functions for copying and moving files for copying. There are two options. There are actually three options with the Shuttle shell utilities module, which I'll have to import. There's copy which takes in a source and a destination file path, and copies the file from the source paths to the destination path. So the source file will still exist. Of course, you're just copying, you're not deleting the first file. The important thing about copy though, is that it just copies the file, the contents of the file, but not its metadata. So for example, things like it's last modification time and so on will not be preserved. That will just be reset to the baseline values. If you needed to do the metadata, you can still use tional dot. Copy to function, which has identical syntax. It just copies the metadata as well. So those are distinct use cases. Then you have shuttled.com P3, which copies full directory trees. This is what you should use if you want to copy directories in any capacity, but just try to keep that in mind while the whole tree rooted at SRC DIR. And then it will copy it into the destination directory for moving renaming. Or because really the two are essentially equivalent, you have two options. One with the Shuttle Module and one with the OS. Shuttle dot move. It takes in again a source and a destination parameter. And it moves the file or the directory from SRC or source to dst, the destination. Then always rename really does essentially the same thing because moving and renaming are really two sides of the same coin, so to speak. It renames the file or directory with the old and the new name. I'll write, I've imported OS and shuttle shall util already. The first thing to do is to show off the functionality of shuttle dot copy. I'll just copy test 1.2x d into a new file and call backup tags. And I'll call it backup 1.2x t Just to make sure you know that it's a backup of Test1 TXT. As you can see, shuttle DOD copy returns the path of the newly copied file back-up one TXT. And if I say ls dot list DIR, you can see that there's now a test 1.2x T and a backup 1.2x T. So this original files preserved and the new backup is also created and those files will be exactly the same content. Now if you need to copy a directory shuttle dot copy will not work. If I try to copy folder one into New Folder one, then that won't work because folder One is a directory. For that, you'll need to use shuttle.com tree, which will do exactly the correct thing. It will copy folder one into New Folder one. I can take a look at that. There it is, Folder one, New Folder, one copied over perfectly. I can list contents of Folder one in the list of contents of the new version just to make sure that you can see that they are in fact identical. So same file, same everything, all copied over just fine. Just be careful with this because it copies the whole directory tree there and he subdirectories, those will also be copied. Sometimes that might not be exactly what you want. Maybe you want a little bit more granularity. And if that's the case, then you'll have to do a little more work and iterate those through the directories on your own. So now let's talk about moving and renaming files because those are really just the same operation. So your opsins are shuttled dot move, and let's try to move test.txt into folder one slash test.txt. As you can see, test.txt is gone from the top level directory, but it shows up in folder one. So that's just like you might expect it to. Now, OS dot rename works almost exactly the same way if you try to move backup 2.txt, which is a file that does not exist in error message will appear on our screen. So a lot of stuff there that all works just fine. And both of these functions work on directories as well. So that's a you can copy, rename and move files and directories in Python. 132. Milestone Project Create an interactive Math Game: Welcome everyone to this milestone Project section of the course. We're going to begin this section by going through a couple of warm up project exercises. We have now covered enough fundamental programming in Python, start coding our first full program. In this section, we're going to code a program that test our understanding of the math order of operations and the rules of an Arithmetic calculation, our program will randomly send an arithmetic question for us to answer. If we get the answer wrong, the program will display the correct answer and ask if we want a new question, if we get it correct, the program will ask if we want a new question. In addition, the program will keep track of our scores and save the scores in an external text file. After each question, we can terminate the program. We will be writing to files for our program. We will call them part one and part two. The first file or part one if you prefer, is MathFunctions dot pi. And the second file, or the second part is math game dot py. I've broken down the program into small exercises so that you can try coding the program yourself. Try the exercises before referring to the answers. Answers are provided in your resources files. Remember, learning the Python syntax is easy but boring. Problem-solving is where the fun lies if you encounter difficulties when doing these exercises, try harder. This is where the reward is the greatest. If you are ready to connect the dots between what you've already learned in creating an interactive program. Let's dive in. 133. Part 1 Importing Modules and Getting the User’s Score: To start, let's create the file math functions dot pi. We will be defining three functions in this file. The first step is to import two modules, the random module and the OS module. I would like to describe the usage of the random module in Python, the random module provides access to functions that support many operations. Perhaps the most interesting thing is that it allows you to generate random numbers, will be using the randint function for the random module. The random function generates a random integer within the range provided by us. We'll use them to generate numbers for our questions later ran into accepts two parameters, a lowest and highest number. The OS module in Python provides functions for creating and removing a directory or folder, fetching its contents, changing in identifying the current directory, et cetera, from the OS module will be using the remove and rename functions. Pause the video and try importing these two modules. The correct code lines are the following. The next step is to get the user's score. Here we'll define our first function. This function accepts one parameter, username type. It opens the file users scores data.txt. In our mode, users scores don t x t looks something like this. Each line records the information of one user. The first value is the user's username and the second is the user's score. Next, the function has to read the file line by line for using a loop. Each line is then split using the split function. Split uses comma as the delimiter. Let's store the result of IIT split function in the list content. Next, the function we'll check if any of the lines has the same username is the value that is passed in as the parameter. If there is, the function closes the file and returns the score beside that username. If there isn't, then function closes the file and returns the string minus1. 134. Part 1 Exception Handling and Updating the User’s Score: Now we need to make some modifications to our code would opening our file previously we use the ARM mode. This helps to prevent any accidental changes to the file. However, when opening a file and our mode in IO error occurs if the file does not already exist. Hence, when we run the program for the first time, we'll end up with an error since the files users scores dot TXT does not exist previously. To prevent this error, we can do either of the following. Instead of opening the file in our mode, we can open it with W mode. When opening with W mode, a new file will be created if the file does not exist previously. The risk with this method is that we may accidentally write to the file, which results in the previous content being erased. However, since our program is a small program, we can check through our code carefully to prevent any accidental writing. The second method is to use a try except statement to handle the IO error. Do that, we need to put all of our previous codes in the try block, then use except IO error to handle the file not found. Error in the except block will inform users that files not found and then proceed create file. We'll use the open function with W mode to create it. The difference here is that the use of the W mode when the file is not found. If the file does not exist initially, there was no risk of erasing any previous content. After creating the file, closes, the file then returns the string of minus one. You can choose either of the above methods to complete this exercise, but I prefer the second method. So let's modify the code. Now we'll define another function called update user points, which takes in three parameters, new user, username and the score. New user can either be true or false. If new user is true, the function will open the file users scores dot TXT and append mode, and append the user's username and the score to the file when he or she exits the game. If new user is false, the function will update the user's score in the file. However, there is no function in Python that allows us to update the text file. We can only write to append to it, but not updated. Hence, we need to create a temporary file. This is a fairly common practice in programming. Let's call this file users scores dot TMP and open it in W mode. Now we'll need to loop through users score don t x t, and copy the data line by line to users force.html. However, before copying will check the username on that line is the same as the one provided by the parameter. If it is the same, will change the score to new score before writing into the temporary file. For instance, if a perimeter provided to the function or is false, Andreas and 30, for example, update user points falls Andreas 30. The table below shows the difference between the original user scores dot TXT and the new user scores dot TMP. After we finished writing to user score dot TMP will close both files and delete users scores dot TXT. Finally, we'll rename users scores Don TMP to users scores dot TXT. 135. Part 1 Generating the Questions and the Mathematical: We've now come to the most important part of the program, generating the mathematical questions, degenerate the questions. Let's first declare three variables, two lists in one dictionary. We shall name the two list, operand list in operator list. Operand list should store five numbers with 0 is their initial values. Operator list should store for strings with space as their initial values. The dictionary consists of four pairs with the integers one to four is the dictionary keys and addition, subtraction, multiplication and exponentiation adds the data. Let's call this operator dict. First, we need to replace the initial values of our operand list with some random numbers generated by the random INT function. Rand INT function takes in two parameters, start and end and returns a random integer n is such as that as less or equal to n or less equal to end. For instance, if Rand INT1 dynein is called, it will randomly return an integer from the numbers one to nine to update our operand list variable with random numbers, we can do this one by one, since operand list only has five members like this. Each time rand INT one dynein is called, It'll randomly returning an integer from the numbers one to nine. But this is not the cleverest way of updating our operand list. Matching how cumbersome it would be if the operand list has 100 thousand members. A better alternative is to use a for loop like this. Great. Now that we have the numbers to operate on, we need to randomly generate for mathematical symbols for our question. To do, then we'll use the rand INT function and the operator D ICT dictionary. Ran Di Andy will generate the dictionary key, which will then be mapped to the correct operator using the operator dict dictionary. For instance, to assign a symbol to the operator list 0, we write. So you should use a for loop to complete this task. However, there is one problem that makes this exercise hard enough. Recall that in Python, exponentiation or two asterisk stands for exponent for example. The problem is, is when we have two consecutive exponent operators in Python, so just two exponent, three exponent two. In the first case, the answer is two to the power of nine, which is 512. In the second case, the answer is eight to the power of two, which is 64. Hence, when we present a question like to exponent three, exponent to, the user will get the answer wrong if he interpreted it as this. To prevent this problem, we're going to modify our code so that we do not get two consecutive signs. In other words, this operator list is fine. But this operator list is not. This park is the hardest thing among all the parts of the project. Let's try coming up with a solution to prevent two consecutive exponents signs. Starting from the second item, IE index equal one and the operator list, the line if index greater than 0 and operator list index minus one, not equal to two consecutive exponents. Signs checks if the previous item in the operator list is the exponent symbol. If it is not the statement operator equals operator. Dick rand IN T12 four will execute since the range is given to the rand INT function is one to four, the numbers 123 or four will be generated, hence the symbols plus minus multiply our exponent will be assigned to the variable operator. However, if the previous symbol is exponent, the else statement operator equal to operator dict rand IN T1. T3 will execute. In this case, the range given to the rand INT function is from one to three. Hence the exponents symbol, which has a key of four and operator Dick will not be assigned to the operator variable. 136. Part 1 Generating a Mathematical Expression and Evaluating the result: Now that we have our operators and operands, we're going to try to generate the mathematical expression as a string. This expression uses the five numbers from our operand list and the format medical symbols from our operator list to form a question, we have to declare another variable called Question string and assign the mathematical expression to questions string. Examples of questions string include. We will use a for loop to concentrate on the individual substrings from operand list and operator list. To get the mathematical expression. We should now have the mathematical expression as a string assigned to the variable questions string. To evaluate the result of this expression, we're going to use a brilliant built-in function that comes with Python. Evil. Evil interprets a string as a code and executes the code. For instance, if we write email one plus two plus four, we will get the number seven. Hence, to evaluate the result of our mathematical expression, we pass in question string to the eval function and assign the result to a new variable named result. This depth is pretty straightforward and can be completed in one code line. Finally, we are going to interact with our user. In this exercise, we will be doing a few things. Step one, displaying the question to the user. Step two, prompting the user for an answer. Step three, evaluating the answer, displaying the appropriate message and returning the user's score. For Step one, we need to use a built-in function for manipulating strings, as mentioned earlier on Python, the two asterix symbol stands for exponent, that is 32, asterix three equals 27. However, to most users, to asterix has no meaning. Hence, if we display a question as this, the user will likely be confused. To prevent that will replace any two abstract symbols in question string with a carat symbol. To do that, we'll build in the function replace using it is straightforward. Just right. Now you can print the resulting expression to the user. For step two, we can use the input function to accept user input. For step three, we should use an if statement to evaluate the answer and display the correct message. If the user get the correct, we will compliment the user and return the value one. If the user gets it wrong, will display the correct answer and return the value to 0. What if the input function returns user input as a string? In this case, when you compare the user's input with the correct answer, you have to do some typecasting to change the user input to an integer. When changing the user input to an integer. And you should try to use a try except statement to check if the user typed in a number. If the user typed in a string instead, the program should inform the user of the error and prompt the user to type it in number. So we have to use a true loop while prompting the user for a number as long as he's slash, she fails to do so. Writing while true is equivalent to writing something like one equal to one, since one is always equals to one, hands always true. The loop will run indefinitely. Let's edit the code. The while True loop will keep looping since the while condition is always true. Exit only when the try block executes correctly and reaches the return statement. 137. Part 2 Writing the Main Program: Congratulations for completing Part one and welcome to part two. Part two is going to be a breeze as we'll mainly just be calling the functions we defined earlier. First, let's enclose our main program in a try except statement. We want to handle any unforeseen errors. One running the main program will start by writing the code for the try block. First, we'll need to import the math functions module. Next, let's prompt the user for his or her username and assign the value to the variable username. Pass this variable as a parameter to the function and get users score. Get users score will either return the score of the user or return minus one if the user is not found. Let's cast this result into an integer and assign it to the variable user score. Now we need to set the value of another variable, new user. If the user is not found, new user equals true, else new user equals false. If new user equal true, we need to change it from score from minus one to 0. The next part of our program involves a while loop. Specifically, our program will prompt input from our user to determine if it should terminate the program or do something else. Step one, you need to declare another variable which user choice, and give it an initial value of 0. Step two. Next, while using a while loop, compare user choice with a string of your choice, say minus one. If user choice is not same as minus1 called the function generator. To generate a new question. Step three, January question will return a score that the user God for that question, use this result to update the variable user score. Step four, finally, in order to prevent an infinite loop, we need to use the input function again with the while loop to accept the user input and to use it to update the value of user choice. Finally, after the while loop terminates, the next step is to update the users score dot TXT file. To do then, we simply call the update user points function. That's all for the try block. Now the except block, we simply inform the user that an error has occurred and the program will exit. Will do finish this damp, you'll have a complete program. Let's run the program. The program will ask for a username. Let's type my name. Then the program generates a question. The mathematical expression I have to calculate, I will not calculate the numbers now, so I'll put in a random number. Of course, my answer is wrong and there is a correct answer. After that, the program will ask me if I want to continue or type minus1 to terminate the program. I will do another example. It works great. Excited. I sure hope you're as excited as I am. We've come to the end of his Milestone Project and hopefully you have successfully coded your first program. If you have problems completing any exercise, please let me know. But we haven't finished yet. I have an additional exercise for you to challenge yourself. Sometimes the question generated may result in an answer that is very large or very small. It is very inconvenient for users to calculate and key in very large or very small number. Hence, we want to avoid answers that are too big or small. Can you modify the program to prevent questions that result in answers greater than 10 thousand and smaller than negative 10 thousand. Try to modify the code and check the code from your resources files. Thanks for watching.