Python Programming: Code Python Like a Boss & Become a Dev! | Jason Cannon | Skillshare

Playback Speed

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

Python Programming: Code Python Like a Boss & Become a Dev!

teacher avatar Jason Cannon

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

48 Lessons (2h 11m)
    • 1. Course Overview

    • 2. Python 2 vs Python 3

    • 3. Installing Python on Windows

    • 4. Installing Python on Mac

    • 5. Installing Python on Linux

    • 6. Writing Python Programs

    • 7. Running Python Programs

    • 8. Strings and Variables - Section Overview

    • 9. Variables and Strings

    • 10. Functions and Printing

    • 11. String Methods

    • 12. String Concatenation

    • 13. Formatting Strings

    • 14. Strings and Variables - Section Summary

    • 15. Numbers and Math - Section Overview

    • 16. Numbers, Numeric Operations, and Numeric Functions


    • 18. Numbers and Math - Section Summary

    • 19. Booleans and Conditionals - Section Overview

    • 20. Booleans

    • 21. Conditionals

    • 22. Booleans and Conditionals - Section Summary

    • 23. Functions - Section Overview

    • 24. Functions, Part I

    • 25. Functions, Part II

    • 26. Functions - Section Summary

    • 27. Lists - Section Overview

    • 28. Lists

    • 29. Slices

    • 30. Exception Handling

    • 31. Loops

    • 32. Sorting Ranges

    • 33. Lists - Section Summary

    • 34. Dictionaries - Section Overview

    • 35. Dictionaries, Part I

    • 36. Dictionaries, Part II

    • 37. Dictionaries - Section Summary

    • 38. Tuples - Section Overview

    • 39. Tuples

    • 40. Tuples - Section Summary

    • 41. Files - Section Overview

    • 42. Files, Part I

    • 43. Files, Part II

    • 44. Files - Section Summary

    • 45. Modules - Section Overview

    • 46. Modules, Part I

    • 47. Modules, Part II

    • 48. Modules, Section Summary

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





About This Class

Learn Python Programming the Easy Way, Complete with Examples, Quizzes, Exercises and more. Learn Python 2 and Python 3.


If you want to learn how to write Python programs like a pro, code python like a boss, solve real-world problems, or automate repetitive and complex tasks, read on.

Hello. My name is Jason Cannon and I'm the author of Python Programming for Beginners, Linux for Beginners, and an instructor to thousands of satisfied students. I started my IT career in the late 1990's as a Unix and Linux System Engineer and I'll be sharing my real-world Python programming and coding experience with you throughout this course.

By the end of this course you will be able to create Python scripts with ease. You'll learn how to take tedious and repetitious tasks and turn them into programs that will save you time and simplify your life on Linux, Unix, or MAC systems.


Here is what you will get and learn by taking this Python Programming course:

  • When to use Python 2 and when to use Python 3.
  • How to install Python on Windows, Mac, and Linux.
  • How to prepare your computer for programming in Python.
  • The various ways to run a Python program on Windows, Mac, and Linux.
  • Suggested text editors and integrated development environments to use when coding in Python.
  • How to work with various data types including strings, lists, tuples, dictionaries, booleans, and more.
  • What variables are and when to use them.
  • How to perform mathematical operations using Python.
  • How to capture input from a user.
  • Ways to control the flow of your programs.
  • The importance of white space in Python.
  • How to organize your Python programs -- Learn what goes where.
  • What modules are, when you should use them, and how to create your own.
  • How to define and use functions.
  • Important built-in Python functions that you'll use often.
  • How to read from and write to files.
  • The difference between binary and text files.
  • Various ways of getting help and find Python documentation.
  • Practice exercises with solutions so you can start using what you learn right away.
  • A download that contains the scripts used in the presentations and lessons. You'll be able to look at and experiment with everything you're learning.
  • Quizzes after each section just to make sure you're learning the most important aspects of Python programming
  • Unconditional 30 day money-back guarantee - that's my personal promise of your success!

Learn to Program Using Python 2 and Python 3

In this course you'll learn when to use Python 2 and when to Use Python 3. The great news is that no matter which version of Python you choose to use, I've got you covered. I'll show you exactly how to program in both versions.

Perfect for Windows, Linux, Unix, Mac, the Web and More!

Once you've completed this course you'll know how to write programs that will run on the Linux, Mac, and Windows operating systems. You can even take what you've learned and apply it web applications.

So... what can do with all this Python knowledge?

Python is HOT right now. The demand in the IT job market for Python skills keeps growing and growing. If you're looking to get into programming as a career, level-up your existing career or open up new doors in the IT field, you really need to learn Python!

Here's What People Are Saying About Jason and His Courses:

"I started this course and instantly started learning new things, just fantastic." --Steven Smith, student

"The instructor is knowledgeable and delivers the course in a way that's easy to follow... Clear, concise, and informative." --Regena Ingram, student

"Excellent course on Linux! It is the best way to get started using Linux that I have come across." --Chris Bischoff, student

"This was a great course! Learned a lot from it!" --Ricardo José Crosara Junior, student

"Excellent starter course. Very good and complete guide to get you started on working on Linux." --Brian Mulder, student

"Great course! Easy to understand for beginners and a great refresher for experienced users!" --Spencer Ball, student

"Very well laid out course. Thanks Jason!" --Eric Etheredge, student

"Love it... it's absolutely one of the best courses I've taken..." --Idriss N, student

"Awesome Course! Another great one. Thanks Jason!" --John Wilmont, student

"Excellent Course! Having come from a moderate understanding of Linux, this course has given me a deeper and more streamlined understanding of Linux. Definitely worth the money." --Armando Cabrera, student

"Fantastic course and very beautifully explained." --S John, student

"Great course, great instructor. I enjoyed every minute of it. I recommend this course 100%." --Alfredo, student

"I am lovin' it. Nice way to begin one's journey into Linux." --Rohit Gupta, student


Free Bonus - Downloads of All the Material Covered

As an added bonus for enrolling in this Python Programming video training course, you'll receive access to all the slides, Python programs, and source code used in the lessons. You can download them and refer to them when you want to jog your memory or double-check your work.

Enroll now and to learn how to write Python programs like a pro!

Meet Your Teacher

Teacher Profile Image

Jason Cannon


Jason Cannon started his career as a Unix and Linux System Engineer in 1999. Since that time, he has utilized his Linux skills at companies such as Xerox, UPS, Hewlett-Packard, and Amazon. Additionally, he has acted as a technical consultant and independent contractor for small businesses as well as Fortune 500 companies.

Jason has professional experience with CentOS, RedHat Enterprise Linux, SUSE Linux
Enterprise Server, and Ubuntu. He has used several Linux distributions on personal projects
including Debian, Slackware, CrunchBang, and others. In addition to Linux, Jason has
experience supporting proprietary Unix operating systems including AIX, HP-UX, and Solaris.

He enjoys teaching others how to use and exploit the power of the Linux operating syst... See full profile

Class Ratings

Expectations Met?
  • 0%
  • Yes
  • 0%
  • Somewhat
  • 0%
  • Not really
  • 0%
Reviews Archive

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

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

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


1. Course Overview: hello and welcome to the course. I'm glad you're here, and I wanted to briefly share some of what's in the course and what you're going to learn first, to learn how to install python and prepare your computer for writing python programs. Next, you'll be introduced to variables and strings. From there, you'll learn how to a handle numbers and perform mathematical calculations with python that will move on to billions and conditional is where you'll learn how to perform simple tests and make decisions in your programs. You'll also learn about functions. You'll learn how to create your own and learn about some of the built in functions Python has to offer. Next, we'll talk about lists and how toe loop through a series of items and perform the same action on each one. You'll also learn about python dictionaries. Next will cover two pools and you'll learn how to store. Read only data and them. You'll also learn how to store and retrieve data from files. Finally will wrap up the course by discussing modules in the standard Python library. Those were just the major highlights, but there's much more in this course, so let's get started 2. Python 2 vs Python 3: Let's quickly talk about whether you should use Python to or python three if you're just starting a new project or just learning. Python at highly recommend using Python three Python 3.0 was released way back in 2008 and at this point, Python two is really considered legacy. However, there are a lot of python to programs that are still in use today, and you may encounter them from time to time. The good news is that the Python 2.7 release bridges the gap between the old python to and the new python three. Much of the code written for Python three will work on Python 2.7. However, that same code will most likely not run unmodified on python versions 2.6 and lower. Here's the bottom line. If it all possible, used the latest version of python available. If you must use python to use python 2.7 as it's compatible with all python to code and much of python three. The primary reason to choose python to over Python three is if you project requires some third party software that is not compatible or just doesn't exist for Python three 3. Installing Python on Windows: Since Python doesn't come installed on Windows by default, we need to download and install it. To do that will visit python dot org's, and then we'll just go to the download section. And then we're going to download the latest version of Python and hear. The latest version is this Python three Serie. So let's click here and down, though that and when that's done, downloading will launch it and pretty much we're just going to accept all the defaults. One important thing to do is check this box right here where it says add python to path. We want to do that so we can run python programs from the command line. If we wish, I will just click install. Now, if you get a pop up asking you if you want this program to make changes to your computer, select Yes. Again, we're gonna answer yes to all these questions. Okay, Python has been installed. We'll just go ahead and close it out here and you are ready to go 4. Installing Python on Mac: at the time of this recording, the MAC operating system ships with Python to. In order to use the latest version of Python you'll need to download and install it. To do this, visit python dot org's and click on the download section. Next, download the latest version of Python. Once you have it downloaded, you can launch the installer and then simply accept the defaults. This consists of mainly just clicking the continue key. If you're prompted to enter in your user name and password, go ahead and do that. Once pythons installed, you should see a Python folder in your Applications folder inside the Python folder. You'll see an Idol application. If you can launch that, just know that you've installed Python successfully will be going over the idle application in a coming lesson. 5. Installing Python on Linux: some Lennox distribution ship would just python to installed. However, it's becoming more and more common to see python to and python three installed by default to determine if you have python installed. Just open up a terminal and type python dash, dash version and python three dash dash version. In many cases, the Python command will actually be python to, and the Python three Command will be for running Python three. So here's an example of that python dash dash version. So this is the python 2.7, Siri's and Will Bron Python three dash dash version. So in some cases, like we just said, Python three is not installed by default, in this case will get a command, not found message like we have here. So in order to install Python three on a Debian based distribution such as Debian, a Bun to and Lennox met will need to run apt get install Dash. Why Python three. Space Idol three. Installing software requires root privileges so we can do that with Sue. Do in front of the command and just note that Sue has to be configured before it can work, and sometimes it is configured by the distribution. Sometimes you have to do it yourself. Or sometimes a system administrator has configured it for you. If it's not configured, you'll have to switch to the root user and do the install, which I'll show you next. So here's an example of you do after get installed dash y for. Yes, just go ahead and install it. We're gonna do Python three and idle three and then old l know the necessary packages and performed the install. Now let's test the python three version Python three dash dash version and we can see that indeed. Python three did get installed. Now, if if you get an error, something about you do not configured, then you'll want to type s you space dash and hit enter and then enter the root password. And then from here you can run the apt get install command. So we've already installed Python three. So I'm not gonna do it at this moment. But that's exactly how you could install Python three on a debian based distribution for our PM based Lennix distributions such as Santos Fedora, Red hat and scientific Lennox. You can attempt to install python three using the yum install Dash y python three Space Python three Dash tools Command again. Be sure to run the command as root or proceeded with studio as installing software requires root privileges. Here's an example of me trying to install Python three on a cento system when a U pseudo pseudo young installed dash s our dash y for yes, Python three python, three dash tools. In this example, it didn't work. There isn't a python three or Python three tools package available. If this was fedora, that would have worked. So in this particular case, we need to install Python using the source code before installing Python three from source code, we're going to have to install some dependencies and in the course, down those section I have all these commands listed out. So if you don't catch him on the screen right here, you can follow along with the course downloads. So the first thing we need to do is a young group installed of the development tools. Now that that's complete, we need to install a couple additional dependencies. Will Ron sued? Ooh yum! Install deaths. Why see lead Dev open SSL dash develop sequel light develop visit to develop and TK develop . Now that we have all the dependencies installed will visit python dot org's and download the Python source code. Here we are at python dot org's. We can go to the download section and download the latest source code here. Go ahead and save that file. Back at the command line. I'm just going to navigate to the directory that I saved the file, and in this case it's the downloads directory. And then I'm going to run the Tar X F command. And then we can just run like this Python star, and that will extract the contents of that archive that we downloaded from python dot org's . Again. These commands air in the download with the course. Now that we've extracted, the contents will just change into the directory and then from here. What we need to do is run the configure command dot slash configure. Next, we run the make command, make a eat dinner. The make command will probably take several minutes to run, so it's normal if it takes a while. The next command we want to run a su make install. This gives us root privileges to do the installation IFC do is not configured. What you'll want to do is switch to the root user with s u dash. And then what you're going to need to do is come back to this directory. You want to see the into home and then whatever your user name, waas and your downloads directory, and then finally into the python directory. But since we have Sue configured here, I'm going to take advantage of that and just run, Sue, do make install. Now, when I run the Python three command, it should work. And there you have it. You successfully installed Python three from source code. 6. Writing Python Programs: When you develop your python programs, you're going to need an editor to write your code in as well as a way to quickly execute that code. You'll probably find yourself writing a bit of python code, executing it to check your work, switching back to the editor and either making adjustments or continuing on with the rest of your application. Fortunately, Python ships with an I D E, which stands for integrated development environment and I D E can help you do what I just described, and it allows you to quickly create and develop applications. Pythons I. D. E. Is called idle. It also stands for integrated development environment. In order to start Idol, located in the Python Installation folder in Windows, you can search for idle and launch it from the search results. You can also navigate to the Python folder and launch Idol. From there in Mac, you'll find Idol in the Python folder, located in the application's folder. Lennox users may be able to navigate to idle and the menu ING system if they're using a graphical user interface. You can also launch Idol from the command line by opening up a terminal and typing in idle three. Once Idol is launched, it looks the same on all operating systems. When you first launch idol, it will open a python shell. This allows you to interact with a python interpreter directly here. You can type in python commands, which are executed right away, and you receive immediate feedback. It's an excellent way to experiment with Python and answer any of your I wonder what happens if I were to do this type of questions. By the way, Python is called an interpreter because it translates or interprets the python language into a format that is understood by the underlying operating system and hardware. Look, if you a quick example, I'm going to enter in on a single line of python code here. I'm going to type print open parentheses, a quote. Hello, a quote and then a closed parentheses and I'm going to hit. Enter. The command was executed and the results were displayed to the screen. We'll get into exactly what just happened in a later lesson, but for now, the most important point for you to know is that you can interact directly with a python interpreter. Now let's create a python program to do that, go to the file menu and select new. This brings up an editor. I've rearranged the window so we can see both the editor and the show in the editor weaken type in our python code and save it to run at a later time uncle ahead and type in a line of python code. Now, in order to execute this code, you'll need to save it. If you forget to save it. Idle will remind you by displaying a prompt asking you to save the file. I'm going to see the file now by going to the file menu in selecting save by convention. Python programs are saved with a dot p. Why extension? If you just type in the name of the file like hello and don't change any of the defaults, it will be saved us. Hello dot p y. Now do you execute our run the program. I'm going to go to the run menu and select run module. Notice that you can also hit F five to accomplish the same task. If we look at the other window, you can see that the program was executed and the resulting output was displayed If we want to add more code to our program, we go back to the editor, add more code and check our work again. By running the Python program, you might have noticed that print is displayed in purple and hello is displayed in green. This is called syntax, highlighting it can help you visually determine if you have a syntax error and are doing something that Python just doesn't understand. Let me add an invalid line of python code. Let's say I misspelled the word print. I can see that it's now in black instead of purple, and I may be able to catch my mistake even before I attempt to run my program. Also idle, supports auto completion. So if I were to type PR I and hit the tab, key Idol will finish the command for me. If I were you, just type the letter P and hit Tab. That's not enough information for idle to know what I'm trying to do. So it pops up a list of possible choices here, Aiken simply Errol up or arrow down to select what I want. And then I can continue typing. You might have noticed that Idol provides you with help as you are using the editor. Or show these little pop ups air called call tips, and they briefly explain how to use the python command you're working with. If you want to open an existing python program or come back to a program that you are working on at an earlier time, simply go to the file menu, select open and navigate to the source code file. Finally, to quit or exit out of idle, go to the file menu and select Exit. 7. Running Python Programs: after you've created your python program, you probably don't wanna have to load it into idle and run it from there each time you want to use it. And this lesson I'm going to share with you a couple of different ways to execute your python programs. If you are in Windows, you can simply double click on your Python program to execute it. A window will pop up why the program is executing, and then it disappears after it's done. Here's what that looks like. I'm going to click on this hello file, which happens to be a Python program. You can see that it runs and it quickly disappears. Now, this might be perfectly fine, depending on what the program does. If you don't really need to see the output of the program, then this will work just fine. But let's say you do want to see the output from the program before the window disappears. To do this run. The program from the command line first opened up, a command prompt and windows. You can usually search for command prompt or find it in the menu. I'm just going to type in command prompt. You can also type in CMD many times, and it will come up a swell. So I'll just click here to start it from here. We can just type in Python and then follow it with the name of the Python program we want to execute. I've saved this hello dot p y Python program on my desktop. I could run the program by providing a path to the file like So I'm just going to type in Python, and then I'm going to give a full path to that file. So see users in this case owner desktop, hello dot p Why? And then the output is produced. By running that program, I can also run it with a relative path like so use python and then, since it's in the desktop subdirectory high, just run it like this and it also executes. Let me change into the desktop directory and run it again. You might have noticed that the file ends in a dot p y extension, but when you look at it on the desktop or in the file, explore the dot P y extension is hidden. Just be aware that you have to include the full name of the file when running it from the command line. Let's move on to Mac and Lennox. Here, the process is very similar. To get to the command line, open up a terminal on Mac. The terminal is located in the Utilities folder that resides in the application's folder. Once the terminal is started, type Python three and then follow it with the name of the Python program you want to execute. So we'll type Python three and then hello dot p y. If you're using python to, then you would run python hello dot p y. In addition to supplying a python file to the Python three Command, you can execute the file directly by setting the execute bit on the file and specifying Python in the Interpreter directive on the first line to set the execute will bit on the File Ranch Ahmad Space Plus X and then the name of the file here will do this on hello dot p y. Let's look at the contents of this file with Cat Command to set the interpreter directive. Make sure the first line in your python file looks like the first line in this Python file starts with a pound sign than an exclamation point and then Ford's last user. Ford slash ben ford slash e NV Space Python three. Now that the interpreter directive line is in place, we can run the Python program by using relative or absolute pass to the file. I can do that by running dot, slash, hello dot p y and hitting. Enter. Or it could run the file by providing the entire or full path to that file. I'll do that by typing and slash users slash Jason slash hello dot p y and his inner note that it's safe to include the interpreter director of Even if the program will be executed on a window system, Windows will simply ignore that line and execute the remaining python code. Finally, I'd like to point out that you could run the python shell interactive leaf from the command line to do that end of the python command by itself. On the command line here, all inter python three. You can see that this looks like the python shell you see when using idol to exit or quit the shell type. Quit with a pair of parentheses 8. Strings and Variables - Section Overview: in this section of the course, you'll be learning all about variables. You'll learn what they are, as well as how and when to use them. You'll also be introduced to the string data type. You'll learn how to create and manipulate strings will even talk about some challenges that are specific to strings and how to handle them. Next, we'll look at several ways to format strings so you can create the output that you desire. You'll also get introduced to some of the most commonly used built in functions Python has to offer. We'll get into the basics of object oriented programming, and how it specifically applies to Python finally will wrap up this section of the course by covering methods. 9. Variables and Strings: variables are storage locations that have a name, said another way. Variables are name value pairs. You can assign values to a variable and recall those values by the variable name to a sign of value to a variable. Use the equal sign. The format is variable. Name equals value. Here we have an example where the value of apple is assigned to the variable called fruit. You can change the value of a variable by reassigning it on the next line. You can see how to set the value of the fruit variable to the value of orange. Note that there is nothing significant about the variable name fruit we could have easily used. Produce crop food or almost any other variable name that you can think of when choosing a variable name. Pick something that represents the data that variable will hold. You may know what a variable name X represents today, but if you come back to the code a few months from now, you may not. However, if you encounter a variable named fruit, chances are you can guess what type of data it will hold. Terrible names are case sensitive. A variable name fruit that begins with a capital F and another variable name fruit. That is in all lower case are two different variables by convention. Variables are in all lower case letter, but it's not a requirement. Variable names must start with a letter. They can contain numbers, but variable names cannot start with a number. You can also use the underscore character in variable names. You cannot use a hyphen or a plus sign and some other various symbols and variable names. Whenever you get the urge to use a hyphen, just use an underscore instead. Here are some examples of valid variable names. The first example is in all lower case letters, and it contains a number. However, it doesn't start with a number, so it is a valid variable name. The second line 1st 3 letters is an all lower case, and it includes underscores, which are valid. However, you can't use dashes, so first dash three dash letters would not be a valid variable name. The third variable is 1st 3 letters, and it's in mixed case, some lower case letters and some upper case letters. Again, this is perfectly fine, but just note that this variable would be a completely distinct variable from 1st 3 letters . In all, lower case, where example. A string is used to represent text and the previous examples. The text Apple, Orange and ABC are strings and python strings air surrounded by quotes. Let's revisit our first example of creating a variable name fruit and assigning it to the string. Apple strings can be encapsulated in single quotes or in double quotes. Python expects matching quotation marks for strings. When you start a string definition with a double quotation marks. The next double quotation mark that python encounters is interpreted as the end of that string. The same is true for single quotation marks. If you start a string with a single quotation marks, the next single quotation mark represents the end of that string. If you want to include double quotes in a string, you can place them inside single quotes, as in this first example. If you want to include single quotes in a string, enclosed the string and double quotation marks, as in the second example on the screen. What if you wanted to use both single and double quotes in the same strain? Well, at this point, you need to escape the offending quotation character by pre pending a backslash on the first example on your screen, the first double quotation mark right before she represents the beginning of the string, and the next quotation mark You Come to is part of the string because it is escaped by the preceding Backslash character. The next double quotation mark you come to is also escape, so it's also part of the string and then the final quotation market. The end of the line since it's not escape, is the end of the string, and it matches the beginning quotation mark at the beginning of the string. On the next example, we have the same situation with single quotation marks. The first single quotation mark begins the strain. The next single quotation mark is escaped with a backslash character, so it's part of the strain, and the last single quotation Mark represents the end of the string, and it matches the opening single quotation mark. Each character in the string is assigned and index string indices are zero based, meaning that the first character in a string has an index of zero. The second character has an index of one, etcetera to access the character at a given index, a penned an open bracket and a number and a close bracket to a string where the number is the index number on your screen, you can see where we create a variable named a and assign it the character in position zero of the string apple. In the next example, we have a variable called E, and it's created using the character from Position four of Apple. The character and position for is, of course, the E. Since variables are simply names that represent their values, this syntax also works with variables. At the bottom of your screen, you can see where the variable fruit is assigned the string apple. The first underscore character variable will equal a because the zero index of the fruit variable is a because it contains the value apple. 10. Functions and Printing: a function is a set of reusable code that performs an action. A function has a name and his cold or executed by that name. Optionally functions can accept arguments in return. Data Python includes many built in functions, one of which is the print function. When a value is provided as an argument to the print function, it displays that value to the screen. You can supply values directly to the print statement or pass in variables on your screen. You can see that we assign the value apple to the variable fruit, and then we print or display that variable to the screen, and the output is apple. Next we print a string directly without a variable involved, and that string is orange and it gets printed to the screen as well. Another built in function is the land function. When a string is provided as an argument to the Lend function, it returns the length of that string, said another way. Land returns the number of characters in a string. In this example, the value of apple is assigned to the variable named fruit. Next, we assign the result of land fruit to the fruit underscore, lend variable. Finally, we display that value to the screen, using the print fruit underscore land function. Since Apple has five characters, the number five is displayed to the screen. You can also pass the land function directly to the print function and skip the intermediary step of assigning it to a variable. This works because land parentheses, fruit, close parentheses is evaluated first, and its value is used by the print function you could even skip using variables all together. In this case, we just called land directly on the string apple. Then we print the value that is returned by land, which is five. 11. String Methods: without going to in depth on the subject of object oriented programming. At this point, it is helpful to understand a couple of concepts before we proceed. The first thing to know is that everything in python is an object. Also, every object has a type you've already been learning about the string data type and will cover other types throughout this course. But let's get back to strings for a moment. For example, apple, surrounded in single quotation marks, is an object with a type of str and str short for stream, said another way. Apple is a string object if we assigned the value of apple to the variable fruit. Using fruit equals apple than fruit is also a string object. Remember that variables are just names that represent their values. As previously mentioned, a function is a set of reusable code that performs in action. That's far you've been using built in functions like print and Lynn. Objects also have functions, but they're not called functions. They're called methods, so methods air functions that air run against an object to call a method on an object, follow the object with a period than the method name and finally a set of parentheses and close any parameters in the parentheses. The lower string method of a string returns a copy of the string and all lower case letters . In this example, you can see how running the lower method on a string object returns that string in all lower case letters. In this example, fruit dot lower returns apple in all lower case letters. The upper string method returns a copy of the string in all uppercase letters and this example If we Ron fruit dot Upper, we get apple and all uppercase letters. 12. String Concatenation: to concoct innate or combine two strings. Use the plus sign. You can think of this as adding strings. Together. You can concoct innate multiple strings by using additional plus signs and strings, and this example notice how spaces are included in the strings string. Can Cat Nation Onley combines the strings as they are, and these strings you can see that I love Python is separated by spaces because those spaces are included in the strings themselves. If you do not include extra spaces, it would look like this. All the words would run together. Remember that the plus sign doesn't do anything. It doesn't add any extra characters. It just combines or adds the strings together. This is an example that demonstrates string concatenation using variables. First, we create three variables first equals. I second equals love and third equals python. Next, we create a variable name senates, and we assign it the value of first plus a space plus second plus another space plus third plus a period. So when we print that sentence, we end up with I Space Love Space Python period. When working with strings, the asterisk is the repetition operator. The format is string asterisk and the number of times you want to repeat that string. For example, if you want to display a hyphen 10 times, use a hyphen EST risk. 10. Note that you don't have to use string repetition with just single character strings. In this example, we're repeating the string happy three times. Here we create a variable name happiness in a sign it too happy asterisk. Three. The output of Happy Asterix three is simply happy, repeated three times. So when we print the happiness variable, we end up with happy, happy, happy and an upcoming lesson. You'll be learning about number data types. For now. Just know that unlike strings numbers, air not enclosed in quotation marks to Can Captain eight, a string with the number first convert the number to a string with a built in str function . The str function turns non strings, such as numbers in two strings and this example We create a variable name version and a sign it the number three. Then we print I Love Python. Then we can captain eight that with the string representation of the variable version, and then finally we contaminate that with the period so we end up with. I love Python three. Here's what happens when a number is not converted to a string before can Cat Nation is attempted, you can see that the air message reports that it can't convert an image or object or I nt object to a str our string object. Just remember to explicitly convert numbers into strings using the str function before you attempt to use them as a string. 13. Formatting Strings: instead of contaminating strings to produce the format. Your desire. You can call the format method on a string create placeholders, also known as format fields, by using curly braces in the string and passing values for those fields to the format method. But a fault. The first pair of curly braces will be replaced by the first value passed to format. The second pair of curly braces will be replaced by the second value passed, a format and so on. In the first print statement, the String I curly braces, which is the placeholder python, evaluates to I Love Python because the curly braces will be replaced by a book, String Love that has passed into the format command. The string in the second print command is comprised of three placeholders. The first place holder will be replaced by the first string passed. The format, which is I the second place holder, will be replaced by the second string passed, a format which is love and likewise the third place holder will be replaced by the third string passed, a format which is python. Notice that when you pass multiple objects toe a function are method, you separate them using a comma. So we have format a string, which is I in single quotes. Then we separated from the next one by a comma, and then we have another string, and we separate that from the last one with another comma. You can explicitly specify which positional parameter will be used for a format field by providing a number inside the braces. So zero, encapsulated in curly braces will be replaced by the first item passed to format. One, encapsulated in curly braces, will be replaced by the second item passed in etcetera. In the example on your screen that zero, surrounded by curly braces, will be replaced by the first string Love, and the one surrounded by curly braces will be replaced by the second string passed a format, which is python. So the output in this case is I love Python. Python loves me. Here's an example of formatting strings. Using variables, we don't have to explicitly pass a string to the format command again. Variables just represent the values that they contain, and since thes variables 1st 2nd and third represents strings, then we can just pass those into format. In this example, the first place holder gets replaced by the first variable, the second with a second and the third with the third, and we end up with a string I love Pike on. Now we can rewrite one of our previous examples that combine strings and numbers with the format method. This eliminates the need to use the str function and this example. The placeholder is replaced by the value of version, which is three, and when we run print against the string, we end up with I Love Python three. You can also supply a format specifications format. Specifications are contained within the curly braces and begin with a colon to create a filled with a minimum character with supply and number. Following the colon. The format field of open curly brace zero colon eight. Close curly brace translates to use the first value provided to format and make it at least eight characters wide. The format filled of open curly brace one colon eight close curly brace means used the second value provided to format and make it at least eight characters wide. This method can be used to create tables, for instance, here's an example where we've done just that. We formatted eat string to be at least eight characters in length to control the alignment used less than for left a carrot for center and greater than for right. If no alignment is specified, left alignment is assumed. Building on our previous example. Let's left line the right column, which contains quantity and the numbers three and 10. Here you can see the format string we used to accomplish this and open Curly Brace, a one which represents the second item passed into the format. Method Colon. A less than sign, which performs the left alignment. And eight, which specifies that the string be at least eight characters in with. You can also specify a data type. The most common cases to use F, which represents afloat floats or floating point numbers, will be covered in detail. In another lesson, you can specify the number of decimal places by using dot in F, where N is the number of decimal places. A common currency format would be dot to F, which specifies two decimal places. Here's what our table might look like if we take a couple of bites out of our apple, No to set the value corresponding to Apple is 2.33333 However, only 2.33 is displayed because we have got to F, which says Give us two decimal places in this floating point number. You could also notice that we have 10 oranges, but again we forced to decimal places so 10 will be displayed. Its 10.0 use the built in function input to accept standard input by default. Standard input comes from a person typing at the keyboard. This allows you to prompt the user for input. In advanced cases. Standard input can come from other sources. For example, you can send the output of one command, asked the standard input toe another command using pipes. For more information on this topic, you can refer to my limits for beginners book or might learn Lennox and five days class. You can also pass in a prompt to display to the input function and this example. We display the prompt, enter a name of a fruit to the user and then what the user supplies will be assigned to the fruit variable here were using a format string to print the information provided by the user. At the bottom of your screen is the output you would see if you happen to run this program and provide the input Apple. 14. Strings and Variables - Section Summary: In this section of the course, you learn that variables are simply names that store values. You also learn that variables must start with a letter, but that they can contain numbers as well as underscores. You can assign values to variables by using the variable name equals value syntax. You also learn how to create strings by surrounding them with quotation marks, either single quotation marks or double quotation marks, and you also learn that each character in the string is assigned in index. We also talked about functions and how they're simply pieces of reusable code that perform a specific action. Some of the functions we talked about were built in functions like the print function, which displays values to your screen and the lend function, which returns the length of an item. We also talked about the str function, which turns and non strings such as numbers into strings. Finally, we gathered user input by using the input function in the section. You also learn that everything in python is an object and that objects can have methods and methods air functions that operate on an object you learned about the following string methods. The upper string method, which returns a copy of the string in all uppercase, the lower string method which does theocracies it, which returns a copy of the string in all lower case, and we also talk about formatting strings with a format method. 15. Numbers and Math - Section Overview: in this section, you will learn how Python handles numbers. First, we'll talk about the various mathematical operations you can perform. Next, you'll learn the difference between integers and floating point numbers finally will touch on comments in our python code. 16. Numbers, Numeric Operations, and Numeric Functions: In a previous lesson, you learned how to create strings by enclosing text in quotation marks. Numbers and python require no such special treatment when you want to use a number simply included in your source code. If you want to assign a number to a variable, simply used the format of variable name equals number. There are a couple of examples of doing this on your screen. Python supports integers as well as floating point numbers. Integers are whole numbers or numbers without a decimal point. Floating point numbers always contain a decimal point. The data type for integers is I anti. While the data type for floating point numbers is float, the Python interpreter can perform several operations with numbers. Here's the table of the most commonly used in America operations. Use the plus sign to add the minus sign to subtract an asterisk or stars. I like to call them to multiply, afford slash to divide a double asterisk or a double star to exponentially eight and a percent sign from module. Oh, you're probably familiar with most of the symbols in the previous table. However, the double star operator is for exponentially ation, which means to raise to the power off, for example, to Star Star four means to raise to the power of four. This is equivalent to two times two times two times two and results in an outcome of 16. The percent sign performs the module. Oh, operation. It simply returns the remainder. For example, 3% signed. Two is one because three, divided by two is one with a remainder of one form Andulo to return. Zero since four divided by two is to with a remainder of zero. Python allows you to perform mathematical calculations right in the interpreter. Here are a couple of simple calculations when you type in one plus two and head in ER, The python interpreter immediately returns the result of that operation, which is three. It acts pretty much like a calculator. You can also assign the resulting value of a mathematical operation toe a variable, as in this example on your screen. Let's just look at the first line. The result of one plus two will be stored in the variable named some. The remainder of the code creates more variables in stores. The output of those mathematical operations in those variables. Finally, at the bottom of the screen. We display those results using a series of print functions. Here is the output of the Python program. From the previous screen, we can see that the sum of one plus two, which is three, is displayed on the first line of output, even though the result of eight divided by two is Thean Deter. Four. You might have noticed that the floating point number 4.0, was in the output created by the previous example. The division operator performs floating point division and will always return a floating point number. Also be aware if you add an integer to a floating point number, the result will be afloat. This example demonstrates how you can even perform mathematical operations using variables some evaluates to three difference evaluates to 99. And on the third line, the variable new underscore number will evaluate to 102 because the value of the some variables three. When it's added to the value of the difference variable, which is 99. The result is 102. In the last two print statements, we perform calculations on variables there as well. This example creates a variable named quantity and assigns at the numeric value of three. It also creates a variable name quantity, underscore string and assigns it the string of three. Remember that strings are enclosed in quotation marks. Here. We've use single quotation marks, but you could have used double quotation marks as well. If you try to perform a mathematical operation against a string, you'll encounter an error. Just be aware that if you surround a number and quotes, it becomes a string to convert a string into an integer used the I. N. T. Or in function and pass in the string to convert. This time you'll notice that we did not get an error because we used all numbers to perform our calculation. The result of ent quantity underscore. String is the integer 33 plus two equals five, which is stored in the variable total. Finally, that value is printed to the screen using the print function to convert a string or an integer into a floating point number, used the float function and pass in the string or integer to convert. Here, the output is 3.0 since the string three was converted to a floating point number and floating point numbers always contain a decimal place 17. Comments: comments are for the benefit of US humans. Python will ignore any comments it encounters. Comments give you a way to document your code. It can help summarize what is about to happen in a complex piece of code. For example, if you are a fellow programmer, need to look at the code at a later date. It can quickly explain what the intention of the code was when it was written. A single line comment is prefixed with an octo Thorpe, also known as a pound sign, a number sign or even a hash. The first line of code on your screen is an example of a single line comment. However, you can chain multiple single line comments together simply by starting each line with a pound sign. You can also create multi line comments using triple quotes. The comment begins right after the first set of triple quotes and ends right before the next set of triple quotes. Even though the comment begins right after the first Triple quote, you can start your text on the line below or even several lines below. If you wish, you can even create a single line quote using the triple quote syntax is shown on your screen. Just remember to start with triple quotes and end with triple quotes going back to our What does the cat say exercise from a previous section? Let's add in some comments to make her code clearer. These comments are simply describing what the code is intended to do. For example, get the input from the user. The next comment is determined. The length of the input and the final comment is make the border the same size as the input . The functionality of the program hasn't changed since Python ignores comments. However, If we come back to this code at a later day, we can quickly tell what it's supposed to do by reading the comments. 18. Numbers and Math - Section Summary: in this section, you learned that unlike string numbers required no special decoration, and you could use them directly in your source code. If you enclose a number and quote, it becomes a strain. Anything enclosed in quotes is a string to convert a string to an integer used. The end function, likewise to convert a string to a floating point number used the float function. Finally, we talked about comments in this section and how single line comments can begin with an octo four, also known as a hash sign or a pound sign or a number sign. Also, you learn that multi line comments are enclosed in triple quotes. 19. Booleans and Conditionals - Section Overview: In this section of the course, you'll learn about the Boolean data type. You'll also be introduced to compare Attar's as well as a boolean operators. Next, you'll learn about the order of operations and how you can explicitly control the order of operations. We'll also talk about creating an identifying code. Blocks and python finally will wrap things up in this section by covering condition ALS and how you can use them to make decisions in your python programs. 20. Booleans: But Julian is a data type that can have on Lee two possible values, either true or false. You can think of a Boolean as either being on or off. There is no in between with billions to assign a boolean to a variable Hughes variable name equals Boolean, where Boolean is either true or false. Do not use quotes around true or false. Remember that quotes of her strings in this sample code on your screen. The first line starts with a variable named a underscore Boolean and its assigned the Boolean value of True. The second Line and the second variable. The other Boolean, is assigned the Boolean value of false. Next, we print the first variable a boolean, and next we print the other Boolean variable. The output is displayed at the bottom of your screen. The output in this case is true, followed by false. The following six operators compare one numeric value with another and result in a Boolean . The double equal signs is the equal to comparator. The greater than signed test for greater van, the greater than symbol followed by equals means greater than or equal to the less than sign. Of course, means less than and the less than sign, followed by equals means less than or equal, and finally an exclamation mark, followed by an equal sign. It's the not equal Comparator when you see something like one equal equal to you can think is one equal to two. If the answer is yes, then it's true. And if the answer is no, then it's false. Let's run the numbers one and two through all six. Comparator Inter actively in the Python Interpreter. First, we'll do one equal equal to, and we can ask herself is one equal to two in. The answer, of course, is no. So the value should be false. Let's hit, enter and see what Python has to say about it. And indeed, the Boolean of False is returned because one is not equal to two. Let's do one greater Bantu that is also false. One greater than are equal to two is also false, and we'll do one less than two. So if we ask yourself is one less than to the answer is yes, it is so. Therefore, the answer or the Boolean that will be returned is true. Let's use one greater than or equal to two. And again that is true, and one not equal to two is true as well. Boolean logic is used extensively in computer programming. The Boolean operators are and or and not they could be used to compare two statements or negate a statement like Comparator is the result in a Boolean the and operator evaluates to True. If both statements are true, otherwise it evaluates to false the or statement evaluates to true. If either of the statements is true, otherwise, it evaluates to false the not operator evaluates to the opposite of the statement on your screen is displayed a truth table. This truth table demonstrates Boolean operators and their results. For example, in the top left hand side, we see true and true evaluates to true. And at the very bottom of our screen, we can see that not false evaluates to true. Let's evaluate two statements with a Boolean and operator. The first statement is 37 greater than 29th and it evaluates to true. The second statement is 37 less than 40 and it also evaluates to true Let's look at 37 greater than 29 37 less than 40 that evaluates to True because true and true evaluate to true. Let's look at 37 greater than 29 or 37 less than 40. The result is true because true or true is also true. The not Boolean operator evaluates to the opposite of the statement. Let's look at 37 greater than 29. That is true. Not 37 greater than 29 is false because not true is false. The order of operations for Boolean operators is a not and or, for example, true and false or not. False is true. First, not false is evaluated, and it's true. Next, true and false is evaluated, and it is false. Finally, false or true is evaluated, and that is true. To control the order of operations. Use parentheses. Anything surrounded by parentheses is evaluated first and as its own unit. So the first line of true and false or not false is the same as parentheses, true and false. Close parentheses or open parentheses, not false close parentheses. It's also the same as open parentheses, open parentheses, true and false, close parentheses or open parentheses. Not falls, close parentheses, close parentheses, using parentheses. Not Onley allows you to get away with not memorizing the order of operations, but more importantly, it is explicit and clear. 21. Conditionals: the if statement evaluates to a Boolean expression, and if it is true, the code associated with it is executed. Here's an example on your screen. Since the Boolean expression 37 less than 40 is true, the code indented under the F statement, is executed. This indebted code is called a code block. All the statements that are at the same distance to the right belong to that code. Block. A code block can contain one or mawr lines. The block of code ends when it is followed by a line that is less indented than the current code block. Also, code blocks can be nested by convention code blocks air indented four spaces, but this is not strictly enforced. Python allows you to use other levels of indentation. For example, using two spaces for indentation is the next most popular choice after four spaces be consistent if you decide to use two spaces for indentation than used to spaces throughout your entire python program. However, I strongly recommend that you follow the conventions unless you have a good reason not to do so. Also, if you encounter this error on your screen, you have a problem with spacing Let's get back to the if. Statement notice that the line containing the if statement always ends in a colon since age greater than or equal to 35. This false. The python code, indented underneath the of statement is not executed. The final print function will always execute because it is outside of the if. Statement notice that it's not invented, so it's not included in the if statement code block. The if statement can be paired with else. The code indented under else will execute when the if statement is false. You can think of the if else statement, meaning. If the statement is true, run the code underneath. If otherwise, run the code underneath else in this example on your screen. Since age equals to 31 31 with greater than or equal to 35 this false, the code block under else gets executed. The output issue are not old enough to be the president as well as the final line, which reads. Have a nice day. You can evaluate multiple conditions using LF which is short for else if, like if and else you need to end the line of the LF, statement with a colon and indent the code to execute underneath it in the example on your screen. The if statement the F age greater than or equal to 35 his false so that presents statement is not executed. The next test is, LF age greater than or equal to 30. That evaluates to true because 31 is greater than 30. Therefore, the code block underneath that statement is executed. There's only one line in that code block, and it's a print statement that says you are old enough to be a senator after that block of code is executed, it goes to the end of the if statement and then continues on with the program. So then print have a nice day is executed. The code, indented under the else portion did not get executed because we didn't make it to that point. In the if statement, the code block under else will only execute if all of the preceding if and LF, statements evaluate to false. Also to be really clear here, the first IFOR LF statement to evaluate to true will execute and any of the remaining LF or else blocks will not execute here is one final program to illustrate this concept and this example. Age is set to 99 the if statement of age greater van or equal to 35 evaluates to True because 99 is greater than or equal to 35. And so the print statement you are old enough to be a representative, senator or the president will be printed. All the other code in the If statement will not execute. It will be skipped. The next command to execute is print. Have a nice day. Here's the output of that python code. 22. Booleans and Conditionals - Section Summary: In this section of the course, you learn that billions are either true or false. You also learn that comparatives, compare one, do merit or value with another and result in a boolean. Also, we talked about the Boolean operators which are and or and not these operators compare to statements or in the gate a statement and also result in a Boolean. If you want to control the order of operations, use parentheses. You also learned that a code block is a section of code at the same level of indentation. Finally, we talked about condition ALS, including if if else and if. LF l statements. 23. Functions - Section Overview: in this section, you'll learn about functions when to use them and how to create your own next to learn about parameters and how you can pass data into a function. We'll also talk about how to document your functions, as well as how to view the documentation for the built in python functions as well as functions created by other programmers. Finally, you'll learn how to return data from the functions that you create. 24. Functions, Part I: There's a concept in computer programming known as dry, which stands for Don't repeat yourself. Functions allow you to write a block of python code once and use it many times. Instead of repeating several lines of code each time you need to perform a particular task or function, simply call the function that contains that code. This helps in reducing the length of your programs, and it also gives you a single place to change, test, troubleshoot and document a given task. This makes your application easier to maintain. To create a function used the deaf keyword followed by the name of the function, Then a set of parentheses must follow the function name if you're function accepts. Parameters include names of those parameters within the parentheses, separated by commas. Finally, in the function definition line with a colon, the code block that follows the function definition will be executed any time the function is called on the screen. At the bottom, you can see a very simple function. If you were to execute this code, no output would be displayed because the function was defined but never called. When calling a function, be sure to include the parentheses so the code on your screen defines this say hi function , and then it calls the function by listing the name of the function followed by parentheses . And the output is high because that is the code block that is executed in the SE hai function. Also, be aware that a function has to be defined before it can be called. Define your functions at the top of your python program. Here's what happens if you try to use a function that is not yet defined and this example we call say hi before we even define it. And then we get an air saying that say hi is not defined. Let's extend this function to accept a parameter. You can think of parameters as variables that can be used inside of the function. The format is deaf function name and then the parameter name in parentheses, followed by a colon To say hi. Function in this example has one parameter called name the first time we call Say hi. In this example, we passed the stream Jason to say hi. That string is assigned to the parameter name. Now we can use name just like we would use any other variable inside our function. Next we call say hi with a string everybody, and as you can see, the output on the bottom of the screen is high. Jason, Hi, everybody. Once you've defined a parameter, the function expects and requires a value for that parameter. If one is not provided, you'll encounter an error. When we run the code on the screen, you can see that the error says that it's missing one required positional argument to make the parameter optional set a default value for it, using the equal sign. So the format is deaf function name and within parentheses. The parameter name equals default value, close parentheses in a colon. So in this example, if we don't pass anything into the say hi function, name is assigned there. So the first time we call say, hi name is there, so the output is high there, and then the next time we call, say, high, we pass in one parameter, which is a strain called Jason and that outputs high. Jason functions can accept multiple parameters, simply include them within the parentheses of a function definition, and separate them with a comma when calling the function supply the arguments and separate them whether comment as well. So in this example, when we call, say high, we provide a string in this example Jane, then a comma. And then we provide the second argument. Dough also a string. When we call, Say hi in this manner first is assigned the String Jane and Last is assigned the string Go . And of course, the output from the printed statement is Hi Jane Doe. The parameters accepted by a function are also called positional parameters because their order is important. Notice that Jane was associated with First and Doe was associated with last. You can also explicitly pass values in tow, a function by name when calling the function supply the parameter name, followed by the equal sign and then the value for that parameter. When using name parameters, Order is not important. As you can see on your screen, we call, say hi twice and the first time we use first as the first parameter, and the next time we used last is the first parameter. However, since we've explicitly defined what their values are, it doesn't matter what the order is required, and optional parameters can be combined as in this example on your screen when we call, Say hi with one argument, that data is associated with the parameter first. The first time we call, say high. We only supply one piece of data, which is a string that says Jane First is assigned the value of Jane and then last is assigned the value of dough. Since we didn't specify that in our call to the function, the output in that instance is Hi, Jane Doe. The next time we call, say high, we use two strings. One will be associated with First John and the next one Coltrane will be associated with last, and the output is high. John Coltrane. 25. Functions, Part II: by convention. The first statement of a function is a Documentation String or DOC String for short to create a dock string, simply surround tax with triple quotes. This DOC string provides a quick summary of the function. When writing the doc string, Ask yourself, What does this function do or why does this function exist? You can access this doc string by using the built in help function. Pass in the name of the function. You want to learn more about to help type. Q. To exit the help screen in the example on your screen, we call help on this say hi function when calling help in passing in the function, say hi, the function definition off say hi is displayed to the screen as well as the doc String. Not only can functions perform a task, they can return data using the return statement, you can return any data type that you like. Once the return statement is called, no further code in the function is executed. Here's a function that returns a string. If the number that has passed into that function is even, it returns the string, even if it's determined to be odd. It returns the string odd. In this example, we assign the output of the odder, even function to the otter, even string variable. Then we print the contents of that variable using the print statement and this example seven. Izod So odd gets printed to the screen. Here is a very similar function that returns a Boolean instead of a string. I've modified the code a little bit just to change things up and show you that you don't have to assign the output of a function to a variable. You can use that output directly in a printed statement. If you'd like a swell, you can create functions that call other functions. An example of doing this is listed on your screen. First, the get name function is defined. Then the same name function is defined. And finally, the get and same name function is to find that last function. Actually calls get name and then say name. So the last line of code when we call, get and say name that function calls to get name function and stores what is returned in the name variable. Then it passes in name into the same name function. At that point the name is printed to the screen. Here's an example run of that program. This is what would happen if I just typed in my name Jason and hit Enter. It would display who are name is Jason. 26. Functions - Section Summary: a function is a block of reusable code that performs in action and can optionally return data. If you find yourself writing the same piece of code in multiple places in your program, that's a very good sign that you need to use a function. Be aware that when you use a function, it has to be defined before it is called. The basic syntax were defining. A function is listed on your screen. It's deaf, followed by function name and then in parentheses. You can include parameters and always in the function definition. With the colon, a function can accept one or more parameters and to make a parameter optional supply a default value for that parameter. You also learned about documenting your functions. You can supply a dock string as the first line of your function that DOC string will be displayed when you run help. On that function, the return statement exits the function and passes back. Whatever follows that return statement, you can use the built in help function to get help with an object. When supplying a function to help the DOC stream contained within that function is displayed. You can use the help function on your functions as well as the built in functions and python 27. Lists - Section Overview: in this section, you'll be learning all about the list data type. You learn how to create and manipulate lists as well as how to search for items in a list. We'll also be talking about how to gracefully handle exceptions in your python programs. Next, we'll look at slices and how to extract select pieces of data from a list. You'll also learn how to generate a series of numbers using ranges. Finally, you'll learn how to perform the same task or set of tests multiple times by using four and wild loops. 28. Lists: so far in this course, you've learned about the string in Teacher Float and Boolean data types. Ah List is a data type that holds an ordered collection of items, thes items or values. Contained in a list can be various data types themselves. You can even have list within lists. Lists are created using comma separated values between square brackets. The format is list name equals open bracket and then a list of items separated by commas and finally, a closing bracket to create an empty list. Just used the list. Name equals open bracket. Close bracket items in the list can be accessed by index. List indices are zero based, meaning that the first item in the list has an index of zero. The second item has an index of one etcetera. To access an item in a list using an index and closed the index and square brackets immediately following the list name. In the example. On your screen, we create a list with three items in it, the first item being man, the second item being bare and the third item being pig. We assign that list to the variable animals, and then we can access each item in that list using an index. So first we print animals at index zero, which returns man, then animals that index one which returns, bear and finally animals at index to which returns pig. Not only can you access values by index, you can also set values by index. First we create a list in the first value is man the second bear in the third pig. The print statement shows that the first item at index zero is indeed man. Now we set animals at index zero equal to cat. And when we print animals at index zero, it shows that indeed that value is now cat, you can access items starting at the end of the list by using a negative index. The negative one index represents the last item in the list. Negative two represents the second to the last item and so on. So here we print a list of man bear pig in reverse order by printing animals at index negative one, which is the last item on the list animals at index negative two, which is the second the last item on the list. And finally, animals that index negative three, which is the third item from the end of the list to add an item to the end of a list, used the upend method and pass in the item to add to the list. Here we start out with a list with three items man, Bear, pig. Then we use animals dot append to upend a string of cow. Tow our list If we print the last item on our list, which is located an index negative one. It indeed shows that the last item in the list is cow. To add multiple items to the end of the list used the extend method. The extend method takes a list. You pass in a list by name, or create one by surrounding a list of items within brackets. In the example on your screen, we start out with a list with three items man, bear, pig and the second line of code on your screen. We pass the list of cow and duck to the extend method of the animals list. When we print that to the screen, we can see the list is now man, bear, pig, cow and duck. Next, we create a new list that contains horse and dog. We store that list in the variable more animals this time when we used the extend method to animals were going to pass in the variable. More animals and the last line of code prints are new list of animals. The complete list is now man, bear, pig, Cal, Duck, horse and dog. You can also add a single item at any point in the list by using the insert method. Pass in the index where you want to add the item, followed by a comma and then the item itself. All of the existing items in the list will be shifted by one and the example on your screen . We start out with a list of animals man, Bear, pig. And then we used the insert method and we pass it Index zero and the string horse. When we print animals, we can see that horses Now it index zero and the other three items in the list have been shifted up. Next we call animals. Start insert in passing an index of two and a value string of duck. When we print this new list of animals, we can see that duck is now at index to, and bear and pig have been shifted up one 29. Slices: to access a portion of a list called a slice specify two indices separated by a colon within brackets. The slice starts at the first index and goes up to, but does not include the last index. If the first index is omitted, zero is assumed. If the second indexes omitted, the number of items in the list is assumed on the example on your screen, we create a list of animals. Next, we take a slice of the animals list and store it, and some underscore animals. The slice we take is from Index one to index for this list will have three items in it. That's because the list starts at one and goes up to four, but it doesn't include for so the animals that index one is bare index to is Pig index three is cow. Those will be the items at slice one coal and four in the animals list. One way to extract the 1st 2 animals from the list is to use animals bracket zero coal and to close bracket again. This means take the animal at Index zero and index one and stored in the variable. First underscore to remember that if we omit the first index, it is assumed to be zero, so zero colon to is the same. It's just colon to here's the output of the execution of that program. Again, the some animal slice is one colon four, which equates to bear pig cow. And then the last two examples contain the 1st 2 items in the list. Here's another example will use the same list of animals this time will extract the last two animals in our list. The slice four Colon six represents the last two items on the list. Since the last two items on the list are index four and five, remember that the last index specified is not included as part of the slice. Another way to extract the last two animals in our list is to use a negative index negative , too, so that means start from two from the end of our list. If we don't specify an index after the colon, the length of the list is assumed. This is a convenient way to extract items from the end of the list without having to know the exact number of items in the list. Here's the output from the execution of that program. And indeed, you can see that the last two items in the list are printed to your screen. You can also use slices with strings. As a matter of fact, you can think of strings is nothing more than a list of characters. Here we take a slice of horse at Index one and two, and then we print that to the screen. So the characters that are at Index one and two R O. R. And that is what gets printed to the screen. 30. Exception Handling: the index list method accepts of value as a parameter and returns to the index of the first value in the list. For example, if there were two occurrences of bear in the animals list passing in bear to animals, dot Index would return the index of the first occurrence of bear. And this example bear is at index one. If the value is not found in the list, Python will raise an exception. Here's an example where we're trying to find the index of cat in our animals list. However, cat doesn't exist. The error that Python reports to us is that cat is not in the list. An exception is typically an indication that something went wrong or something unexpected occurred in your program. If you don't account for or handle exceptions in your program, Python will print out a message explaining the exception and then halt the execution of the program. Here's an example of a nhan handled exception. The's messages can be extremely useful and correcting mistakes in your code. As you can see from the example, Python displayed the line number and code that raised the exception to prevent python from exiting when it encounters an exception. You need to tell your program what to do when it encounters one. Surround any code you faint may raise an exception and a try except block. Let's update the previous example with a try except block. If an exception is raised while executing the code in the try block, the code in the except Block is executed. If no exception is encountered in the tri code block, the code in the except code block is skipped and not executed. Since CAT is not in the animals list. A call to animals DOT index would result in an exception, since the exception was raised in the try block the block of code following the except statement gets executed. In this example, we assigned the cat Underscore Index variable to a string that says no cats found. When we execute this program, it executes cleanly and prints to the screen. No cats found 31. Loops: if you want to perform some sort of action on every item in a list. Use of four loop The format is four item variable in list name colon, followed by a code block. Like if statements and function definitions, the four statement ends in a colon, and the code block that follows the four statement will be executed for every item in the list. Essentially, what happens is that the first item in the list at list index zero is assigned to item underscore variable and the code block is executed. The next item in the list. The item at index one is assigned to the item underscore variable and then the code block is executed. This process continues until the list is exhausted. If there are no items in the list, the code block will simply not execute. Here is an example that prints the upper case version of every animal in the animals list. The first time the code bought gets executed, Animal is assigned the value of man. Since man is the first item in the list of animals, the second time, the block of code gets executed. Animal is assigned the value of bear since bear is the second item in the list and finally the third time the block of code gets executed. Animal is assigned the value of pig. In addition to the four, loop, python has a wild loop. The format is while then some condition, followed by a colon. As long as the condition evaluates to true, the code block following the wall statement will execute. Typically, the code block will alter a variable that is part of the condition. At some point, the condition will evaluate to false and the program continues after the wild loop. If the condition never evaluates to false than you have an infinite loop to halt the execution of a python program type control see. So if you accidentally create an infinite loop, you can break out of it with control. See the example code on your screen creates an index variable to store an inter and will be used as the index of the animals list. The while loop executes. While the index is less than the length of the animals list during the code block, the index variable is incriminated by one. The plus equals operator adds a value to the variables existing value and assigns the new value to that variable. So using index plus equals one will increment the index variable by one. When the code on your screen is executed, it simply prints each item in the list. 32. Sorting Ranges: to sort a list called the sort list method on the list. Without any arguments, it will reorder the current list. However, if you want to create a new list, use the built in sorted function and supply a list as an argument. The sorted function will return assorted version of the list. In the example. On our screen, we create a small list of animals. Next, we create a new list called Sorted Animals by using the sordid built in method and passing in the animals list to it. When we print the animals list to the screen, we have our original list, and then when we print assorted animals list, we can see that it is sorted alphabetically. Next, we alter the list itself by running animal Stott sort now that when we display the contents of the animals list to the screen, we can see that it's alphabetically sorted to concoct innate or combine two or more list used the plus sign. In this example, we can Katyn, Eighth E Animals and Mawr Animals list into a new list called All Underscore Animals. When we print the all animals list to the screen, we can see that the Man Bear Pig list was attitude or contaminated with the cow Dark horse list to determine the number of items in a list used. The land built in function and pass in a list. Here are original list of animals. Contains three items, so when we print the length of animals, it returns. Three. If we were to upend another item to the list like Cal, for instance, then the length of the animals list has grown by one and therefore print Lynn Animals returns for the built in range function, generates a list of numbers and is often paired with the four statement. This comes in handy when you want to perform in action a given number of times or when you want to have access to the index of a list. The range function requires at least one parameter that represents a stop by default. Rains generates a list that starts at zero and continues up to, but not including the stop. So to generate a list of three items, use range and pass in the number three. The list starts at zero and will contain the numbers 01 and two. You can specify the start as well as the stop to do this first pass in the start, followed by a comma, and then specify the stop to start a list at one and stop it. Three. Use range one comma three. This will generate a list that only contains two items the numbers one and two. In addition to the start and stop parameters, the range function can also accept a step parameter. When using all three parameters, the list will start at the start value stop just before the stock value and increment the list by the step value. If no step value is specified, as in the previous examples, its default value is one. Here's how we can generate a list that includes all of the odd numbers from 1 to 10. First we pass in a start of 12 range, and then we specify 10 as the stop. And finally, we specify to as this step. Here's an example of using the range function with a list to print every other item in that list. Here we specify zero as to start the length of the list as the stop and finally to as the step so you can see on our screen that the first item in the list at Index zero is printed . And then the item at index to is printed pig and then the item at index four duck. And then finally, the item at Index six is printed witches dog. 33. Lists - Section Summary: in this section of the course, you learned how to create lists by using a comma separated set of values between square brackets. You also learn that items in a list can be accessed by an index. List. Indices are zero based, meaning that the first item in the list is at index zero. You can access items from the end of the list by using negative indices. The last item in a list is that index negative. One. You can use the upend or extend bliss methods to add items to a list. If you want to access just a portion of a list, you can use a slice. The list index method accepts of value as a parameter and returns the index of the first value in the list. If that item is not in a list and exception will be thrown, you can loop through a list using a four loop. Another type of loop we discussed was the Wild Loop, and that it executes is long as the condition evaluates to true. We also talked about two ways to sort of list. Using the sort list method sorts the list itself, or we can use the Sorted Function, which returns a new sorted list. The built in range function generates a list of numbers. Finally, in this section of the course we talked about unhand Aled exceptions and how we can gracefully handle those using try except blocks. 34. Dictionaries - Section Overview: in this section of the course will be focusing on dictionaries. First, we'll talk about what dictionaries are, and then we'll move right into creating them. Next, you'll learn how to add and remove items from a dictionary. From there will talk about searching the contents of dictionaries. You'll also learn how the nest dictionaries, and finally, you'll learn how the loop through all of the items in a dictionary. 35. Dictionaries, Part I: The dictionary is a data type that holds key value. Pairs the's key value. Pairs air called items you'll sometimes hear dictionaries refer to his associative arrays, hashes or hash tables. Dictionaries air created using comma separated items between curly braces. The items starts with the key is then followed by a colon and is concluded with a value. The format is dictionary name equals open curly brace aqui colon, a value comma, the next key colon, the next value and so forth and then finally ends with a curly brace. If you like to create an empty dictionary, simply use the dictionary. Name equals open curly brace and then the clothes. Curly brace items in a dictionary can be accessed by key. To do so, enclosed the key and brackets immediately following the dictionary name. In the example on your screen, we created Dictionary and assign its contents to the contacts. Variable. This dictionary has two items. The first item has a key of Jason with a value of 555 deaths. 0123 The second item has a key of Karl, and its value is 5550987 In order to access the value associated with the key. Put the key inside brackets immediately following the dictionary name on the second line of code on your screen. You can see that that Jason's underscore Phone variable contains the value associated with the key of Jason in the contacts dictionary. Likewise, on the third line, the Carl's Underscore phone variable will contain the value associated with a Karl Key in the Contacts dictionary. The last two lines of code here on the screen simply print those phone numbers to the screen. Not only can you access values by key, you can also set values by key. In the second line of code on your screen, we set the value associated with the Jason Key in the Contacts Dictionary to be 555-0000 Next we extract that value and stored in the Jasons Underscore phone variable and the last line of code prints that new value to the screen. You can add new items to a dictionary through assignment. As you can see the first line of code, we have two items in our dictionary. The keys are Jason and Carl. If we want to add a key of Tony to the dictionary. We simply enclosed Tony and brackets, followed by the dictionary name, which in this case is contacts and then assign it value, which is 555-0570 On the third line. We just print the context to the screen, and you can see that indeed, Tony was added to the dictionary. Now we have three keys. Jason, Carl and Tony. Finally, we print the length of the Contacts Dictionary. The land function also works on dictionaries, just like it does on lists, and it reports the number of items within the dictionary. You can also remove items from the dictionary. You can do this by using the Dell statement. You simply supply the dictionary name followed by the key. You want to delete within brackets and pass that to the Dell statement and this example We delete the item that is associated with the Jason Key in the context dictionary. You can see we start out with two items. We delete the Jason item and then when we print the dictionary to the screen and D. Jason has been removed and all we're left with us. The Carl Key and associated value in the dictionary. The value stored in a dictionary do not have to be of the same data type and the example on your screen. The value for the Jason Key is a list. While the value for the Carl Key is a stream, you might have noticed that the creation of the Contacts Dictionary looks slightly different in this example. When assigning the items to the Context dictionary, additional spaces were used to improve readability as long as the sin taxes followed, Python will ignore the extra spaces in this case. In this example, we have one key value pair or one item per line in the Contacts dictionary. This makes the code easy to read. Finally, at the bottom of your screen, there are four prints statements which print out the data, and you can see that the list associated with the Jason Key was printed to the screen, while just the string associated with the Karl Key was printed to the screen. Accessing the value associated with the key in a dictionary acts in the exact same way as if you are working with that value directly. For example, let's use a four loop for all of Jason's phone numbers in the list. Here, you can see that the print statement was run against each one of the items in the list and is displayed to the screen. If you want to know if a certain key exists in the dictionary, you can use the value in dictionary name dot keys, syntax. If the value is a key in the dictionary, true is returned. If not, then false is returned. First, we start out by creating the Contacts Dictionary. Next, we use an if statement. If the if statement is true, the code block associated with it will be executed. If not, it will be skipped. And this example? The first if statement is true, since the Jason Key does in fact exist in the contacts dictionary. The second, if statement, is false because the Tony Key is not in the dictionary. Thus, that code block following that statement does not get executed, since the value associated with the Jason Key is a list you can act on it just like a list . So accessing Index. Zero of the list associated with the Jason Key in the Contacts Dictionary returns the first value in that list here is the output of the execution of that program, just like we expected. The first item in the list associated with the Jason Key in the Contacts Dictionary is printed to the screen. The Values Dictionary method returns A list of values in the dictionary used the value in list syntax to determine if the value exists in the list. If the value is in the list, true is returned. Otherwise false is returned. And this example, the value of 555-0987 is in the dictionary, so true is returned. 36. Dictionaries, Part II: one format for looping through items in a dictionary is for key variable in dictionary name . The code block that follows that four statement will be executed for every item in the dictionary to access the value of the item. In the four loop used the pattern of dictionary name, followed by the key variable name in brackets. It's very common to name dictionaries using a plural noun such as contacts. The typical format for the four loop uses the singular form of the dictionary. Name is the key variable, for example, for contact in contacts or four person, and people, unlike list dictionaries are unknown ordered the four loop guarantees that all of the items in the dictionary will be processed. However, there is no guarantee in which order that they'll be processed. In the example on your screen, we simply loop through the contacts dictionary and print out the value associated with each key. You can also use two variables when defining of four loop to process items in a dictionary . The first variable will contain the key, while the 2nd 1 will contain the value in the example on your screen. The person variable will be assigned the key from the contacts dictionary, while the phone underscore number variable will be assigned the associative value. Note that this code is functionally equivalent to the previous example, since values in a dictionary can be anything you can nest dictionaries and this example, names are the keys for the contact dictionary. While phone and email are the keys used in the nested dictionary. Each person in this contact list has a phone number and an email address. Pay close attention to the location of Coghlan's question marks. Commas embraces using additional whitespace. When coding these types of data structures can help you better understand the data. If, for example, you want to know Jason's email address, you can retrieve that information using contacts followed by the Jason Key and brackets, followed by the email key in brackets. The code on your screen is a continuation of the code on the previous screen. It loops through the Contacts Dictionary and prints out the phone number and email address for each person in the contacts Dictionary. 37. Dictionaries - Section Summary: in this section of the course you learned about dictionaries and how they hold key value pairs called items. You also learned how to access the value stored in a dictionary by key. Next, we talked about adding and changing values in a dictionary through assignment. From there, we talked about deleting items from a dictionary using the Dell statement. You also learned how to determine if a key exists in a dictionary using the value and dictionary name dot value Syntax, which returns a Boolean. Also, the Values Dictionary method returns a list of the value stored in that dictionary. Next, we looked at looping food dictionaries, and finally we talked about how dictionary values can be of any data type, including other dictionaries. 38. Tuples - Section Overview: in this section, you'll learn about the to pull data type in python. You'll learn when to use them, how to create them and how to delete them. Next to learn how to convert a to pull into a list and how to convert a list into a to pull , we'll also talk about the special ways you can use variable assignment with two bulls. Finally, you'll be introduced to even Mawr of pythons built in functions. 39. Tuples: A to pool is an immutable list, meaning once it's defined, it cannot be changed. With normal lists, you can add, remove and change the values in the list, but with two pools, you can't. Two pools like lists are ordered, and the values in the to pull can be accessed by index. You can perform many of the same operations on A to pull that you can on a list you can iterated over the values in a to pull with a four loop, you can concoct innate two pools. You can access values from the end of the to pull using negative indices, and you can access slices of a too full. Two pools are created using comma separated values between parentheses. The format is to pull name equals, open parentheses, item comma, the next item and so on until there are no more items you want to define in the to pull and then the close parentheses. If you only want a single item in a to pull, that single item must be followed by a comma. The format is to pull name equals, item comma, close parentheses, two polls air great for holding data that will not or should not change during the execution of your program, using A to pull insurers that the values air not accidentally altered, for example, the days of the week should not change during an execution of your program. The code on your screen starts by storing a to pull in the days of the week. Variable This to bill contains seven values online to we access the first value in the to pull by index like lists. Two pools use zero based indices. Next, we print the value to the screen and then print a blank line. Finally, we looked through there to pull printing out each item. The output will include all seven items, but it's cut off on your screen here. This example really demonstrates how to pools can be treated like lists. The biggest difference between A to pull and a list is that the to pull is a mutable, meaning you can't modify it. If you were to try to change the value in a to pull, we will encounter an error here. The Python interpreter tells us that two bulls do not support item assignment, even though you can't change the values in a to pull. You can remove the entire to pull during the execution of your program. By using the Dell statement. In this example, we create a to pull and display it to the screen. Next we delete the to pull with a Dell statement. Finally, just to demonstrate that the to pull is no longer available, I try to access it and an exception is thrown to create a list from A to pull, used the list built in function and pass in the to pull to create A to pull from a list used the to pull built in function, the built in function type reveals and objects type. In this example, we first create a Tupelo online one. Next we pass in that to pull to the built in list function and store that list in the weekend list. Variable. The next two lines used the type function to display that types of the objects Here. We're just confirming that the two pool is a terrible and that the list is a list. This example starts with a list on line one. Next we create a to pull bypassing in that list to the to pull built in function. Finally, we print the objects type to the screen. If you want to perform some action on every item in a tube, will use a four loop the format ISS for item variable and to pull name. You'll notice that the line ends in a colon. Next, you follow this line with a block of code that you want to execute on each item in the To pull. This example demonstrates how toe loop through a to pull first, a two bowl is created. Next, we use a for loop, just like we would with the list. This four loops simply prints each item in the to pull to the screen. You can use to pools to assign values to multiple variables at once. In the example on your screen, the variable sat and sun are assigned the weekend days from the weekend days to pull. We print out the contents of each variable to demonstrate that this method does indeed work . The sad variable contains the Saturday string and the sun variable contains the Sunday string you can also use to pull assignment with lists. Here we assign the first value in the list to the phone variable and the second item in the contact info less to the email variable. Then we display that information to the screen. To pull assignment can be used with functions as well. For example, you could create a function that returns to to pull and assign those values to different variables. This example uses the built in Max and men functions. The Max Built in Function Returns, the largest item that has passed in the men built in function returns, the smallest item that has passed to it. The higher low function returns a two bowl containing the highest and lowest number of the list that was passed into the high and low function. We create a variable called lottery numbers in a sign, a list of numbers to it on the next line. The high and low function is called with the lottery numbers as an argument. The first number returned by the function will be stored in the first variable in the to pull, which is highest. Likewise, the second number will be stored in the second variable, which is lowest. We print the values of these variables to the screen with a couple of print functions, you'll notice that 42 is the highest number, and it's printed first and four is the lowest number in that list, and it is printed on the last line you can use to pull assignment in a four lupas Well. In this example, the contacts list contains a series of two poles. Each time the four loop is executed, the variables name and phone are populated with the contents of A to pull from the contacts list. The result of running this code is that the name and phone number for each item in the list is displayed to the screen. 40. Tuples - Section Summary: but to pull is an immutable list, meaning once it's defined, the values contained in the to pull cannot be changed. Even though you can't change the items within a two bowl, you can remove the entire to pull from your program to do that. The Lita to pull with the Dell statement If you want to convert a to pull into a list used the list built in function. If you want to convert a list into a to pull, pass it into the to pull built in function. We also talked about to pull assignment and how you can use it to assign values to multiple variables at once. We also talked about using to pull assignment in four loops. Finally, you learned about the max built in function that returns the largest item that is passed to it. And you also learned about the men built in function, which does the opposite and returns the smallest item that has passed to it. 41. Files - Section Overview: In this section, you'll learn how to store and retrieve data from files. You'll be introduced to file objects in several file object methods that will allow you to read and write to files as well as other common operations. You'll also learn about a string method that you'll find yourself using when reading from files. We'll talk about how toe loop through files one line at a time. Next to learn about the various file modes and when to use each one well, briefly touch on the difference between Windows type files and UNIX type files that are used on UNIX. Linux and Mac systems finally will wrap up this section by gracefully handling exceptions that can be raised when working with files. 42. Files, Part I: you learned how to accept standard input by using the built in input function. You also know how to send data to standard output, which is typically the screen using the print function using standard input in output. Work well for certain types of applications, but if you want to keep data generated by your program, you will need a place to store that data. Also, if you want to retrieve save data, you'll need techniques to do that as well. One common place to store data is a file you can read, input and write output to a file, just like you can read input from a keyboard and display output on a screen. To open a file, use the built in open function to use the open function, simply passing a path to a file to it. The path can be an absolute or a relative path, and it includes the file name. An absolute path contains the entire path, starting at the root of the file system. Be that afford slash and macro Lennox or a drive letter in windows. An example of an absolute path is ford slash far slash log slash messages. Relative path will contain just the file name or a portion of the path which starts at the current working directory. An example. Relative path is log slash messages. This example assumes the current working directory is already in slash var. Using ford. Slash is is a directory. Separator will be familiar to those who have ever worked on a UNIX or UNIX like operating system. However, Python recognizes Ford Slash is even when running on the Windows operating system. The Windows operating system uses back slashes asked the directory. Separator, for example, of Valid Path and Windows would be C colon backslash log back slash messages back slash data dot text. However, in Python, you can use forward. Slash is an example would be Siegel and Ford's last users for its last Jason for its last documents. Finally, ford slash python dash notes dot txt. Finally on your screen, we show an example of using a relative path using Ford slashes. Here we pass in documents ford slash python dash notes dot txt to the open method, the open function returns of file object, sometimes referred to as a stream object, which can be used to perform operations on the file past to the open function to read the entire file at once used the read method on the file object. The re method returns a string containing the file's contents. In this example, we used the open built in function to open the etc host file. We assigned the file object to the host variable. Next, we store the contents of the host file into the host Underscore file. Underscore contents variable by using the read Method on hosts. Finally, we print the contents to the screen. In this example, the etc host file only contains one line which is displayed at the bottom of your screen. To modify this example to work on a window system will set the host variable to see slash windows slash system 32 slash drivers slash etc. Slash hosts. And remember that python allows us to use forward slashes in windows paths as well. At the bottom of your screen, you can see the contents of the host file on a window system when reading from a file. Python keeps track of your current position in the file. Since the re method returns the entire file, the current position will be at the end of the file. If you call read again, an empty string will be returned, since there is no more data to return at your current position in the file. To change the current file position, used the Sikh method and pass in a byte offset, for example, to go back to the beginning of the file. Pass in zero to the Sikh method to start at the fifth bite of the foul pass in five to the Sikh method. Note that in most cases the 10th bite will correspond to the 10th character in the file. However, in some cases it will not. For utf eight encoded files, you can encounter characters that are longer than one bite. You'll run into this situation when using con gee, Korean or Chinese, for example, to determine your current position in the file used. The tell method. The first line in this example opens the etc. Hosts file. Next, the current position is printed to the screen using the tell method. Since the file has just been opened, the position is zero. Next, the entire contents of the host file is red. Using the read method, the contents of the file of printed to the screen with the print method. Next, we check the current position in the file by executing the tell method again. This time, the position will be at the end of the file, as you'll see in the output on the next screen. Calling. Read again on the file will not produce any output because there's nothing else to read from the file. Since we are at the end of the file already, we return to the beginning of the file by passing zero to the Sikh method on the host file object. We display that position to the screen, and finally we reprint the contents of the file to the screen. Here is the output that I was describing. When you first open a file, the position will be zero. After you call the Read Method, that position will be at the end of the file. In this case, that position is 20. Notice that there is no output on the next line. That's because we called read on the file when it was already at the end of the file. Finally, we reset the position to be a zero with a Sikh method and reprint the contents to the screen. Using the read method, The read method can accept the number of characters to read. This example displays the 1st 3 characters of the host file. In this case, the 1st 3 characters are also the 1st 3 bites. When we call the tell Method on the file object, it reports that we are at Position three in the file. 43. Files, Part II: It's a good practice to close a file once you're done with it. If you're Python Application opens many files during its execution, this could lead to a too many open files error, too close a file. Use the clothes method on the file object. In this example, we open a file, read its contents printed to the screen and then close it. Each file object has a closed attribute that returns true. If the file is closed and false. If it is not, you can use this attribute to ensure a file is closed. This example uses an if statement to check if the Boolean return by the closed. Attribute is not true. If the file is not closed in the following code block is executed in this case, it simply closes the file. To automatically close a file. Use the with statement the format is with, followed by a call to the built in open function where you pass in the path to the file. You wish to open next, used the word as and follow it with a variable name you would like to use for the file. Object. Finally, you end the line with a colon after the file is opened, the code block that follows it is executed. When that code block finishes, python will automatically close the file. Also, if the code block is interrupted for any reason, including an exception, the file is closed. This example demonstrates automatically closing a file. First, we announced We're opening the file. Next, we use the with statement to open the host file and assign the file object to the host variable. From there, we start executing the code in the code block. First, we check to see if the file is closed and it's not closed since the with statement opened the file. Next we display the contents to the screen, which ends the code block. We print a nice message explaining that the file is closed, and finally, we confirm that it is indeed closed by checking the closed attributes on the host file Object, which correctly reports that the file is closed. To read a file one line at a time, use a for loop the format. ISS four line variable in file Object variable, followed by a code block. At the top of your screen is the contents of the file dot txt file. In the middle of your screen is the code that first opens the file. Next, we looked through the file one line at a time in print each line to the screen. The output of that code is displayed at the bottom of your screen. In the output. There is a blank line between each one of the lines in the file. This is because the line variable contains the complete line from the file, which includes a carriage return or New line character. Let's update the example and remove the trailing whitespace, including the new line and carriage return characters. By using the R Strip string method. Now you can see that the output is what we would have expected when opening a file. You can specify a mode to do so. First, pass in the file to open to the open built in function than follow it with a comma and then supply the mode. So far, we've been using the default mode of our, which opens a file and read only mode. If you want to write to a file clearing any of its existing contents, use the W mode. If you want to create a new file and write to it used the X mode. If the file already exists, an exception will be raised. Using the X mo prevents you from accidentally overriding existing files. If you want to keep the contents of an existing file in append or add additional data to it , use the A mode with both the W and A modes. If the file does not already exist, it will be created. If you want to read and write to the same file, use the plus mode. You can also specify if the file you're working with is a text file or a binary file by default all files or opened as text files unless otherwise specified. Simply append a T or B to one of the read or write modes. For instance. To open a file for reading and binary mode, use RB. Tow a pen to a binary file. Use a B text files contain strings while binary files contain a series of bites, said another way. Text files are human readable and binary files or not. Examples of binary files include images, videos and compressed files. To check the current Motiva file, use the mod attributes on a file object and this example, you can see that the default mode of our is used when opening a file. Now that you know about the different file modes, let's write some data to a file. It's Azizi is calling the right method on the file object and supplying that text you wish to write to the file. First, we open a file for writing by using the with statement so that it automatically closes when we're finished with it. Notice how we supplied a W s the second argument to the open function. Next, we use the right method and provide some text we call the right method again and supply even more text. Finally, we open the file again and read only mode and print its contents. The output, which is displayed at the bottom of your screen, might not be what you expected. The right method writes exactly what was provided to it. In this example. No carriage return or line feet was provided, so all the text ended up on the same line. The slash R sequence represents a carriage return, and the slash n represents a new line. Unique style line endings only contain the slash in character. American Lennox files use this type of line ending window style line. Endings can be created using slash r slash in let's try our example again. But this time, using a line feed character at the end of the line, you can see that slash in was provided at the end of the string. We pass into the right method at the bottom of your screen. The output is, as you would expect, the main thing to remember about binary files is that you are dealing with bites, not characters. The read Method accepts bites is an argument When dealing with binary files. Remember that the read method accepts characters when the file is opened. As a text file, this example opens up a picture of a cat in binary mode. We seek to position to using the Sikh method on the file object. Next, we read four bites from the file using the read method. Next we print to the screen the current file position, which is six. Finally, we display the motive. The file, which is R B working with anything that exists outside of your program, increases the chances for errors and exceptions working with files falls well within this category. For example, a follow you are attempting to write to maybe read only ah follow you are attempting to read from may not be available. In a previous lesson you learned about try except blocks. Let's put it to use here in this example Here, we attempt to store the contents of the contact dot txt file in the contacts variable. If an exception is thrown in this tribe block, the except block will be executed to continue gracefully in our program, we simply create the contacts variable with an empty string in the example output on your screen. The contacts dot txt file existed and was able to be read and resulted in a string with the length of 319. If the file couldn't be opened, the output would read zero, which is the length of the empty string assigned to the contact variable in the except block 44. Files - Section Summary: in this section about files you learn how to open a file using the built in open function. The open function requires a path to a file and optionally a file mode. If the motives admitted when opening a file that defaults to read, only you also learn how Ford Slash is can be used as directory separators even when you're working on Windows systems. If you want to return the entire contents of a file as a string called the Read Method On that file object to close a file, use the close file Object method. You learned how to automatically close a file by using the with statement. Next, we talked about how to read a file one line at a time, using a for loop. We also talked about removing the extra white space using the R Strip method. When reading text from a file, you also learn how to write data to a file using the right file object method. Next, we talked about how the read method behaves differently, depending on if a file was opened as a text file or binary file. When a file is opened in text mode, Read accepts characters when a file is opened in binary mode, it accepts bites. In most cases, a character will correspond to a bite. But that's not always the case. When using utf eight encoded files, you may encounter characters that are longer than one bite in length. Finally, we talked about how working with files can increase the chance that your program will throw an exception. You learn to plan for these exceptions by using, try and accept blocks. 45. Modules - Section Overview: in this section of the course, you'll be introduced to modules. You'll learn how to create your own modules and how to include existing modules in your python programs. Next, we'll look at a built in python function that allows you to view the contents of a module. You'll also learn about the module search path, when to modify it and how to do so. Finally, you'll learn about the Python standard library and how it can make your life easier as a programmer. In many cases, you can use the existing code in the Python Standard Library that takes care of low level details while you focus on what you want your program to accomplish. 46. Modules, Part I: Python modules are files that have a dot p. Why extension and can implement a set of attributes, methods and classes. A module can be included in another python program by using the import statement followed by the module name to import a module name. Time. Include an import timeline in your Python program. You can now access the methods within the time module by calling time dot method, name or attributes, sometimes called variables by calling time dot attributes name. Here's an example using the A S C time method and the time zone attributes from the time module. The time zone attribute contains the number of seconds between UTC and the local time when you import a module. All of the methods in that module are available as module name dot method name. If you want to use a single method in a module, you can import just that method using the from module name, import method, name syntax. Now the method is available in your program by name instead of calling module name dot Method name. You can now just call method name. Here is an example. Notice that we can call a SC time directly instead of proceeding it with a module name of time. Note that you don't have to import just methods. You can do the same thing with module attributes and classes. If you want to import more than one item from a module, you can create a separate from module import method Name line for each one. You can also provide a comma separated list like this from Method name Import Method one comma method to etcetera. Let's import the A S C. Time in sleep methods from the time module. The sleep method suspends the execution of your program for a given number of seconds, so we use the from time import SC time comma sleep line. Now we can call SC time and sleep directly. One of the advantages of importing a single method or list of methods from a module is that you can access it directly by name without having to proceed it with a module name. For example. We can call sleep versus time dot sleep. If you want to be able to access everything from a module, use an asterisk instead of a list of methods to import. However, I don't recommend this practice. I only pointed out, because you'll see it used from time to time. The reason you want to avoid this approach is that if you import everything into your program, you may override an existing function or variable. Also, a few import multiple methods using an asterisk. It will make it hard to determine what came from where. Here is an example of what not to do. The first line is from time import asterisk. Yes, you can see that we can conveniently call each of the methods from the time module directly . But again, it's not a good practice to do this. Use the de IR built in function to find out what attributes, methods and classes exist within a module. Here. The time module is passed to the D. I. R. Function. This more or less allows you to see the contents of the time module. You can view the default module search path by examining cysts dot path. When you issue an import module names statement, python looks for the module and the first path in the list. If it's not found, the next path is examined and so on until the module is either found or all of the module search paths have been exhausted. In addition to directories, the module search path may include ZIP files. Python will search within the ZIP file for a matching module as well. The default module search path will vary depending on your installation of Python, the version of Python and the operating system. Here is an example from a Python installation on a Mac. The first block on your screen is the contents of the Python program that produced the output on the bottom of your screen. This simple program was located in slash users slash Jason, and that's the directory I was in When I execute it, notice that slash users slash Jason is first in the module search path. The other directories were determined by the Python installation. If you want python to look in other locations for modules, you will need to manipulate the module search path. There are two methods to do this. The first method is to modify, says Stop path, as you would any other list. For example, you can append directory locations using a string data type. Here, I appended the slash users slash Jason slash python directory to the module search bath it becomes the last item in the list, and it's printed last when we looped through the module search paths. In this program, you can also manipulate the python path environment variable. It acts very similar to the path environment variable on Mac and Linux systems. Python Path can be populated with a list of colon separated directories on Windows systems . The Python Path environment variable requires the use of semicolons to separate the list of directories. The directories listed in Python Path are inserted after the directory, where the script resides and before the default module search path. In this example, slash users slash Jason is the directory where the show module Path thought P Y Python program resides. It contains the code we've been using to display the module search path. In the last few examples, the user local Python Modules path is included in Python Path. The Export Command makes Python path available to program started from the show. You can see that the first item in the module search path is the present working directory of slash user slash Jason, the second item in the search path. IHS slash user slash local slash python slash modules justice specified in the python path . Environment. Variable. If a module is not found in the search path and import error exception is raised here, the say hi module cannot be found. 47. Modules, Part II: in the previous examples we have been using. The time module, which is included with python python, is distributed with a large library of modules that you can take advantage of. As a matter of fact, I suggest looking at what the Python Standard Library has to offer before riding any of your own code. For example, if you want to read and write, see SV comma Separated values files. Don't waste your time reinventing the wheel. Simply use python See SV module. Do you want to enable logging in your program? Well, use the logging module. Do you want to make an http request to a Web service and then parse the Jason response? Use the U. R L Lib request and Jason Modules. The list of what's available in the Python Standard Library is located at the U. R L. Located at the top of your screen, I said, just taking a look at what's included in the Python Standard Library. You can accomplish a lot with very little code on your part by taking advantage of the library. Let's use the exit method from the CIS module to cleanly Terminator program. If we encounter an error in this example, the file tests dot txt is opened. If the program encounters an error opening the file, The code block following the except statement will execute. If the reading of test dot TXT is required for the remaining program to function correctly , there is no need to continue. Note that the exit method can take an exit code as an argument. If no exit code is provided, zero is used by convention. When an error causes a program to exit, a non zero exit code is expected. Here we exit with a status of one. If a air is encountered. Just as Python has a library of reusable code, so can you. If you want to create your own module, it's easy. Remember that in the simplest form, modules are files that have a dot p. Why extension? Simply create a python file with your code and imported from another python program. The first block of code on your screen contains the contents of the say hi dot pie file. The second block of code shows how you can import and use the Say hi module to call the Say hi method within the SE Hai module. You say hi dot say hi. The output that is produced is high. This is another simple module cold say hi to at the top of your screen are the contents of this file say underscore h i two dot p y. First to say hi function is defined. Next apprint function is called the block of Code. In the middle of the screen is how you would import and use the say hi to module. Finally, at the bottom of your screen is the output. By running that code, you might not have expected that output. So what happened? While when say hi to is imported, its contents are executed. First, the say hi function is defined. Next, the print function is executed. Luckily, Python allows you to create programs that behave in one way when they are executed and another way when they are imported. If you want to be able to reuse functions from an existing python program but do not want the main program to execute, you can account for that. When a python file is executed as a program, the special variable underscore underscore name underscore underscore is set to underscore underscore main underscore underscore when it's imported the underscore. Underscore name underscore underscore Variable is not populated. You can use this to control the behavior of your python program. Here we create a say hi function. Next we create a main function. This is how we want the program to behave when it's executed directly. Finally, we have an if statement that checks to see if the program is being executed. If it is, then the main function is called in. That block of code is executed. If the module is imported, the main function never gets cold or executed. This is a common pattern, and you'll see this in many python applications again. When this is imported as a module, nothing is executed unless explicitly called from the importing program. Here is what would happen if I were to execute this program from the command line. 48. Modules, Section Summary: in this section of the course, you learn that python modules are simply files that have a dot p. Why extension and they can implement a set of variables, functions and classes. Used the import module name syntax to import a module. You also learned that the default module search path is determined by your python installation to manipulate the module search path, modify cyst, stop path or set the python path environment variable. We also talked about how the Python Standard Library is a large collection of code that can be reused in your python programs. You also learn how to use the de IR built in function to find out what exists within a module. Next, we talked about how you can create your very own personal library by writing your own modules. Finally, we talked about how you can control how a python program behaves, based on whether it is run interactive, Lee or imported by checking the special variable underscore underscore name. Underscore, underscore