navigate site menu

Start learning with our library of video tutorials taught by experts. Get started

Up and Running with Python

Up and Running with Python

with Joe Marini

 


Get a quick intro to Python, the popular and highly readable object-oriented language. Joe Marini provides an overview of the installation process, basic Python syntax, and an example of how to construct and run a simple Python program. Learn to work with dates and times, read and write files, and retrieve and parse HTML, JSON, and XML data from the web.
Topics include:
  • Installing Python
  • Choosing an editor/IDE
  • Working with variables and expressions
  • Writing loops
  • Using the date, time, and datetime classes
  • Reading and writing files
  • Fetching Internet data
  • Parsing and processing HTML

show more

author
Joe Marini
subject
Developer, Programming Languages
software
Python
level
Beginner
duration
2h 24m
released
Jul 19, 2013

Share this course

Ready to join? get started


Keep up with news, tips, and latest courses.

submit Course details submit clicked more info

Please wait...

Search the closed captioning text for this course by entering the keyword you’d like to search, or browse the closed captioning text by selecting the chapter name below and choosing the video title you’d like to review.



Introduction
Welcome
00:00 (MUSIC). Hi.
00:04 I'm Joe Marini and I'd like to welcome you to Up and Running with Python.
00:07 This course will give you an introduction to the Python programming language.
00:12 We'll start by seeing how to determine if Python is installed on your system and how
00:15 to install it if it isn't already there. Next, we'll examine the basics of the language.
00:20 Variables, loops, functions, classes and more.
00:24 We'll also see how to build our first Python program in just a few lines of code.
00:29 Then, we'll move on to working with some of Python's built-in, high-level data
00:32 types just as dates, times and files. Finally, we'll wrap up by taking advantage
00:38 of Python's extensive library of pre-built modules to build advanced features, like
00:42 retrieving data from the internet and processing information such as HTML, XML,
00:46 and Json. If you're ready to start building the next
00:50 generation of cross platform applications that run in the Cloud as well as the
00:53 client, then lets get up and running with Python.
00:56
Collapse this transcript
What you should already know
00:00 Before we get started there are some things that you should already know, and
00:03 that I am going assume that you are familiar with, before beginning this course.
00:07 This course is designed to get you up and running with the Python Programming Language.
00:11 It's not intended to be a general introduction to the Fundamentals of Programming.
00:16 You should already be familiar with Basic Principles of Programming such as
00:19 variables, and functions, and statements etc.
00:22 Prior experience with other languages like Javascript will also be very helpful.
00:27 You should also know how to use common programming tools, like a text editor or
00:31 an integrated development environment like Aptana Studio or Dreamweaver or whatever
00:35 your favorite editor is. Now, if you're not familiar with these
00:38 concepts already, you should watch Foundations of Programming: Fundamentals
00:42 with Simon Allardice. This course does a great job of
00:44 introducing the fundamentals of programming like I described earlier.
00:48 You should also consider watching JavaScript Essential Training, also by Simon.
00:52 JavaScript has some language features that are kind of similar to the things we'll
00:57 run into with Python as well. So, having some knowledge of JavaScript
01:00 will help you immensely. Once you're comfortable with these
01:02 concepts, you can go ahead and start the course.
01:04
Collapse this transcript
Using the exercise files
00:00 If you are a member of the lynda.com online training library, you have access
00:04 to the exercise files used throughout this course.
00:07 Just download them and extract them and put them in a convenient location where
00:10 you can access them as you're going through the course material.
00:13 I've put the exercise files for this course here on my desktop.
00:16 So let's open the folder and see how they're laid out.
00:20 Each of the exercise files is laid out according to a chapter in which it is used.
00:24 So you can see here, I've got chapters two through five.
00:26 If you look inside the individual chapter, you'll notice that some of the files are
00:30 named underscore finished, while others are named underscore start.
00:33 The underscore finished version of the file is the completed code for the lesson.
00:37 The underscore start version is the starting point which is where I'll be
00:40 beginning each lesson and building towards the finished example.
00:44 How you want to use these files is entirely up to you.
00:46 If you want to follow along with me by opening the underscore start version and
00:50 building towards the finished version, that's fine.
00:52 If you want to use the finished version, just jump straight to the code and see how
00:56 it works, that's fine as well. It's entirely up to you.
01:00 Back up here in the exercise files folder, I've also included this file here called
01:04 example snippets.txt. Example snippets contains the snippets of
01:08 code that I'm going to be copying and pasting into the underscore start versions
01:12 of each file. That way you don't have to sit there and
01:14 watch me type. Okay, well that's pretty much all there is
01:17 to it for the exercise files, let's get coding
01:20
Collapse this transcript
1. Preparing the Development Environment
Installing Python
00:00 Let's begin by making sure that Python is properly installed and configured on our computer.
00:05 Now, the good news is that many modern computing systems already come with Python installed.
00:10 So for example, if you're watching this course on a Mac or on Ubuntu Linux.
00:14 Then you've already got Python on your computer.
00:17 The best way to make sure that the python is already installed, is to open up a
00:21 command prompt, and try executing the Python interpreter.
00:24 Now, I'm going to do that here by opening up a command prompt in my windows machine,
00:28 if you're using a Mac, you can just start your terminal program and do the same thing.
00:33 And so here in my command prompt, I'm going to type python dash dash version and
00:39 I'm going to execute this, and you can see here on my computer, I'm using Python 2.7.5.
00:46 Now, if you didn't get a result that looks like this, the word Python followed by a
00:50 version number, maybe you got something that looks like a error saying something
00:53 along the lines of, Python is an unrecognized command, or something like that.
00:57 That means that Python is not currently configured on your computer and you need
01:01 to go get it. So, let's go do that on the Python website.
01:06 Okay, this is the Python website located at python.org.
01:09 And over here on the left hand side, if I scroll down a little bit, you'll notice
01:13 there are two versions of Python. There's 2.7 something, and then there's
01:17 the three dot X line. Both versions of Python are still
01:21 currently supported. The 2.7 version is the original version of
01:26 the Python language. The 3 version is the newer updated version
01:30 of the language. Now, all of the things I'm going to be
01:33 showing you in this course, should work fine on either one of these versions of Python.
01:37 I'm going to be using version 2.7.5 in this course, because it's still very
01:42 widely supported throughout the industry. For example, the version that comes with
01:46 Mac is currently is still 2.7, Google app engine supports 2.7 for example so, I'm
01:51 going to be using 2.7. But don't fear, if you decide the three
01:55 line that, should work just fine. So to install Python on your computer,
01:59 probably a Windows machine, you'll just need to click on the Windows installer
02:02 right here. This will download the windows.msi
02:05 installer, it will install Python on your computer, and then you'll be off and running.
02:09 All right. Once you've got Python installed on your
02:12 computer, let's go ahead and take a look at some developer tools for working with Python.
02:16
Collapse this transcript
Choosing an editor/IDE
00:00 There are a lot of great tools out there for working with the Python programming language.
00:04 I'm going to take a moment and show you a few of my favorites.
00:07 But, of course, if you're already using a programming tool that you like such as
00:11 Dreamweaver or Notepad or Text Wrangler, it doesn't really matter.
00:15 You can use that editor to follow along with this course.
00:18 One of my personal favorites is Python Fiddle.
00:20 If you go to pythonfiddle.com this is an online python editor in the Cloud.
00:25 So I can just go ahead in here in the editor and start typing some Python code.
00:29 And I realize I haven't shown you any of this yet, so just bare with me a moment.
00:34 But I can write a really simple program, I can click run, you can see down here I'm
00:38 getting my output. I can configure the window a little bit larger.
00:42 Over here in the side bar, there are examples of Python programming.
00:46 You can work with different packages and so on.
00:49 So Python Fiddle is really a great online editor, if you like using online editor.
00:53 Of course, there's also Sublime Text. Sublime Text is a really great programming
00:59 editor, it runs across platforms. It's available for Mac, Windows, Linux.
01:03 This is one of my personal favorites, so you can use this if you want to.
01:07 But in this course, I'm going to be using Aptana Studio, and the reason why I'm
01:10 going to use Aptana Studio, is because it has built in support for Python.
01:14 You can write your code and run you Python code and debug it, all without having to
01:19 leave Aptana Studio. So I'm going to be using this but again,
01:23 it doesn't really matter. You can use whatever editor you want and
01:26 I'll show you how to run the Python code if you're not using Aptana Studio.
01:30 Okay. So now that we're going to be using Aptana
01:32 Studio, I'm going to show you how to install it and get up and running with it.
01:35
Collapse this transcript
Installing the developer tools
00:00 In this course, I'm going to be using Aptana Studio 3 to write and run and debug
00:05 my Python programs. It's cross-platform.
00:08 It runs on Mac, Windows and Linux, and it's 100% free.
00:12 You can just download it and use it because it's open source.
00:16 So, I'm going to come here to Aptana Studio.com, click on the Products link.
00:21 And then click on the Download Aptana Studio 3 button to install this product.
00:26 Now, if you're not familiar with using Apata Studio, don't worry about that.
00:29 I've actually got a course right here on lynda.com called Up and Running with
00:32 Aptana Studio 3. It's only about an hour long and it
00:36 introduces all of the concepts that you'll need to know to get the most out of
00:40 working with Aptana Studio. And the great thing is, once you've gone
00:43 through this course, you'll be able to use Aptana Studio for other courses here on
00:48 lynda.com regardless of the programming language.
00:50 It's a great editor for working with HTML and CSS and JavaScript and PHP and Ruby.
00:56 And all the other programming languages you might want to work with.
00:59 So, once you've downloaded and installed Aptana Studio, fire it up and let's get
01:04 started using it. So, here I am in Aptana Studio, and what
01:11 you need to do first is go to the Help menu and then choose About Aptana Studio.
01:15 What you want to make sure is, that this little icon right here kind of looks like
01:19 a leaf is present. Because this is the Python Development Environment.
01:24 If you click on this icon, you'll notice that the feature name is called Pydev.
01:28 This is the Python Development Environment provided by Aptana Studio.
01:31 So make sure that this is installed because you'll need it to work with all
01:34 the Python features in Aptana Studio. If this is not present, you can go get it
01:39 from the Aptana website. Alright so I'm going to click on that.
01:43 Click Close. Over here in the local file system, I'm
01:47 going to expand this. And you'll see that here in the desktop,
01:50 I've got my exercise files folder. So use this local file system over here to
01:55 browse to wherever you've got the exercise files.
01:58 Right click on the folder, and then choose Promote to Project.
02:01 Okay, I'm going to go ahead and click Finish.
02:06 And you'll see that Exercise Files is now a first class project within my Aptana Studio.
02:11 So now, I can collapse the local file system, expand this.
02:15 And you'll see that all of the python code that we're going to be working with is
02:19 right here set up as a project for us. This will allow us to do things like edit
02:23 the code, run it, debug it. Run it right here inside of Aptana Studio
02:27 in the built in console output. All the great things that Aptana Studio
02:31 has for working with Python. Alright, once you've got all set up using
02:35 Aptana Studio, it's time to begin the course and start writing some Python code.
02:39
Collapse this transcript
2. Python Basics
Building Hello World
00:00 Okay, so now that we've got Python installed and our tools installed and
00:03 setup it's time to start writing some actual Python code.
00:07 And before we use our tools, before we use Aptana Studio to do that we're going to
00:11 use Python's interpretive mode in the command line interface, to see how easy it
00:16 is to write some Python code. So go ahead and start up a terminal
00:19 incidence on your computer and here on Windows, I'm going to run the command prompt.
00:24 If you're on the Mac, use the terminal program and on Linux, you know there's
00:27 another command line thing that you can use.
00:29 Whatever you're using, just start up a terminal window like this.
00:32 Now type the word Python and hit Return. And as you can see, I'm now entered into
00:38 Python's interpreted mode. So, right here is the version number for
00:42 Python, and some help text. But I'm running the Python interpreter in
00:46 command line mode. So now I can just simply type some Python
00:49 code, and it will run. So type 2 plus 2.
00:52 And you can see that the answer comes back 4.
00:55 Python like JavaScript is also an interpreted language, in other words it's
01:00 not like Java or C, or C++ or objective C. The application does not need to be
01:06 compiled before you can run it. The Python interpreter simply takes each
01:10 line of code as it comes across it and interprets and executes it.
01:14 And in this case, it's simply taking the numerical expression 2 plus 2, evaluating
01:18 it and it gets 4 back. Okay, so, now let's try something else.
01:20 Type, Print and Hello World and hit Return.
01:29 And you can see now that I've executed the simple Python statement Print, which is a
01:33 built-in command. And the string, Hello World.
01:35 So this is not how you would normally write Python code, I mean obviously Python
01:41 programs are going to be a lot more complex than this but you can use the
01:44 Python interpreter in command live mode to try out simple things.
01:48 Alright now let's type the word, exit, with.
01:51 A opening close parenths, so we're actually calling the exit function.
01:56 And that will exit us back out of the Python interpreter and into the command line.
02:02 Okay, so now that we've seen how to write and execute some basic Python statements,
02:06 let's start up Aptana Studio and write our first Python program.
02:12 Okay so here we are in Aptana Studio and I'm going to close the Start Page and over
02:18 here in my project I'm going to open up in the Exercise Files helloworld_start.
02:24 And I'm also going to open up my Snippets File which contains the code I'm going to
02:28 be using throughout this example. Alright, so let's start off in helloworld_start.
02:33 Type print, and you can see that as I'm using Aptana Studio, I'm getting statement
02:38 completion right as I'm typing. So, there's print, and type Hello World, okay.
02:48 Hit Return and save it. Okay, so now what I'm going to do is use
02:52 the built in Python interpreter in Aptana Studio, and the built in console window to
02:58 run this code right here in my development environment.
03:02 So I'm going to click on the little green button up here which runs the application,
03:05 and you can see down here I'm getting the Hello World output.
03:09 Now you might, the first time you do this. You get a little dialog that pops up that
03:13 says run as, and that dialog will give you two options.
03:16 It'll say run as, run PyDev, or run Python unit test or something like that.
03:22 Choose the first one, not the second one, choose run as PyDev.
03:26 And that's going to be the option that executes the application.
03:30 So you can see here we've got print hello world and that's what's happening.
03:34 Now if you're not using Aptana Studio if you decided to use your own editor and you
03:38 want to run this application you'll need to do things a little bit differently, so
03:42 go back to your command prompt and go into where the Exercise Files are that you're
03:49 working on. In my case they're in the desktop, so I'm
03:51 going to CD into my desktop. Into the Exercise files, into Chapter 2
04:00 and if I type DIR okay you should see that's the contents of the directory.
04:04 Now in order to run this example I'm going to type, python helloworld_start.py.
04:17 And you can see that I'm getting the same example output right here, it says Hello World.
04:21 So, if you chose not to use Aptana Studio that's fine, you'll just have to run each
04:26 example by using the Python command right here, and the name of the script that you
04:31 want to execute. Okay, let's go back into the Hello World
04:35 in Aptana Studio. Alright, let's jump over to the snippets.
04:39 And here in my Chapter 2 section under HelloWorld I'm going to copy these two
04:44 lines right here, 13 and 14, and then paste them in where this statement was,
04:50 going to get rid of it and paste in this instead.
04:52 So I don't expect you to understand all of this right away.
04:55 We will be going into this more deeply as the course goes on.
04:58 But what I'm doing here is defining a function.
05:01 So line five defines a function called main.
05:04 And that function has only one statement, it prints hello world.
05:09 So I'm going to save this, and I'm going to run it.
05:11 And one thing you notice is, nothing happens.
05:14 And the reason nothing happens is because nothing is calling this function main
05:18 right now. I need to write some code that actually
05:20 executes function main. And before I do that the other thing I
05:23 want to point out is that Python syntactically is a little bit different
05:27 than other languages you might be used to. So for example in JavaScript if I were to
05:32 write something like function f, right and I have these two curly braces inside
05:37 function f I can put some code, right, let's imagine these are lines of code, so
05:41 I've got one, two, three. Now inside this function, I can indent
05:45 these however I want. I can put this one over here, and I can
05:48 put, you know, this one over here. And it doesn't matter.
05:51 The JavaScript interpreter isn't going to care how these lines are indented because
05:55 these two curly braces indicate that the lines of code, 10, 11, and 12.
06:01 Belong to function f. Now, python does not work like that.
06:05 Python does not have this notion of these scope delimiters by these curly braces.
06:10 So if I get rid of this code for a second, okay.
06:12 Python actually uses the indentation level of the lines of code to indicate where
06:19 that code belongs. So because under the definition for the
06:22 main function I've got this indented by two spaces, that indicates to the Python
06:27 interpreter that line six belongs to the function name.
06:30 If I put another line down here like, you know, print me too, and I save this, now
06:38 if I run this you'll notice only the me too gets printed because it's not part of
06:44 the main function. So I need to find a way to call the main
06:47 function, so let's go back to our snippets and in here I'm going to copy lines 16 and 17.
06:54 Okay, and I'm going to put lines 16 and 17 right in here.
07:01 So I'll paste them in and in here there lines eight and nine.
07:05 All right let me explain what's going on here, what's happening here is this line
07:09 of code line eight is checking to see that when this module, when this file of Python
07:14 code is loaded and the Python interpreter has assigned the underscore underscore
07:19 name property the value of main that means that this Python program was executed as a
07:25 main program. It was started up from the command line or
07:28 somehow invoked and therefore this function right here, main, should be called.
07:33 Now I might have chosen to take this Python file and simply include it in
07:39 another application, and in that case I don't want the main function to be called,
07:44 what I'm probably doing is including this as if it was a library.
07:47 And if I had a whole bunch of Python coding here that provided some
07:50 functionality, I wouldn't want those functions to be executed.
07:53 So lines eight and nine help distinguish between when a Python is being included as
07:58 a library, or when that Python code is being executed as a program.
08:02 So it's being executed as a program line eight will be true, and then the main
08:06 function will be called. All right, so now, if I save this and I
08:10 run it, you can see that now the main function is being called along with the me
08:16 too line down here on line 11. Now, we'll get more into this as we go
08:21 into the rest of the course, but for now, that's a very quick introduction to
08:25 writing your first Python program.
08:27
Collapse this transcript
Variables and expressions
00:00 Now let's take a look at how the Python language works with variables.
00:03 So I'm going to go over here and open up variables_start.py and here in my snippets
00:06 I've scrolled down to my variable section. And I'm going to copy lines 22, 23, and 24.
00:17 So I'll copy those and bring them over. This gives me an opportunity to point out
00:22 a couple more things about the Python language.
00:25 First, comments are declared using this character right here.
00:28 Now some people call this a pound sign, some people call it a hash symbol or a
00:33 number symbol, doesn't matter what you call it.
00:35 You use this to declare comments. The next line, line 6, declares a variable.
00:41 In this case I'm declaring a variable named F and assigning it the value of 0
00:45 and then on line 7, I have print F, which is going to print the value of that variable.
00:50 So let's Save and let's run this. Okay.
00:54 And again, if you get a little dialog that says how should I run this choose run pie div.
00:59 Don't choose the unit test 1. So you can see that it's printing the
01:02 value 0. Because that's what the value of the F
01:06 variable is. Okay, let's go back to the snippets and
01:09 now let's copy lines 26 through 28 and bring those over.
01:15 Paste those in. As you can see here I've got f equals 0
01:19 and then print f, and now I've got f equals abc, so I'm redeclaring the variable.
01:24 I'm simply saying whatever f was before it's now a string.
01:27 So let's go ahead and save this and run it and you can see that that works.
01:33 In the first instance I've got f equals 0 and then I print it and that's right here,
01:38 and then I got f equals abc and I print it and that's right here.
01:41 So even if the variable has already been declared you can redeclare it and that
01:46 works just fine. All right once again back to the snippets.
01:53 Let's copy lines 30 and 31 and we'll paste that and let's uncomment line 14.
02:00 Alright so save. Now let's see what happens when I try to
02:03 execute the program here and it should run.
02:07 And you can see that I'm getting a type error.
02:09 Cannot concatenate str and int objects. This is happening because Python is what's
02:15 called a strongly typed language. And even though you don't have to declare
02:19 the type of a variable before you use it. What happens is, when Python goes to
02:23 execute the code, if it infers a specific type for a value or variable.
02:29 You can't go back and change the type or combine it with other types.
02:33 So here I've got a string, and I've got a number.
02:35 Now, in JavaScript this works, right? The JavaScript interpreter sees this
02:40 number right here, sees that you're combining it with a string.
02:43 Converts it into a string, and then this would print out string type 1, 2, 3, just fine.
02:49 In Python, that doesn't work. You have to have all of these guys be the
02:52 same type. So what I'm going to do is go back to my
02:55 snippets and I'm going to copy line 32 here.
02:58 going to paste that in and comment out line number 14.
03:04 What I'm doing here is using Python's built in function called str to convert
03:10 this type here into a string. So that way I'll have a string plus a
03:14 string and that work just fine, so I'm going to save and I'm going to run.
03:19 And you can see now string type 123 is being printed out as we would expect.
03:24 And in order to do this, you have to convert types to the same type.
03:27 So, we're going to str right here. Okay, back to the snippets.
03:34 Now, let's take a look at global versus local variables.
03:38 So, I'm going to copy this right here. And again, and we'll get more into
03:42 functions as we go on. But I'm going to paste this in for now.
03:45 Okay and lets go ahead and take out some of the lines we were working with before,
03:50 because we don't need them for this example.
03:54 So here on line 10, I'm defining a function.
03:56 And inside that function you can see that these two lines are indented by two
04:00 spaces, indicating that they belong to this function right here.
04:04 I've got F equals DEF and then print F. Now remember, I've already declared F up here.
04:10 So there's a variable here and there's a variable here.
04:13 And back in the snippets, we need 2 more lines.
04:16 We need 40 and 41 right here. So let's copy that.
04:19 And let's go down here and paste. Okay.
04:22 So we're going to call some function and I'm going to print F.
04:26 So let's watch what happens. going to click Run.
04:30 You can see that f starts out as 0 and on line 7 it prints f.
04:34 That's the 0 rate here. Then I declare the function.
04:37 Down here on line 15, I call some function which sets the value of f to be def and
04:43 then prints f. Now in that case, it's right here, that's
04:47 what's getting printed. And then outside that function, after it
04:50 returns, I print f again and it's back to being 0.
04:54 That's because when you're inside a function definition like this, the
04:57 function gets it's own local copy of whatever variables you declare inside the function.
05:02 So this variable f right here is different than this variable F right here.
05:07 Now if I actually want to affect the value of the global variable I have to tell the
05:13 function that this is in fact a global variable.
05:16 So I'm going to use the global statement right here with the name of the variable
05:20 called F. And now when I run the code, you can see
05:25 that def is being printed twice that's because it starts out as zero here inside
05:30 the function assign the value of def. And because I've told it that's it's a
05:34 global variable now it's going to affect the variable value of it globally.
05:39 So after this function comes back and we print f again the value has been changed
05:44 outside the function as well. So you can see it's being set to def in
05:48 both places. Okay, and let's go back to the snippets
05:50 one more time, let's copy these lines right here, and we'll paste them in here.
05:58 Okay, and we'll save. The del statement deletes the definition
06:04 of a variable that was previously declared.
06:07 So up here I declare the variable f, down here I delete it.
06:12 So when I get to this line there should be a problem, it should give me an error
06:16 because that variable is gone. So let's just for clarity's sake get rid
06:20 of these lines right here, so all we've got left is 6 and 7 and now we've got 9
06:26 and 10 right here. So we'll save and we'll run.
06:30 So you can see that the first thing that happened was the number 0 was printed
06:36 because that's what f is right here on line 6.
06:39 Then when we get to line 10, after calling del f you can see that there's an error.
06:45 It says name f is not defined. That's because I deleted it on line 9.
06:50 So you can undefine variables in real time by using the del statement.
06:54 Okay that's a quick look at using variables in Python.
06:57
Collapse this transcript
Python functions
00:00 Most applications whether their written in Python, or some other programming
00:03 language, are broken up into smaller blocks known as functions and Python's is
00:08 no different. So in this example we're going to take a
00:10 look at how to work with functions in Python.
00:12 So I'm going to go over here under Chapter 2, and open up functions_start.py, this is
00:19 the example file for this part of the course.
00:21 Back over here in my example snippets text, I'm going to copy lines 49 through
00:28 51, and paste them in. Now if you've been following along the
00:33 course so far you've already seen me do something like this, I'm just defining the function.
00:37 Functions are defined with the def keyword and then they're given a name.
00:42 And then open and close parens. Now this function doesn't take any
00:45 arguments, but we'll get to that in a little bit.
00:47 And then a colon. The colon indicates that you're starting
00:50 the scope of a function. And so you can see down here that line
00:55 number 7 is indented in to two spaces. And it's up to you how many times you want
00:59 to indent something. It's not limited to two, you can set it to
01:02 three or four or whatever. But the important point is it has to be
01:05 indented to indicate that this statement is part of the function.
01:09 Okay, so let's go back to the snippets and let's scroll down, and let's copy lines
01:16 75, 76, and 77. And we'll paste them in down here, and
01:22 we'll save. Line 9 simply calls func 1, so let's
01:27 comment out the other two just for a moment, save and let's run this.
01:31 And you can see that you're getting PythonRun or Python unit test as a
01:36 question (UNKNOWN) studio wants to know how you want to run this.
01:39 Whenever you see this dialogue just choose PythonRun.
01:41 Okay. And you won't need to do this again for
01:43 this file. Python just needs to know the first time,
01:45 like, how are you running this. I'm going to click Okay and you can see
01:48 that when we call func 1 it prints out I am a function, which is not surprisingly
01:53 that's what would happen. Alright now let's go down and uncomment
01:57 line 10 and then save. Now let's run it again and you can see
02:02 that func1 is being called and it's printing out I am a function.
02:06 Here I'm calling print func1, so it actually executes the function right here
02:11 and then it prints as well. What's happening is, let's run it again so
02:15 you can see it. So it calls the function and so the
02:18 function itself prints I am a function, but there's no return value.
02:22 Right? My functions not returning a value, its
02:24 just simply falling through and not returning anything.
02:27 And so my number 10 is trying to print whatever the return value was, and since
02:31 there wasn't any return value. It simply prints the built in Python type
02:35 None, Okay. So let's go back into code and let's
02:40 uncomment line 11 and save. Now in this case I'm printing func1 but
02:47 I'm not actually invoking the function. So let's see what happens there.
02:51 Okay, So you can see that line 9 gets executed that's this right here.
02:56 Line 10 is calling the function and then printing the value, the return value of
03:00 which there isn't any. And then line 11 says print func 1 and you
03:04 can see here it's printing out this Function func1 at some hexadecimal address.
03:10 And this is happening because functions in Python are themselves objects, they have a value.
03:16 In this case it's an object, it's a function object, and the print command is
03:21 printing out the value of the func1 object.
03:25 Now you probably won't ever need to do this in a partical Python program but this
03:30 is just an indicator of how Python treats objects.
03:33 Okay, let's go back into the code. Let's comment these guys out and let's
03:40 copy in the next example. And the next example if we scroll back up,
03:44 now we're going to define a function that takes arguments.
03:47 And we'll copy that and we'll paste that in, so now I'm defining func2, and it
03:54 takes two arguments, arg 1 and arg 2. And all it does is print out arg1
03:59 separated by a space and then arg2, okay. Let's go back to the snippets, scroll
04:04 down, and let's call func2 a couple of different ways.
04:10 Okay, we'll paste these guys in down here. So, here I am calling func2, with 10 and
04:17 20, and you can see I'm going to print these guys out.
04:20 And then, I'm going do the same thing, print func2.
04:23 Alright, so let's run this. And you can see that on the first line 10
04:28 and 20 get printed and then on the second line.
04:31 Once again, this is similar to the first example where the function prints out
04:35 something but there's no return value, so it simply returns the value none.
04:40 Okay, so let's go back to the snippets. All right, now let's get the next example.
04:46 We're going to define a function that returns a value.
04:50 Copy and we'll paste the same over here. And then we'll copy over the code the
04:57 exercises it and that's this guy right here on line 80.
05:03 And so we'll print cube right there. And let's comment out these other two
05:08 functions and save. All right, so here we're defining a
05:11 function called cube and it takes a number and then it returns that number times
05:15 itself three times. So it calculates the cubed value of that
05:19 number and returns it. So now we have print cube 3.
05:24 So we'll run this. And you can see, actually lemme scroll
05:29 that into view so you can see it there a little bit better.
05:31 Hang on a second. Let me run it.
05:32 You can see that what's happening now is, when we print the cube of 3 we get the
05:38 value 27. So in this case the function does return a
05:41 value and that is what gets printed. All right, back to the snippets /g.
05:49 Let's copy line 61 through 66 and paste those in over here.
05:55 Okay, let's go ahead and comment out the cube call and let's copy Lines 81, 82, and 83.
06:09 And we'll paste those in down here, alright.
06:11 Now what I've done is I've defined a function called power and it takes two arguments.
06:16 One of them is called num and one of them is x.
06:19 And all it does is, it takes a number and raises it to the given power.
06:24 Now, you'll notice here that I've got x equals one.
06:26 And what I'm doing there is assigning a default value for that argument.
06:32 So, down here on line 30, I'm calling it print power of 2 but I'm not giving it a power.
06:38 So the value of x is going to default to one, and it's going to print out the
06:42 result of this mathematical calculation in here.
06:46 Now, again we haven't gotten into loops yet, we will in a little bit, but all this
06:49 is doing is looping over the number of x that we've given it and multiplying the
06:55 number by itself that many times. So in this case we're going to have 2
06:59 raised to the power of 1, 2 raised to the power of 3 and so on.
07:04 So let's go ahead and run this and what we're going to do is first let's comment
07:07 out 32. Let's run 30 and 31.
07:12 So, we've got power of 2 and power 2 raised to the power of 3.
07:16 Let's run this, and you can see that 2 raised to the first power is 2 and then 2
07:21 cubed is 8. So, 2 times 2 is 4, 4 times 2 is 8.
07:26 Okay. The other thing I'm doing, on line 32,
07:29 let's un-comment that. In this case I'm actually reversing the
07:35 order in which the arguments are called. But because I'm calling them with their
07:41 names and supplying the value, the Python interpreter can figure out which arguments
07:47 I'm supplying the values to. So in this case even though num has been
07:51 called second and its defined to be the first one.
07:54 The Python interpretor will figure out them giving this parameters name right
07:59 here this value. So you don't have to call the function
08:03 with the arguments in a particular order if you simply supply the names along with
08:07 calling them. So lets try this again and save and we run
08:13 and you can see that the results are the same.
08:15 2 to the third power is in fact 8, so if I change this to say 4 and save it and run
08:23 it, you can see now we're getting 16. Let's go back to the snippets.
08:29 We got one more example to look at. I'm going to copy this, and we're going to
08:38 paste it. And again, don't pay too much attention to
08:42 stuff in here that may not look familiar. The four in, we'll cover loops a little
08:47 bit later. But what we're going to do now is comment
08:50 outline 39 and in my snippets I'm going to copy line 84 and paste it in down here.
09:00 Okay. So what we've done here is define a
09:03 function called multi_add, and the star character means that I can pass in a
09:10 variable number of arguments. So, what's going to happen is on line 26
09:17 I've got the result is equal to 0. So I'm defining a local variable named result.
09:21 Then I'm going to loop over each one of the arguments.
09:24 So here, arguments is a list of things that were passed to the function.
09:29 So for each one of those guys we're going to add that value to the overall
09:35 result and then return the result. Okay, so you can see I"m calling it down
09:40 here with 4, 5, 10 and 4, so it's going to add 4 plus 5 plus 10 plus 4.
09:47 So when I save and I run, you can see that the result is 23.
09:52 Okay. So I can come down here and add another
09:56 number 10, so that should give me the result of 33 now.
10:00 So, if I run this again, you can see that that's what happens.
10:03 So, that's how you can define a function that takes a multiple number of arguments.
10:08 All right, that concludes a quick look at functions.
10:11 Let's move onto the next lesson.
10:13
Collapse this transcript
Conditional structures
00:00 One of the fairly common things you run into in programming is making decisions.
00:04 Comparing values and executing code based upon whether one value is greater than, or
00:09 less than, or the same, or not the same as another one.
00:12 And that's where conditionals come into play.
00:14 In Python, conditionals are handled using the If statement and that's what we're
00:18 going to look at now. So let's start up conditionals_start.py.
00:24 And you can see here in the main function for this example, I've got two variables X
00:28 and Y. And they are 10 and 100 to start with.
00:33 So let's go over to the example snippets.txt.
00:35 And let's copy lines 90 and 91. So we'll copy that.
00:41 And we'll paste it in down here. And you can see that what's happening is
00:48 we're comparing X to Y. And if X is less than Y, then the value of
00:54 this ST variable will be X is less than Y. And then down here we're going to copy
01:00 line 96 and we'll paste that in right here, make sure it's indented the same.
01:08 Okay, so let's go ahead and run this and watch what happens.
01:12 So I will click Run and I choose Python Run.
01:17 And you can see sure enough X is less than Y.
01:21 Okay. let's see what happens if I change the
01:22 value of X to be 1000. So I save and I run.
01:27 And nothing happens. Well actually I get an error because line
01:31 9 never executed. So line 10 is trying to print the value of
01:35 a variable that was never declared. Well why did line 9 never run?
01:39 Well because X is now not less than Y. It's greater than Y.
01:42 So, we have to figure out a way to add in the case Where this condition is false.
01:49 So, let's go back to the snippets and let's copy lines 94 and 95, and let's
01:56 paste those in right here above the print statement.
01:59 So now we have If and then we have Else. So when the if condition is true, then
02:07 this block of code right here will execute.
02:09 In all other cases, this block of code will execute.
02:13 So now let's save and let's run. And sure enough now we're getting X is
02:18 greater than Y. So we've got the If and the Else statement
02:21 but let's try something special. Let's try making these two exactly the
02:26 same as each other. So, now, we're going to save and we're
02:30 going to run. And sure enough I'm getting hm, X is
02:33 greater than Y, but that's not really true.
02:35 They're the same. The problem is that this condition right
02:38 here is evaluating to false. Therefore this condition is evaluating
02:44 even though it doesn't check to make sure that X actually is greater than Y.
02:49 So let's go back and fix that problem. So back here in the snippet, we're
02:53 going to copy lines 92 and 93. And we're going to paste those in right
02:56 above the else. So now, we have If, Elif, and Else.
03:03 So we have a way of chaining more than one condition together.
03:06 And if you're used to using a language like JavaScript, you're probably used to
03:11 seeing this written as If, and then Else if, and then Else if.
03:17 So JavaScript just takes If and Else and combines them into one operator.
03:21 Python has the Elif operator right here. So there's If, Elif, and Else.
03:28 So now we're checking for the special case where X is exactly the same as Y and
03:34 catching it rather than just assuming that X is greater than Y.
03:37 So now if we run this, we get the correct output of Y is the same as Y.
03:44 Python provides one other way of writing a conditional statement.
03:49 And a lot of times what you'll run into is situations like this.
03:52 You'll run into situations where you have if and else.
03:56 So you've got four or whatever lines of code Intended to do a comparison.
04:01 And then, if that statement is true, otherwise the statement is false, alright?
04:05 So let me undo that cut, and let's go back over to the snippets.
04:10 Okay, and let's copy lines 98 through 100. And we'll put those in here at the top,
04:21 nah let's put it at the bottom of the file right here.
04:23 Okay let's paste that in. Python has a construct called a
04:26 conditional statement. And the conditional statement let's you
04:29 write something like A, if this condition is true Else B all in one line.
04:35 So, we can write this entire construct right here.
04:40 And in fact, let's just go ahead and cut this out for the moment so that it won't
04:43 execute on us. Okay.
04:45 So now we have ST equals this string X is less than Y If that condition is in fact true.
04:53 Otherwise X is greater than or equal to Y. So, we've got this, if the condition is
05:02 true, otherwise this. So, this one line let's us condense down
05:09 these lines of code right here into one statement.
05:13 Kay, so let's go ahead and cut this out. Alright, we'll save and we'll run.
05:21 And you can see that X is greater than or equal to Y, which is true because it's not
05:25 less than Y. So, if I go back in here and change this
05:27 to 10 again and save and run it, you can see now X is less than Y.
05:34 So Python gives you a nice concise way of writing a conditional statement, instead
05:39 of having to write out nice giant if else block.
05:42 So the if statement is used to execute conditional code.
05:45 and you can use conditional statement like this one, A if C else B to condense
05:50 conditionals into one line, that's pretty cool
05:53
Collapse this transcript
Loops
00:00 Repeating code over and over again via a construct known as a loop is also a fairly
00:05 common scenario in programming. And Python provides a couple of ways of
00:09 doing that, which we're going to take a look at now.
00:11 So let's open up loops_start.py. And you can see I've got a stub doubt
00:17 function here called main. And a variable named x which I'm
00:21 initializing to zero. Over here in example snippets.
00:25 We're going to come down to the loop section.
00:27 And let's start by copying lines 105 through 108.
00:32 Okay, so we'll copy those and we'll paste them in here below the x definition.
00:37 Okay. So this is a while loop.
00:43 And the contents of the while loop, and again you can see that it's indented.
00:47 So that indicates that these lines of code belong to the while loop and not up here
00:52 in the main part of the function. So a while loop executes while the
00:58 condition contained inside these parenthesis is true.
01:02 So while x is less than 5, we're going to print the value of X, and then we're going
01:07 to increment X by 1. Now some languages like C, provide a whole
01:11 bunch of ways of doing loops. They've got do while, and while, and for,
01:15 and other ways of doing loops. Python likes to keep things simple.
01:19 It's only got two ways of doing loops, while and for.
01:21 We'll get to for in a moment, but for now, let's just take a look at while.
01:25 So we're going to save this, and we're going to run it.
01:28 I'm going to Python run it. And, so you can see that X starts out as
01:33 zero, so it prints zero, one, two, three, and four, and then in increments to five,
01:40 the conditioning here is no longer true, and so the loop terminates.
01:44 'Kay, pretty simple. Let's go back to the snippets.
01:48 Now, let's define a for loop. So, we'll copy lines 110 to 112, and we'll
01:52 put them in here, 'kay? And let's get rid of these lines while
01:56 we're at it, so that we don't get distracted.
02:02 So we'll comment those out. For loops in Python work a little bit
02:08 differently than you're probably used to seeing in other languages.
02:12 Some languages like JavaScript and C and Java, have the concept of an index
02:17 variable that counts the number of iterations in the for loop.
02:21 So for example, in JavaScript, you'll probably see something that looks like this.
02:26 You've got for, right, and then i equals zero.
02:29 And then i is less then ten. And then i plus, plus.
02:34 So what's happening here is you've got a counter variable that's being used to
02:39 control the execution of the loop. That's not really how Python is intended
02:45 to operate. Python's for loops are what are called iterators.
02:49 So in this case, if I want to have x loop over a range of numbers.
02:54 I use the range function here. So I've got a range going from five to ten.
02:59 And I'm going to print x each time. So it's probably easier to understand once
03:03 you've seen it in action. So, let's save that and run it.
03:07 Okay, and once again down here in the output window, you can see it's printed
03:11 out five, six, seven, eight and nine. So you've got x within the range, which
03:17 obviously is not inclusive of ten, so its eludes this number right here, so it
03:22 printed out five through nine. But for loops operate over sets of things,
03:27 not just numbers, so let's go back up to the snippets and this time we're going to
03:32 use a for loop that loops over a collection.
03:36 So, let's go ahead and copy those and paste them in here.
03:40 And let's comment out these lines. Now in this case, I've got a variable
03:45 named days, and I'm initializing it to a list of abbreviated day names.
03:51 So I've got my opening bracket, my closing bracket, and inside the brackets, I've got
03:54 my day names. Now, I'm saying for d in days.
03:57 Print d. So this has nothing to do with numbers.
04:01 What's going to happen is, the for loop is going to iterate over each member of this list.
04:06 And d will be set to the current member that it's looking at that time through the loop.
04:12 So if I save and run. You'll see it's printing out Monday,
04:16 Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday.
04:19 So it's looping over the contents of this list right here.
04:23 So, again, no index counter involved. Just iterating over the members of a list.
04:29 All right. Now, let's take a look at using the break
04:33 and the continue statements. So, we're going to copy lines 119 through 123.
04:39 We'll paste those in down here. And let's comment out these guys.
04:45 Okay. So we have the same for loop that we had
04:48 before, right, so recall before we had for X in range of five to ten.
04:53 So we have that one more time. But now we're going to do two different things.
04:56 First, let's take a look at the break statement.
04:59 The break statement is used to break the execution of a loop, if a condition is met
05:05 or some other reason. So what I'm doing here is saying if x is
05:09 equal to 7 then break. The break statement here will cause this
05:14 for loop to terminate and fall through to the next block of code, which in this case
05:18 is the end of the function. So let's save and let's run this.
05:23 Okay. And you can see that what's happening this
05:26 time is instead of going all the way to nine, it prints out five and then six and
05:31 then gets to seven. And then this break statement kicks in and
05:35 terminates the loop, so it need gets to seven, eight or nine.
05:40 Okay, so let's comment that out. Now, let's take a look at the continue statement.
05:45 The continue statement skips the rest of the loop when it is encountered, so in
05:51 this case I'm saying if f modulo 2 is equal to 0, in other words take x divide
05:57 it by 2. And if the value left over is equal to 0,
06:00 then continue. Which means, don't do this statement right
06:04 here, just go back up to the start of the loop.
06:07 So in other words, if I come across an even number, then don't print it out, right?
06:12 The continue statement is going to skip the rest of the loop.
06:15 Now the rest of the loop in this case, is only one statement, but if there were more
06:19 statements here, they would all be skipped.
06:21 So let's save and let's run. And you can see that six and eight were
06:26 skipped because those are even numbers and it only printed out five, seven and nine.
06:32 Okay, so that's the continue statement. All right, let's go back to the snippets.
06:38 And let's take a look at one more example of using loops.
06:42 So we'll copy 125 through 128 and we'll come back in here and paste.
06:51 And let's comment out these. Okay.
06:56 Now we're going to go back and revisit the loop that we had up here, where we were
07:00 looping over these days. Now remember earlier I said, that normally
07:03 the for loop in Python does not use an index variable, there's no loop counter normally.
07:10 Well, you can get one if you really need it.
07:14 So here we have a collection, right. It's the same days collection.
07:18 Only now, what we're doing is we're saying 4i comma d in enumerate days, so the
07:25 enumerate function is actually going to iterate over this collection like the loop
07:29 normally would. But in addition to returning the value of
07:32 the item being looked at, it also returns a value that is the index of the item in question.
07:39 So this function's going to return two values.
07:41 It's going to return the index and the member of the collection that we're
07:45 looking at. And here I'm printing out both of those,
07:47 the index and the item, so let's save and let's run, and you'll see now I'm getting
07:56 zero, Monday, one, Tuesday, and so on. So I'm getting the value of the day that's
08:02 in the collection, as well as its numerical index using the enumerate function.
08:08 All right. So, that's loops in Python.
08:10
Collapse this transcript
Classes
00:00 Just like Javascript, Python gives you the option of writing code that is procedural
00:05 or object oriented. You can use classes in Python.
00:09 Classes are a really great way of encapsulating functionality that can be
00:14 kept together and passed around as a complete module for use in other projects.
00:19 And that's what where going to take a look at now.
00:21 So, let's open up Classes_Start here in chapter two.
00:25 And you can see that I've got the beginning of a main file here, but I'm not
00:30 going to add code to main just yet. What I'm going to do is in the example
00:33 snippets, I'm going to copy lines 133 through 138.
00:39 Copy that and I'm going to paste it in above main.
00:44 Okay, so I've got my class, and then, down in the snippits, I'm going to copy lines
00:50 149 through 151. Well, lets copy 148 as well.
00:57 Ok. So we'll copy those, paste those into main
01:01 down here. Okay.
01:03 Let's clean that up. Okay, so let's take a look at what's going on.
01:08 Classes are defined using the class keyboard and they're given a name, right
01:14 here, my class, and if this class was based on something else I would put the
01:19 name of that other class here in these parenthesis.
01:21 But this is just a base class that doesn't depend on anything else so, I don't have
01:25 to put anything in there. Inside classes, I can define functions or
01:30 in object oriented speak methods that are part of this class.
01:35 So, I indent twice, use the Def key word just like I would define any other
01:40 function, in this case I'm calling it method 1, and then am to find another
01:45 method called method 2. Now because this is object oriented,
01:48 usually the first argument to anyone of the methods, is the self argument, and the
01:53 self argument refers to the object itself. That's hence the use the word self, so
02:00 inside this method, self will refer to the particular instance of this object that's
02:06 being operated on. Down here in the main function, I
02:11 instantiate the class by declaring a variable, and saying equals and then just
02:15 the name of my class right here, which is called strangely enough myClass.
02:20 And that will new up or instantiate a version of this class.
02:26 And once I've got the class created, I can then call methods on the class like I can
02:30 call methods on any other object. I simply type the name of the variable and
02:34 dot and then the name of the method I want to call.
02:37 You can see here that I've got method two, which takes an argument called someString.
02:42 Notice that when I call the class, I don't have to supply the self keyword.
02:46 That's automatically handled for me by the Python run time.
02:49 I just have to care about the arguments that I'm passing in.
02:52 In this case, the string that I want to print out.
02:54 Okay? So we're going to save, and now let's run.
02:58 I'm going to do Python Run. So you can see that here, inside method 1,
03:05 we're printing out myClass method 1, and that's the result right here.
03:08 And then in method 2, we printout myClass method2 plus whatever string was passed in.
03:15 And you can see that that's what's happening because we're passing in this
03:18 string, and so that's the output that we're getting.
03:21 Okay, so let's take a look at another feature of object point and programing.
03:27 This time we're going to create another class, so we'll copy lines 140 through
03:31 146, and we'll paste them in here above main /g.
03:35 So now I've got 2 classes, I've got my class, and I have another class, and in
03:42 this case another class is based on my class.
03:47 Right? So what I'm doing is, I'm saying, another
03:49 class is inheriting from my class. So I've passed the name, my class, into
03:54 the constructor for another class. And you can see that what I'm doing here,
03:57 is I've got definitions for method 2 and method 1.
04:02 So, I'm overwriting the methods that were defined in my class.
04:07 So let's go back down to snippets. Okay.
04:10 Let's copy these lines here and let's paste the name to main, okay.
04:19 So now you can see that I'm creating c2, which is an instance of another class, and
04:27 then when I call method 1 on c2, that's this right here.
04:31 The first thing I'm going to do, is call the inherited method on the Superclass.
04:35 Which is the class I'm inheriting from. So I'm going to call my class .method1.
04:40 Which should print out my class method.1. Then I'm going to print out another Class method.1.
04:45 Okay? So I'm going to Save.
04:50 And going to run. So you can see that, the code that we were
04:53 originally using is still there. We've got my class method one and my class
04:56 method two, this is a string. But now we have another class.
05:01 So we have my class method one, which is being called on the inherited class.
05:05 That's this guy right here. Line 17 is executing, and calling the
05:09 parents' class, method 1, then it's printing another class method 1.
05:14 So let's go back into the code here and type c2.method2, in this case we're
05:25 passing different string, okay. So, here in another class, you can see
05:33 that method2 is not calling the inherited class.
05:37 Well, actually, this version doesn't even take an argument.
05:40 So, I'll just simply leave that out. (NOISE) And we're going to save that.
05:44 So, now, what's going to happen is this version of method2 is not going to be
05:47 called, because we're overriding it here in another class.
05:51 So let's save and run, and you can see another class method 2 is being called,
05:56 and since we're not passing in an argument, right, you can see that this
06:00 result here in the first class is not being executed.
06:04 Here in another classes method 1, we're calling this super class, here we're not
06:09 in method 2. Okay, so that's a quick introduction to
06:14 object orientated Python, and as you can see, you can define classes in Python, as
06:19 well as classes that inherit from other classes.
06:21
Collapse this transcript
3. Working with Dates and Times
The date, time, and datetime classes
00:00 Now that we've taken a look at the basics of the Python language.
00:03 We're going to turn our attention to using the rich library of predefined code that
00:09 comes with Python in order to build functionality into the Python applications.
00:13 And in this chapter we're going to focus on manipulating dates and times.
00:18 So here in my project I'm going to go to chapter three and I'm going to open up
00:22 dates_start, and I've got my examples snippets open and scroll down to Chapter 3.
00:27 Okay, so here's the starting point for the first example, now in order to get this
00:33 rich functionality that Python provides into your application.
00:37 You have to tell the Python interpreter to go get it from somewhere.
00:41 And the way you do that is by using something called an Import statement.
00:44 So let's go over to the example snippets and here in the date I'm going to copy
00:48 these three lines right here, alright, I want to paste these into the top of the file.
00:53 What I'm doing here is telling the Python interpreter that from the datetime module
00:59 I want to import the datetime and datetime classes.
01:03 These are predefined pieces of functionality in the Python library that
01:09 let me manipulate dates and times. So I don't have to write this code, it was
01:13 already written for me, and to use it I just need to import it.
01:16 So now that I've done that let's go ahead and exercise some of the features of days
01:21 and times. So let's copy these first few lines right
01:25 here from 166 to 169. (SOUND) Okay now put those in my main
01:32 function right here. So now that I've imported the date object,
01:36 we can start working with dates. So right here on line 12 I've got today.
01:40 So I'm declaring a variable and I'm saying today equals date.today and that will get
01:45 me today's date. And I simply print it out.
01:48 So I'm going to save this and run it and see what happens.
01:51 You can see that today's date is 2013-06-09.
01:56 Okay, pretty good, so we're off to a good start.
01:58 And by the way, remember, if when you click that Run button a little dialog
02:01 shows up, choose PythonRun, okay? Don't choose Python unit test.
02:04 You shouldn't have to do that more than once, by the way.
02:07 Okay, let's go back to the snippets. Alright, let's take a look at the
02:12 individual components of a date. So, I'm going to copy these lines right
02:17 here, and go back to date start, and I'll paste those in right there.
02:22 So, the today object that comes back, the variable that comes back from getting the
02:27 date.today function has several properties associated with it.
02:31 So, I can get the individual day, the individual month or the individual year
02:35 among other things. So, let's go ahead and save and print this out.
02:40 Okay, so, you can see that the date's components are 9 for the day, 6 for the
02:45 month and 2013 for the year. So, now, I can work with these individual
02:50 components, whenever I want to do date manipulations.
02:52 Now, let's go back to the snippets again. Let's copy and paste lines 174 and 175
03:00 into here. The date object also provides some useful
03:04 properties that I can use in other more advanced features of an application.
03:08 So for example, I can retrieve what's called the weekday number and that starts
03:13 off in 0 for Monday and goes up to 6 for Sunday.
03:16 So if I had some list that I wanted to provide an index variable for that
03:21 depended on the weekday. I could use those weekday property to
03:24 index into a list of, say, abbreviated day names.
03:27 Or something else where I'm using a list that represents a collection of days, so
03:32 that just returns an integer number. And we're going to click Run and you can
03:37 see that today's week day number is 6. So, today is a Sunday.
03:41 Okay, so, that's pretty good introduction to dates.
03:44 Let's start working with date time objects and I'm going to copy these lines here.
03:51 So, just like working with dates, I can get times as well.
03:56 So using the date time class, instead of the date class, I can call the now
04:01 function and that will give me the current date as well as the time.
04:05 Let's comment out some of these other lines that way they don't interfere with
04:11 this lesson down here. Okay, so let's save and let's run and you
04:17 can see that now the current day and time is 2013, June 9th.
04:20 And this is the time of day right here, so we've got hours, minutes, seconds and milliseconds.
04:27 All right let's go back to the snippets, okay let's get the current time.
04:33 I'm going to paste this in right down here.
04:37 To get the current time, we need to get the time portion of the date time object.
04:45 So I've got a variable here called T, and I'm going to construct a time object given
04:50 the full date and time from the date time class.
04:55 'Kay, so the datetime.time class, remember we imported that up here.
04:59 That's this guy right here. So we're importing time.
05:02 So I can now create a class, a time class, and I can give it the current value of a datetime.now.
05:07 And this will give me just the time. So let's go ahead and run this.
05:13 Okay, so you can see that here I got the date and time.
05:15 And then the next line, I've got just the time by itself.
05:20 Alright, let's do one more thing. Let's go back and use that weekday indexer
05:25 like I talked about a few moments ago. We'll see if we can make it do something
05:30 useful, so I'm going to paste these lines of coding here and let's comment out the
05:36 other ones. All right, so remember that that weekday
05:41 operator gives me a number 0 through 6, depending on what the current weekday is.
05:48 Here I'm declaring an array of days and I've got Monday, Tuesday, Wednesay, all
05:52 the way up through Sunday. So what I'm going to do is get the
05:55 weekday, print that out and then I'm going to print which is a and then the string
06:01 which is indexed by that weekday number. Let's go ahead and just say that today.
06:10 Okay we'll save that and we will run it and you can see that today is day number 6
06:16 and which is a Sunday . So here in the code write, I get today
06:21 that's the day (UNKNOWN) now I say okay what week day it is that gives me a number
06:26 0 through 6 and then I use that value as an index into this list right here of day names.
06:34 So if you want to use the weekday indexer into an array like this, that's how you do it.
06:39 Ok, so that's a quick introduction into using dates and times in python.
06:42
Collapse this transcript
Formatting time output
00:00 Now that we've seen how to use Python to retrieve basic date and time information.
00:05 Let's take a look at how to format the output using a set of predefined string
00:10 control codes. So, what I'm going to do here is in my
00:13 example snippets, I'll scroll down to formatting.
00:16 I'm going to open up the formatting_start file.
00:20 Now in this example file, I've already set up the import statement to import the
00:24 datetime class. So, you don't have to do that.
00:27 Back over in the snippets. Let's begin by copying over these lines
00:32 right here, 196 to 198. And we're going to paste that into the
00:36 main right here. So, this line of code should now look
00:40 familiar to you. I'm just retrieving the current date and
00:43 time using the daytime class's Now function.
00:46 Okay, so now that I've got the current date and time, let's take a look at some
00:50 of the options I have available to me to format the output.
00:54 Let's begin by looking at some date formatting.
00:56 I'm going to copy lines 200 through 202 first.
01:00 And these are just comments for now. So, to format date, you can use control
01:06 codes %Y and upper and lower case in this example mean abbreviated or full.
01:12 So, this is the abbreviated year of the full year, this is the abbreviated weekday
01:16 of the full weekday, and so on. If you've ever done any programming in C
01:20 or C++ and you used the standard C library.
01:23 These control codes might look familiar to you, so let's see how to actually use them.
01:29 Back in the snippets copy line 203 and let's put it back in the formatting start
01:34 file under here. So, I'm going to use the stir f time.
01:39 The stir f time function on the value that I got back for the current date and time
01:45 takes a string, which is a control string right here.
01:47 And replaces whatever the control code is. In this case, the %Y with the value that's
01:54 in the date or the time. So, this will print the full year with the century.
01:59 So, it'll be 2013. So, let's save, and run.
02:05 And choose Python Run if you see this dialog.
02:08 And you can see it prints 2013. Now if I change this to a lowercase y and
02:13 run it, you'll see it just prints 13 without the century.
02:18 Okay, so let's go replace that. Alright, let's go back to the snippets.
02:23 Now let's do something a little bit more advanced, let's get line 204 in here, so
02:27 line 204, we'll paste that. So, now I'm printing the abbreviated day
02:33 name with a comma, followed by the days number which is %d.
02:38 Followed by the full month name and the abbreviated year.
02:43 So, this is going to print out something like Sun, number of the day, the full name
02:48 of the month and the year. So let's go ahead and run that.
02:53 And you can see that's what it's printed out.
02:55 So, here it prints out Sun because the lower case a is for the abbreviated.
02:59 If I change this to an upper case A right, I run it again.
03:04 You can see now it says Sunday. So, it's a Sunday 09 June of 13.
03:10 Okay? Alright, so let's go back to the snippets.
03:15 Python also gives you a way of printing out locale specific information.
03:19 So, rather than having to figure out where your application is being run.
03:23 And how to print out information using the current localized versions of date and times.
03:28 There's a control code that does that for you.
03:30 So I'm going to copy line 206 to 209 and we'll paste them in down here.
03:36 Okay, so %C is the locale's date and time, lower case %x is just the date and upper
03:44 case %X is just the time. So let's comment out these lines right
03:49 here so they don't interfere. All right, and let's run this.
03:53 And you can see that it's printing out the date and time information.
03:57 The date and the time all appropriate for how I have my locale set up on my computer.
04:02 If I was running this on a computer in say Europe, then the information you see
04:06 printed here would probably look a little bit different based upon what the locale
04:09 settings are. Here I've got the month and the day first.
04:12 Other countries put the day and then month, and these control codes, C X and
04:17 uppercase X allow you to use whatever the locale's appropriate formatting is for
04:22 dates and times. Alright, back to the snippets.
04:26 Okay, let's take a look at time formatting now.
04:30 So, just the same way that you can print formatted data information, you can print
04:35 formatted time information as well. And I"m going to comment out these lines here.
04:41 Alright. So, same kind of idea.
04:45 You've got %I and h for 12 versus 24 hours, m for minute s for seconds and then
04:51 p for local's am or pm. So if I wanted to print out for example
04:56 the 12 hour base time with the minute and second and the am or pm, I would say % i,
05:02 % m, %s. And then a space, and then a %p.
05:05 If I want to use 24 hours, I would just say %h and %m.
05:09 So, let's go ahead and save and run. And you can see that's printing out
05:14 11:43:34 AM or just 11:43 when I use the 24-hour clock.
05:20 Now if it was afternoon, this would print a 24-hour based value, so 13 for example
05:26 for one o'clock. Okay so, as you can see, Python provides
05:30 some pretty rich control for printing out dates and times using complex formatting
05:35 just by using some control codes.
05:36
Collapse this transcript
Using timedelta objects
00:00 A common scenario involving dates and times involves performing mathematical
00:04 operations on dates and times themselves. And you'll run into this for example when
00:08 you want to calculate the number of days until an event.
00:10 Or you want to find out when an expiration is going to be and we can use the time
00:15 deltas class in Python to help us with this.
00:18 And that's what we're going to look at in this particular lesson.
00:20 So I'm going to open up timedeltas_start.py.
00:25 And you can see that I've already imported some information about dates and times
00:29 from the Python library. So let's go back to snippets.
00:32 So now what I'm going to do is import the Time Delta class.
00:36 I'm going to copy line 220, I'm going to paste that in here.
00:40 Okay so now I can use time delta information.
00:43 A time delta is basically a span of time. It's not a particular date.
00:48 It's not a particular time. It's a span of time and you can use this,
00:51 class, to perform time-based mathematics. So let's take a look at some examples.
00:58 Let's copy lines 222 and 223. All right.
01:03 So, to construct a basic timedelta, all you do is create the timedelta class and
01:08 pass in the amount of time that you want the delta to represent.
01:12 So in this case, I'm going to say days equals 365, hours is 5 and minutes is 1.
01:17 So this timedelta is going to represent a span of time that's one year, five hours,
01:22 and one minute. And I'm going to print that out.
01:24 So let's run this. I'm going to choose Python Run here.
01:29 And you can see that's what it does. It's 365 days, five hours, and one minute.
01:34 So that's the span of time for this timedelta.
01:36 Okay, let's start exercising this. Okay, let's print out today's date.
01:42 Okay, so this should look familiar to you by now.
01:46 All right. So we've got today's date right here,
01:49 today's date and time. Let's go back to the snippets, let's use a
01:53 time delta to figure out what today's date will be one year from now.
01:57 So let's copy 228 and 229 and paste those in.
02:03 So what I'm doing here is printing out, one year from now it will be, and then I
02:07 get the string value of daytime.now, right so that's today's date.
02:11 Plus a time delta whose span is 365 days, so that will give me the date in one year.
02:20 I run this and you could see that one year from now it will be June 9th in 2014.
02:24 Okay, so, that's pretty interesting. Let's keep on going and see what else we
02:29 can do. So, let's copy these two lines right here
02:33 and paste them in. So, now, I'm using a time delta that's
02:38 more than one argument. So, I'm saying, in two weeks and three
02:41 days, it will be and once again I get the string value of today's date plus a time
02:46 delta that spans two weeks and three days. Alright let's run that.
02:51 So now you can see that in two weeks and three days it will be June 26th at this
02:57 particular time. Alright let's go back to the snippets.
03:02 Okay, let's calculate the date one week ago and format it as a string.
03:08 So down here. And, by the way, you notice in this
03:12 example, I'm not using a main function. Python doesn't require that.
03:16 I've just been using it in some of the examples but I'm not going to use it in
03:18 all of them because I'm just using the Python interpreter to print out some
03:21 information here. Just wanted to point that out really quickly.
03:25 Okay, so down here, we've got calculate the date, one week ago formatted as a string.
03:32 So what I'm doing here is taking this statement on line 23.
03:36 I've got a variable named T. I get the current date and time.
03:40 And then I subtract off a time delta that's 1 week long.
03:43 Then, I use the stir F time function on the resulting time object, it was a
03:49 daytime object actually. I'm going to print out a formatted string
03:52 to say 1 week ago it was whatever that string hapens to be.
03:56 So let's run that, save it yep. And you can see one week ago it was
04:03 Sunday, June 02, 2013. So by using a time delta I can calculate
04:09 times both in the future and in the past. All right, let's take a look at one more
04:13 interesting example. Let's write a script that's going to
04:16 calculate how many days it is until the next April fools' day.
04:20 So I'm going to copy these lines right here.
04:22 Copy, and we will paste this in. So to calculate the number of days until
04:32 April Fools' day, there's a few things that I have to do.
04:34 So here on line 29, I get today's date. Now we know when April Fools' day is,
04:39 right, It's every year on April 1, so what I'm going to do is create another variable
04:44 name afd which represents April Fools' day.
04:47 And I'm constructing a date object that uses today's year, I retrieve the current
04:53 date on today. So whatever the current year is, on April
04:58 1st, that's April Fools' day. Now I need to use date comparison to see
05:03 if April Fools' day has already gone by for this year.
05:06 And if it has, I have to get April Fools' day for next year.
05:10 So here on line 33 I'm comparing the two dates.
05:13 You can use comparison operators on these objects, and I can calculate to see if a
05:18 date comes before or after another one. So in this case on line 33, I say, if
05:23 April Fools' day for the current year is less than today, in other words it's
05:26 already gone by, then I print out April Fools' day already went by.
05:31 And I say present d days ago, and then I'm using string formatting to get the number
05:36 of days that are different between today minus April Fools' day.
05:42 Since the current day is June, April Fools' day is in April, we can see that
05:47 April Fools' day has already gone by. So I'm going to use subtraction here to
05:51 subtract April Fools' day off of current today's date.
05:55 And get the days property to see how many days ago Aprils Fools' day was.
06:00 Now since April Fools' day has already gone by, I then use the replace method on
06:05 the date object to replace the current year with this year plus one.
06:11 So I'm just going to replace the year property that will give me a new date that
06:15 represents April Fools' day next year. Okay, now once we've done that, let's go
06:19 back to the snippets. Now, calculate the amount of time until
06:25 April Fools' day, so, copy these lines here, and we'll paste them in down here.
06:31 So, now that I've gone through all these calculations to figure out when April
06:35 Fool's day is, whether we're using the one for the current year, or the one for the
06:38 next year. Based upon whether it's already gone by I
06:41 can then subtract off today's date from April Fools' day.
06:46 So if it's already gone by, I've got the date for next year, otherwise I've got the
06:49 current date for this year. So I'm going to subtract those off, use
06:53 the absolute value Maths function to make sure I have a positive number of days.
06:56 And then print out the days property on the resulting time object to say, it's
07:02 this many days until the next April Fools' day.
07:06 So let's go ahead and run this and you can see, that since April Fools' day already
07:11 went by for this current year, since it's June.
07:14 Right here I've got April Fools' day already went by 69 days ago and it's now
07:18 296 days until the next April Fools' day. So you can see that by using timedeltas
07:23 you can do some pretty advanced and complex date calculations and you can use
07:27 these all over your Python programs.
07:29
Collapse this transcript
Working with calendars
00:00 Alright, let's wrap up this chapter by taking a look at few examples of how to
00:03 work with calendars in Python. Again, this is going to come up from time
00:07 to time, you'll have to work not just with dates and times, you'll have to work with calendars.
00:11 And Python's library provides a couple of useful utilities for working with
00:16 calendars in both text and HTML formats. So, I've scrolled down here in my snippets
00:23 to the calendars section, let's open up calendars_start.py.
00:29 So, let's begin by copying and pasting the import calendars statement.
00:36 So, notice how this is a little bit different then what you see me doing in
00:39 the past couple of examples, I'm not saying from module import something.
00:43 In this case, I'm going to say import calendar, because I want to import all of
00:46 the features that Python provides with the calendar class.
00:50 So, I'm not selecting any particular classes I want to work with, I just want
00:54 all of them. So, I'm going to save that.
00:57 Okay, let's go back to the snippets. Let's start off by just creating a plain
01:01 text calendar. So, I'm going to copy these lines right
01:05 here and paste them in. So, in this case, I've got a variable c.
01:09 And on the calendar class, I'm creating a text calendar, and I'm telling it that the
01:14 option I want to use is to use Sunday as the first day.
01:17 And then I want to format the month of January in 2013, and I want to print out
01:24 that formatted month. So, lets go ahead and save and run this,
01:29 and I'll choose Python Run. And you can see, now if I scroll down here
01:35 actually make this a little bigger so you can see it.
01:39 So, you can see that it's formatted January 2013 for me.
01:42 It's got Sunday as the first day and I've got one starting on Tuesday.
01:48 Alright, let's go back to the code. Let's just change this to calendar.MONDAY
01:53 and run it again. And you can see that in this example now
01:57 I've changed it, now Monday is the first day and it ends up here with Saturday and Sunday.
02:02 So, nice little option that you can put in there.
02:04 So, let's go back. Let's change this back to Sunday and save.
02:09 Alright, now let's see how to do the same thing with HTML.
02:12 So, we'll copy these lines right here, go back to calendar start, and paste them in.
02:19 Alright, let's comment out the previous example.
02:25 So, pretty much doing the same thing here, only in this case, I'm not using text, I'm
02:28 using HTML. So, right here I've got hc equals calendar.HTMLCalendar.
02:33 So, not using the text version. Once again, starting on Sunday and
02:37 formatting the month of January in 2013. So, let's run this, and you can see that a
02:45 whole bunch of HTML came back. And the HTML represents the table based
02:51 calendar that I've requested. In this case it's January.
02:55 You can see right here in the code, it says January 2013.
02:58 And you could also see that the Python calendar library has already put on some
03:03 helpful class attributes for me. So, in case I wanted to define CSS classes
03:08 like month and Sunday and Monday, and whatever else, I can do that in any CSS
03:12 code that I want to include this HTMLin. So, you can do this for example, on the
03:19 server side and then return the HTML back to the client however you want to, but you
03:23 have options for building calendars using both text and HTML.
03:29 Alright, back to the snippets. Now, you can also use the calendar class
03:33 to do things like dates and other kinds of mathematical operations on days.
03:39 So, for example, what I might want to do is loop over the days of a given month.
03:44 So, let's go back to the snippets here, copy these lines, paste them in, and let's
03:50 comment this out. So, what this example is doing is it's
03:55 using a for loop to loop over the days that are in a given month.
04:00 In this case, I want t iterate over the month days, and I'm using the iterate
04:04 month days function on a calendar class and I guess I need to create the calendar,
04:08 so, I'll uncomment that line right there to create the calendar.
04:11 And I want to get the month of August, which is month number 8 and the year 2013.
04:20 So, I'm going to get back a number that represents each day in the month.
04:24 So, let's run this and you can see the output.
04:28 And what's happening is, it's looping over all the days.
04:32 So, in August, there were 31 days. So, you have, see there's day number one
04:36 and day number 31. Now, the zeroes at the start here indicate
04:41 that there are days in the week that belong to another month.
04:46 So, what's happening is, this right here, c.itermonthdays is going to come back with
04:50 a list of days. And it's going to come back with a list
04:54 that starts on a Sunday and goes all the way through to the end of the month.
04:58 And in the output, you'll also see output trailing zeroes sometimes too.
05:03 What that means is, so, for example, Sunday in this month happens to belong to
05:08 another month. And the first time we see the number 1,
05:11 that's is Sunday, Monday, Tuesday, Wednesday, that's a Thursday, so, that's
05:15 what happening here. You're seeing that the zeros are being
05:18 padded in to represent the day's that don't belong to the month of August.
05:22 Alright, just go back to the snippets. So, the calendar class also provides some
05:30 useful utilities for the current locale. So, what I can do is cut out these lines out.
05:38 I can loop over the names in the month names and day name properties on the
05:43 calendar class. So, I don't have to have code in my
05:47 application that knows what the names of the months are around the world, the
05:51 systems locale will just give them to me based upon where the user happens to be located.
05:57 So, let's save this, and let's run it. And you can see that because I'm here in
06:03 the US, right, I'm getting months January, February, March.
06:07 If I was in another part of the world or my local system here was set to be
06:11 someplace in Europe for example, I would get the locale based names.
06:16 And again, you can see I'm getting Monday, Tueday, Wednesday up through Sunday.
06:19 So, I can get the names of both the months and the days as they would appear in the
06:26 current locale for where the computer is or for where the system happens to be set to.
06:32 Alright, let's do one more example. Let's go back to the calendars for example
06:36 as we get these commented out. Alright, Save.
06:42 So, let's take a practical example. Suppose I had a team and the team met on
06:48 the first Friday of every month, and I wanted to write a script that would print
06:53 out what those days actually are. That way, I could give those list of days
06:59 to my team members and they would know what the dates are.
07:02 So, what I need to do is calculate when the first Friday happens in each month,
07:08 and then build up a date that represents that day.
07:12 Okay. So, let's do that.
07:13 Let's copy these lines right here. (INAUDIBLE) Let's start off with these
07:19 lines and I'll explain them as we go along.
07:21 Alright, back over to calendar start and let's paste them in.
07:26 Alright. So, what I'm doing is writing a for loop,
07:29 and I'm going to have m, which represents the month, in the range of 1 to 13.
07:36 And remember 13 is on inclusive, so, I've got 1 through 12.
07:39 So, each one of these numbers is going to represent a particular month, so 1 will
07:43 represent January, 2 is February and so on and so forth.
07:47 Now, what I am going to do is get an array of weeks that represent each one of the months.
07:53 So, for each time through this loop, m will be a month number.
07:57 And then I'm using the calendar class' month calendar function to get an array of
08:02 weeks that represent the days in the given month.
08:06 And so, I'm going to use hard-code the year 2013, and I'm going to request that
08:10 array for each one of those months. Now, the first Friday has to be somewhere
08:16 within the first two weeks. So, I've got two local variables here,
08:20 week one and week two. And so, I've got cal-0 and cal-1.
08:26 Okay, remember that the length of this Cal object is going to be you know, a certain length.
08:31 It's going to be either four or five depending on how many weeks there are in
08:34 the month. Now, I'm only interested in the first two
08:36 weeks, because the first friday has to be in there somewhere.
08:39 Let's go back to the snippets. What I'm going to do now is copy these
08:45 lines 293 to 97, and paste those in. Okay.
08:54 So, now I'm saying okay, if week one, right, I've got this list right here.
08:57 And I'm using the calendar's constant Friday, the calendar object gives you
09:02 constants that represent Sunday, Monday, so on, so forth.
09:05 We've seen these previously. So, I'm saying hey, if in week one the day
09:10 represented by the Friday constant is not equal to 0, remember zeros represent days
09:16 that belong to another month. So, in this case, if it's zero, it's
09:20 going to be a Friday that belongs to the previous month.
09:23 But if the first Friday is not equal to 0, that means that my meeting day happens to
09:29 be within the week one list. Otherwise, if that is 0, then the first
09:34 Friday isn't in the first week of the month, it's gotta be in the second.
09:38 So, then I say okay, set my meetday variable to be the Friday represented by
09:43 Week two. So, meetday is going to come back with
09:47 whatever the day is for either the first or second week.
09:51 Alright. So, we'll save.
09:53 Now, my last one here, I'm going to print the day that's represented by that value.
10:05 So, I've got a formatting string here, and all I'm doing is printing a string.
10:09 And again, if you've used C or C++, these print formatting strings probably look
10:13 familiar to you. What I'm doing is saying, print out a
10:16 string which is represented by the calendar's month name and pad it by ten
10:20 spaces, that way they all line up nice and neatly.
10:23 And then print out an integer number which is represented by the meetday.
10:28 Again, pad that by two spaces, that way everything is all nice and lined up.
10:34 So, the best way to understand what's happening here is to actually run it.
10:36 So, remember, we've got a loop. This is going to happen for each month.
10:39 So, for each month, this print statement is going to print out the day, the actual
10:43 date that the first Friday appears in that month.
10:47 Alright. So, let's run this.
10:51 Okay. So, let's scroll up, and I'm actually
10:53 going to make this window a little larger so, you can see the full output.
10:58 Alright. A little larger.
11:02 There we go. So, you can see that we've looped through
11:05 all the months, and here's the padding effect of that format string.
11:08 You can see that I've padded out the information, so, it all lines up nice and neatly.
11:13 So, the first Friday in January falls on the 4th, in February it's the first and so on.
11:17 You can see down here in June, the first Friday falls on the 7th.
11:20 So, now I can give this list of dates to my team and they'll know what the actual
11:27 dates are for the first Friday in each one of the months when we're going to have our
11:31 team meeting. This is the power of Python.
11:34
Collapse this transcript
4. Working with Files
Reading and writing files
00:00 Python provides built in methods for working with file types.
00:04 You can open files, write data into them, add data onto the end, read the data back
00:09 in and so on. Basically, all the things you expect to do
00:13 with file objects and that's what we're going to take a look at here in the next chapter.
00:18 So, in my example snippets I've scrolled down to the file section, and in chapter 4
00:22 lets' begin by opening up the files_start.py file, alright.
00:27 So over here in snippets, let's go ahead and copy in these lines right here, and
00:34 you don't need to do any imports here. The file type is just built into python,
00:38 so I don't need to import any classes just to be able to write files.
00:42 So this line right here line 7, creates a variable named F.
00:45 And I'm calling the function open to open a file named textfile.txt.
00:49 So open takes 2 arguments, the file I want to open, and then a string
00:55 representing the kinds of permissions or operations I want to do on the file.
01:00 So in this case I'm passing in the letter w which means write and the plus sign
01:03 which means create it if it doesn't exist. And the available options here are w for
01:09 write and r for read and a for append and plus sign means if it's not already there,
01:15 make it for me. And we'll see examples of the other
01:18 options like reading and appending in a little bit.
01:21 Alright, so now that we've opened the file Let's go back to the snippets.
01:25 Let's just write some stuff into the file. So, we'll copy these lines here, and we'll
01:31 paste them in. And save.
01:32 So, what I'm doing here is, I have a 4 loop that runs over a range of 10 numbers,
01:38 and then just uses the write function to write into the file, this is line number
01:44 and then percent d, so I'm just putting in the line number that I'm writing and I'm
01:50 putting in a carriage return and a new line character.
01:53 So when this executes there should be 10 lines of information in the file just
01:58 saying this is line 1, 2, 3 for example, and then after I do that.
02:03 Back here in snippets, I have to make sure that I close the file when I'm done with
02:07 it, so I'll copy these lines and I'll just paste them in right here.
02:11 Alright so, just to recap we open the file, we write some information into it
02:17 and then we closed it. So let's run this.
02:20 So we save, click run, Going to choose python run, and if you notice over here,
02:28 text file.txt was successfully created right here in the example files, the same
02:32 directory where this code is located. And if we open it up you can see it says
02:37 this is line 1, line 2, line 3 and line 4, and so on and so forth just like you would
02:41 expect, okay, so let's close that.. Now, let's go back to the snippets.
02:47 And instead of opening for writing, let's open up for appending text to the end.
02:53 Okay, so we'll copy all these lines right here and we'll paste them in here.
02:58 And we'll uncomment that line and we'll comment out this line.
03:02 So now, instead of opening with write access, I'm going to open up with append access.
03:09 When I open up a file for writing, I'm going to overwrite all the contents that
03:13 are already in there. If all I want to do is add stuff onto the
03:16 end of the file, I use the append permission.
03:19 And once again, the plus size means create the file for me if it's not already there.
03:22 But in this case it is already there so, we don't need to worry about that.
03:26 Alright. So I'll save.
03:28 Now this is the same code here, it's going to write the lines.
03:31 So, what's going to happen is here in the text file, I'm going to have all this
03:35 original content, and then this should all be repeated all over again when the next
03:40 set of lines are written in there. Alright, so let's save and let's run.
03:46 Okay, now let's open it back up. And you can see, that the original ten
03:52 lines are there, followed by the ten lines that got written in.
03:57 Alright, so far so good. Let's go back to the snippets.
04:01 Right, now that we have the file created, let's open it up and read the information.
04:05 Copy and we'll paste. So now, let's comment out all the stuff
04:16 that does the reading and the writing so that we don't get any interference, all
04:21 right, so now I'm going to call open with the read permission to read the file.
04:27 Now there's a couple of ways to read the file.
04:28 If I want to read the entire thing, I can just use the read function.
04:31 So the (INAUDIBLE) this lines equals f.read and what I'm doing here is opening
04:37 up the file with read permission. I check the mode to make sure that the
04:40 file was opened. So if the mode is equal to read, then
04:45 things must have gone right and the file is now open for reading.
04:48 I'm going to use contents equals f.read. And then I'll just say print contents.
04:53 Alright let's run this, and you can see here in the output window in (UNKNOWN)
04:58 studio, you can see that the contents of the file are indeed being read in and
05:04 printed out. Alright.
05:07 You can also read the contents of a file line by line, so if you have a really
05:12 large file. Sometimes doesn't make sense to read the
05:14 whole thing in. Especially if all you want is 1 piece of it.
05:17 So what we'll do is copy these lines here, and we'll paste them in, and we'll comment
05:26 these out. So in this case, here on line 26 what I"m
05:32 doing now is calling the read lines function.
05:35 Read lines will read each individual line into a list, and then I'm going to use 4x
05:42 in that list of file lines to print out each individual line.
05:45 So the net effect should be the same that you just saw, only I'm just doing it a
05:49 different way, I'm eating in each individual line and then printing it.
05:53 So let's run. And you can see that once again, what's
05:56 happening is I'm reading in each individual line and printing it out.
06:00 Alright. So that's a quick introduction to using
06:04 file objects in Python.
06:06
Collapse this transcript
Working with OS path utilities
00:00 Sometimes you need to do some work with files that goes beyond things like reading
00:04 and writing data. You need to find out information about the
00:07 file, whether it exists, what the path of the file is, whether a path is a file or a
00:12 directory and so on, and Python provides path related utilities to help you do
00:16 this, and that's what we are going to look at in this particular movie.
00:19 So, let's go over chapter four and open up ospathutils_start.py.
00:25 And then from the snippets let's do something really simple just to begin with.
00:29 Let's copy this line here import os. And we'll paste that in here, and then
00:35 let's copy in this line of text right here that just prints the name of the os.
00:41 Okay, so I'm importing the OS or Operating System Module from Python into this
00:51 example, and let's just run what we have right now.
00:54 So I click Run, go choose Python Run, so I run it.
00:59 And you can see that I'm printing out the letters nt so I'm running Windows eight
01:04 here and the OS name as far as programmers are concerned is nt.
01:08 Now you might see a different name based on what kind of computer you're using, if
01:12 you're using a Mac for example or Linux or whatever then you'll probably see a
01:16 different string here. Alright let's go back to the snippets.
01:20 Now let's import the path module from the os module.
01:26 So now we're going to say from os, import path.
01:30 So these are the path utilities that we are going to need.
01:33 And let's just exercise some of the things that you can do with the path module.
01:37 So let's copy these lines right here, copy.
01:40 And by the way. We'll just pass this in.
01:43 Okay. So, this example is going to depend on the
01:46 fact that this text file, .txt file exists.
01:50 So, if you didn't do the previous, movie where this file gets created and
01:54 manipulated, you might want to go back and do that now, so that the file is here, for
01:58 this particular lesson. All right.
02:00 So, all we're going to do is use the path module to do things to see if the items
02:05 exists, whether it's a file, whether it's directory, that kind of stuff.
02:09 So let's save and let's run it. And you can see that the item does in fact exist.
02:18 That the item is in fact a file, and it is not a directory.
02:24 So, okay, so far so good, we using the path module to get some basic information
02:28 about an item. To see whether it exists or what it's type is.
02:31 All right, let's go back here. Let's do some work with the file path
02:38 itself, so we'll copy these lines and we'll paste them in.
02:45 And let me comment out some of these other lines, so that we can clearly see what
02:51 we're doing. All right.
02:55 Okay, so what we're going to do now is use the real path function on the path module
03:00 to figure out what the actual full path is to this text file, .txt.
03:06 And I'm using the Str function to make sure that that's a string, so that I can
03:09 (UNKNOWN) with this string right here. So I'm going to get the realpath and then
03:14 I'm going to use the split function to take the realpath to this file and split
03:20 it into two different things, the path to the file and the name of the file itself.
03:25 That's a pretty common operation that you'll find when you working with files.
03:28 Sometimes you just need the file's name sometimes all you care about is the path
03:32 and that's what the split function gives you.
03:34 Alright, so I'll save and I'll run. And you can see that the path to the item,
03:40 the full path is 'C:\\Users\\Joe\\Desktop\\Exercise
03:44 FIles\\Ch4' , 'textffile.txt'. And in this case I've got a path and a name.
03:49 So here's the path. Alright, and here's the name of the file.
03:53 So that's a really useful utility for splitting out the file name from the path.
03:58 This happens all the time in real programming scenarios.
04:02 Alright back to the snippets. Alright, let's figure out the modification
04:10 time of the file. So let's comment these.
04:16 So what I'm going to do is, oh I also have to import the date and time stuff because
04:21 I'm going to be using time information. So let's copy these import statements here.
04:27 Put them at the top of the file to make sure that I've got all my stuff in a row,
04:30 that way I don't get any complaints about using modules I haven't imported.
04:34 And what I'm going to do now is use the path module to get the modification time
04:40 of the file and then I'm going to use the time classes c time function to convert
04:46 that into a readable time. And then I'm going to print that out.
04:50 And actually let's comment line 26 just for the moment so we can see that operation.
04:55 So we'll run this, and you can see that the file was last modified Sunday, June
04:59 9th at 12:28. Which is not surprising because if you
05:03 were following along with the course then you would see a similar time if you
05:07 modified it just recently. But it shows you the modification time of
05:11 the file. All right, let's do something a little bit differently.
05:17 Now, I'm going to use the Get Modification Time function from the path and I'm
05:21 going to construct a date time object using the From Time Stamp function that's
05:26 built in to the date time class. All right so let's comment out the print t
05:32 right there just so that we're getting this result so we run that.
05:36 And you can see that the different format is now being printed.
05:39 Now I've got a date time format rather than a c time format.
05:44 So let's go back and uncomment line 25 so you can see the difference between the two.
05:50 So in one case I've got a nice, user-readable format.
05:54 In this case I've got a format that looks more like a regular date time object.
05:59 Alright, so let's go back to the snippets. Okay, let's do some date math.
06:07 And if you watched the chapter on manipulating dates, then this will be a
06:10 little bit of review for you. But again, it shows you some useful things
06:13 you can do when you combine more than one module in Python.
06:17 So here I'm combining the path module and the date time module to do some useful work.
06:22 So we're going to calculate how long ago the item was modified.
06:25 So let's copy these lines. And we'll paste them in, okay.
06:32 And what we'll do is we'll comment out these lines here just so we can focus on
06:37 this work right here. So I've got a variable named td.
06:41 And I'm going to get the current date and time using the now function.
06:46 And I'm going to subtract off using date math the value of the get modification
06:52 time, and I'm going to use the from timestamp method on the date time class.
06:57 So, recall from the previous example we just did right here, that gets a system
07:03 looking kind of time. So, I'm going to construct up a date time
07:07 from that timestamp. I'm going to construct up a date time
07:10 using the current date time. I'm going to subtract one from the other,
07:13 and I'm going to convert that value, this variable right here, into a string.
07:18 And it's going to say, it has been, you know, the time difference since the file
07:24 was last modified. And then, I'm going to use the total
07:27 seconds function. On that time delta object to say it's also
07:33 been this number of seconds. So we'll save and we'll run.
07:37 And you can see, it's been about 13 minutes.
07:40 So, zero hours, 13 minutes, 31 point some odd seconds since the file was modified.
07:46 Or if you like instead 811.913149 seconds so that's combining time deltas in the
07:56 time module class with the path module to do some useful work.
08:00 You'll see this kind of thing in Python all the time.
08:03
Collapse this transcript
Using file system shell methods
00:00 Python provides a set of utilities for manipulating files using the Operating
00:05 System's shell utilities. And that's what we're going to look at in
00:08 this example. So here in my example snippets file I
00:11 scroll down to the shell section. And let's start by opening up shell_start.py.
00:18 So from the snippets, let's copy and paste these three lines right here.
00:25 And we'll paste them at the top. And, let's start off doing something
00:31 pretty simple. Let's make a duplicate of an existing file.
00:35 Okay. So let's copy these lines to begin with
00:39 and paste them into the main. Okay.
00:42 Now this example depends on text_file.txt existing, and you can see I've got it over
00:48 here in my list. if it's not there for you it's probably
00:51 because you didn't do one of the previous exercise.
00:55 So you should go do one of the previous exercises to make sure that this file
00:58 exists right here. All right, so what we're going to do is
01:02 use the path module's exists function to make sure the file exists.
01:07 And then assuming that it exists, and you can see that it does, we're going to get
01:10 the path to that file and store it in the source variable right here.
01:18 So once I've done that I'm going to get the separated path and file name.
01:28 So, here I'm going to use the split function on the source variable to get
01:33 back the separated path from the file name.
01:36 So, let's just run that and see what we have so far.
01:38 Let's save okay, so you can see that I've got the path and the file name separated
01:44 out, alright so far so good, okay. What we're going to do is make a duplicate
01:50 of it and give it a new name. So let's copy these lines right here and
01:55 go back in and paste. So I'm going to take the original file
02:00 name textfile .txt and put the letters .bak on the end to indicate that it's a
02:06 backup copy. And then I'm going to use the shell
02:08 utility's copy function. Right here on the shutil module to copy
02:14 from the source to the destination. So, basically the destination variable is
02:18 the same as the source just with .bak on the end.
02:22 So, let's run that. All right, and you can see over here in
02:28 the list sure enough textfile.txt.bak got created all right.
02:34 So that's how you use the shell to make a copy of the file, and let's go back into
02:39 the snippets. Now the copy function only copies over the
02:44 contents of the file. If you want to copy over things like the
02:47 file permissions and the other meta data associated with the file like the
02:51 modification time and so on. You need to use the copy stat function.
02:55 So we'll copy that and we'll paste it in over here, paste, alright lets save.
03:03 Now lets go delete this file so we can do the whole thing all over again.
03:07 Alright. So let's run this.
03:11 Okay. And you can see that textfile.txt.bak was created.
03:19 And if you go look at the properties of that file in your operating system shell,
03:23 you'll see that all the other metadata was copied over as well.
03:26 I'm not going to do that here because its beyond the scope of the exercise, but, you
03:30 know, if you want to do some extra credit go look at the file in your OS shell.
03:34 All right. Let's go back to the snippets.
03:36 Now let's rename the original file. So we'll copy these lines here and down
03:44 here at the bottom. (SOUND) All right.
03:47 So let's comment out all the stuff that we used before because we're not going to
03:51 need it again. So what I'm doing here is using the rename
03:58 function on the OS module to rename textfile.txt to newfile.txt.
04:04 All right, so we'll run this. And let's go over here and Refresh.
04:13 And you can see, sure enough, that textfile.txt was renamed newfile.txt, okay?
04:17 So, we can use the shell to rename things, that's pretty cool.
04:22 All right. Let's do something even cooler.
04:25 Let's put stuff into a ZIP archive. So, I'm going to copy these lines here and
04:32 I'm going to comment out the renamed function and I'm going to paste these
04:35 lines in. Alright, let me scroll down a little bit
04:38 so you can see what's going on. Okay.
04:41 So we're going to use the shell utilities make archive function in order to create
04:46 an archive file that contains the contents of the directory.
04:50 And in order to do that I'm going to need to import the make archive class from the
04:59 shell utilities. I'll copy that, scroll up here and paste.
05:05 All right. So what we're doing is we're using the
05:09 split function to split out the directory and the file name from the full path to
05:16 the location of the textfile.txt file. And actually since we just renamed that,
05:23 we should probably fix this problem by changing this to say newfile.txt.
05:30 Okay. So now that code will work.
05:33 So what we're going to do is get the path to that file, split it into a directory
05:37 and a tail, and then we're going to call on the shellutil module, the make archive function.
05:43 This is the name of the file that will be created.
05:44 It's going to be called archive. The type that we want to create is a zip archive.
05:48 And Python lets you create different kinds of things.
05:51 You can create Tar files for Unix, and so on.
05:54 But for the purposes of this example, we're going to create a zip file.
05:57 And then we pass in the root directory of things we want to be zipped up.
06:01 So, everything in this directory, the directory where the file's located is
06:04 going to be zipped and put into an archive.
06:07 So, let's save. All right, let's run it.
06:10 Okay, let's Refresh. And you can see that archive.zip got created.
06:18 So I am going to right click on this and choose show in Window's Explorer.
06:23 And, this may look different for you on Mac or Linux, but, the show in feature
06:28 should be there. And you can see right here, here's
06:32 archive.zip, so I'm going to open it up. And you can see that everything in the
06:37 folder, all the example files, the text files, everything got added to the zip file.
06:42 Now that's not exactly what I wanted. I only wanted to put the text file and
06:46 txt.bak file into the archive. So lets close this.
06:52 Lets go back into Aptana Studio . Lets delete this archive.
06:59 Okay. Alright.
07:02 I want to have more control over my zip file, so what I'm going to do is, in
07:05 example snippets I'm going to import the zipfile class from the zip file Python module.
07:13 And this module gives me full control over creating zip files.
07:16 So I'm going to paste that in up here, save.
07:19 Alright let's go back to the snippets and let's do some more fine grained control
07:25 over my zip file. Alright.
07:28 So I'm going to paste this in down here and I'm going to comment these guys out.
07:34 Alright. So by important this zip file class I can
07:38 now have much greater control over creating zip files, so here's what I'm
07:43 going on line 36. I'm saying with, and with is a Python
07:46 construct that creates its own local scope for working with objects.
07:51 So, what I'm saying is, with creating a new ZipFile class and a creator file
07:55 called testzip.zip, I need to pass in the permissions I want, because it's a file.
08:00 So I want to write information into the file as newzip.
08:06 Now when I say as newzip, inside this with scope block I can use this variable to
08:11 refer to a zip file that I just created. So what I'm going to do is say
08:15 newzip.write, we use the write function on the newzip variable.
08:20 Which is a zip file class object, I'm going to write the newfile.txt file, and
08:25 I'm going to write the backup file that we created into that archive.
08:30 So now, I'm not going to add all the example files, just the files that I want
08:33 to be in the archive. So, I'm going to save, and I'm going to run.
08:37 Okay. And we'll give it a second to refresh,
08:42 I'll just refresh it. Okay.
08:44 So you can see there's test zip.zip. And by the way I want to point out that
08:49 the reason why I'm not closing off the zip file here with you know newzip.close.
08:53 For example is because inside this width scope lock, when the flow of control the
08:59 program falls outside of the scope. The file will be already cleaned up and
09:03 automatically closed for me. It's just something that Python does for
09:07 you when you use scope locks like this. Okay.
09:10 So let's go out and look at the zip file. So once again we'll show it in the OS.
09:15 So there's test zip.zip. If I open it up, you'll notice that only
09:19 those two files were included in the zip archive.
09:23 So you can see that using the shell utility's module of Python gives you
09:27 really great control over working with file objects.
09:30
Collapse this transcript
5. Working with Web Data
Fetching Internet data
00:00 One of the areas where Python really shines is in retrieving and working with
00:04 data from the Internet. Data such as JSON, XML, HTML, you can use
00:10 Python to work with this data directly, and Python makes it really easy.
00:13 And that's what we're going to show in this chapter.
00:16 We're going to start by showing how to retrieve Internet data from the Web.
00:20 So, here in my example snippets, I've scrolled down to chapter five and the
00:24 internet data section. So, over in the files, open up inetdata_start.py.
00:33 And we're going to do copy and paste here. So, the first thing I'm going to do is
00:37 copy and paste this import statement. So, I'm importing something called the URL
00:42 lib two module. URL lib two is a python module that
00:45 provides utilities for connecting to web addresses and retrieving data from them.
00:52 So, we'll see how to do that. So, let's copy a few more lines of code
00:58 and we'll paste this in. So, I'm defining my main function and I
01:02 have a variable here called weburl. And what I'm doing is I'm calling the
01:06 urlopen function on the on the URL lib two library.
01:09 And the URL I'm opening up is just the URL for my homepage.
01:15 So, this will open a connection to my homepage.
01:18 Back here in the snippets, let's copy the next line and paste that in.
01:22 So, now I'm going to print out the result code.
01:26 So, the result code is retrieved by calling the getcode function on the webUrl
01:30 variable that I've created. going to convert that to a string, so, I
01:33 can concatenate it with this string over here.
01:35 So, this will be a regular old HTTP result code.
01:40 So, for example, 200 if everything's okay, or a 404 if not found.
01:45 That kind of stuff. So, we've got something we can run here.
01:47 So, let's go ahead and save and run. And you can see that the result code is in
01:53 fact 200. So, I'm able to connect to my website
01:56 without any errors. Alright, let's go back to the snippets.
01:59 Now that we've got the URL open, let's read some data and print it out.
02:04 So, I'll paste these lines in. Alright.
02:08 Here on line 15, I'm calling the read function on the webUrl variable I've created.
02:15 So, recall from earlier, we had a read function that allowed us to read the
02:19 contents of data files. I'm doing pretty much the same thing here.
02:23 I'm just reading the entire contents of this URL into a variable called data and
02:28 then I'm going to print the data out. So, if all goes well, this should be the
02:32 HTML code for my home page. So, let's save and let's run, and sure
02:38 enough you can see that it's working. HTML code is coming back, looks like
02:42 everything is just fine. There is the result code of 200.
02:46 Okay. So, that's a quick introduction to how to
02:51 read data from the Internet, and we'll see how to use this a little bit more in depth
02:55 in the next movie.
02:56
Collapse this transcript
Working with JSON data
00:00 In this example we're going to see how to use Python to connect to a real time JSON
00:05 data feed out on the internet and process the information.
00:08 JSON stands for JavaScript Object Notation and you'll run into this a lot when you're
00:13 working with data feeds. The data feed that we're going to be using
00:16 is the US geological surveys earthquakes data feed.
00:21 You can see here that the earthquake data feed is provided by the USGS, and they
00:25 provide the feed in a variety of formats. They provide Atom, they provide JSON and
00:30 if you click on this link over here Geo JSON summary, this describes the format of
00:36 the JavaScript object that comes back from the data feed.
00:39 So we're going to be using this information to get information about
00:43 current earthquakes all around the world. All right so let's go back to the code and
00:47 get started. All right so here in my examples (UNKNOWN)
00:50 I've scrolled down to the JSON data section go ahead and open up jsondata_start.py.
00:58 Now I've already defined the main function and I've got a variable here called URL
01:03 data, which is pointing to a URL that the USGS uses to to deliver JSON data for all
01:11 earthquakes in the last day that were larger than the magnitude of 2.5.
01:15 So you can see right here on the URL, it's 2.5-day.geojson'.
01:21 Now, there are other links. You can get all of them larger than
01:23 magnitude one, larger than magnitude five. I think there's one for the last hour,
01:28 (UNKNOWN) day. We're going to be using this one to make
01:30 sure that we get some good data. Okay so this is the URL that's going to
01:34 deliver the JSON to us. So let's go back to the snippets.
01:38 The first thing that we'll need to do is import the modules we'll need to use in
01:41 order to get the data and process the JSON, so these two lines right here, I'm
01:46 going to copy those and paste them in up here.
01:48 So I'm importing the URL lib2 library, which is what we're going to use to open
01:52 the URL and retrieve the data, and I'm importing the JSON library, which will
01:56 allow us to manipulate the JSON information.
01:59 All right, so let's save. Okay.
02:01 So now, let's scroll down here. Let's copy these lines here, 457 through
02:11 465, and let's paste them into our main function.
02:14 Okay, so just like in the previous example, I have a web URL variable and I'm
02:23 calling the URL open function on the URL to get the data.
02:27 I'm going to print out the result code to make sure that we're getting a result code
02:33 of okay, or 200. If the result code comes back as 200,
02:37 we're going to read the data from the URL. This will retrieve the JSON data from the
02:44 website, and we're going to write a function called printResults, which will
02:47 print out our customized results. Otherwise, if something comes back other
02:51 than 200, there was some kind of error and that print out an error message to the
02:55 console here. Alright.
02:56 So let's save that. Now let's go back into the snippet, and
03:01 scroll back up okay, this is the function we were going to write to print out the results.
03:08 Okay, so let's copy the first few lines and paste them in up here and above our
03:13 main definition. Alright so we're defining a function
03:17 called print results and it's going to take one argument called data.
03:21 Now to load the JSON that comes back from the website into what's called a
03:25 dictionary object, which is basically a, hash table if you've ever used it in
03:30 JavaScript or something like that we're going to call the json.loads method, we're
03:35 going to pass it the string that comes back with the JSON data from the website.
03:40 This will give us a native Python object that we can use to process the information.
03:45 Okay, so let's go back to the snippets, once we've done that we can access the
03:49 contents of the JSON like any other Python object.
03:54 So I'll paste that, okay, and it says if the word title is in the JSON object's
04:01 metadata section, then print the metadata title.
04:09 So let's go back to the website really quick where we're getting the data from to
04:12 take a look at this. So recall over here in the JSON data feed, right?
04:17 Here is the metadata section, and there is the title property.
04:22 So we're making sure that the title property exists in the metadata collection
04:27 and then printing it. Alright, so let's go back to the code.
04:30 Okay, so back here in the code we're going to print out the title property
04:33 that's in the metadata section. So let's save and let's run this.
04:39 And we'll do Python Run. Okay, so there's the result code.
04:42 It's 200. Everything's fine, and the title is USGS
04:46 Magnitude 2.5 plus Earthquakes in the Past Day.
04:50 So, it looks like getting the JSON data correctly, we're loading it in correctly,
04:54 and everything seems to be working. So before we go any further let me show
04:59 you debugging here in Aptana studio with Python.
05:03 I'm going to right click on this line number right here and choose Add Breakpoint.
05:08 You can see the little break point shows up there when I do this.
05:11 So now if I want to debug this I can debug this like any other application.
05:15 I'll just simply choose the little Bug icon up here instead of the Run icon
05:19 because I want to actually debug this. So I'm going to debug this and the
05:24 Debugger is going to launch and I'm getting a little perspective that says hey
05:28 you know Aptana has this thing called a Debug perspective.
05:31 And if you watch my title on using Aptana Studio you'll be more familiar with this
05:34 but for now I'm just going to say Remember my decision, click Yes.
05:38 So it's switches over to the debugging view, okay?
05:42 And you can see that the breakpoint right now is sitting here on line 12.
05:45 See the little arrow right there? So now I can look at, for example, the JSON.
05:50 And I can hover over it to get the contents or I can look up in here, right?
05:56 You can see that we've now created a native JSON object.
06:00 In Python, right? So here I've got my features, here's the metadata.
06:05 So we look inside the metadata and sure enough, there's the title property right there.
06:10 You can see that a string saying pretty much exactly what we expected to see.
06:15 Alright and we go back outside the metadata, now the features array will
06:19 contain information about all of the different earthquakes.
06:23 So if we open one up you'll see that there's a whole bunch of data in here.
06:26 There's a geometry, there's a properties object, which is what we're interested in,
06:30 and so inside the properties you'll see a whole bunch of information about the earthquake.
06:36 And we'll get more into this as we go through the example, so for example the
06:39 magnitude is 2.6, alright, but we'll see more of this as we go through the examples
06:43 so let's just go ahead and terminate this. All right.
06:46 Let's go back to the web view, and let's take off the break point.
06:50 Let's go back to snippets. So, now what we're going to do, is output
06:54 the number of earthquakes that we found, plus the magnitude and the name of each event.
07:01 All right. So, let's copy, and let's paste these
07:05 three lines. So I have a variable called count and
07:09 inside the metadata there's a property called count, which is the number of
07:13 events that were recorded that day. And then we're going to print out the
07:17 stringified version of that number plus the string events recorded.
07:20 So let's just run this. And you can see that today at least there
07:25 were 23 events recorded. Now the data's going to be different for
07:28 you based upon what day you visit this website on.
07:31 So your data probably will not be the same as mine but you should see some similar results.
07:35 All right so we've got 23 earthquakes so let's go back to the snippets.
07:39 Now for each event we're going to print out the place where it occurred.
07:44 So we'll copy this and back here we'll paste.
07:49 So now, inside the features array and the JSON data, we're going to print out the
07:57 place property inside the properties collection.
08:01 And we're going to loop over each one of these properties.
08:05 So, remember, let's go back to the code for a second.
08:07 So, in here, we've got Features and Properties.
08:10 Right? So, Place is in here somewhere.
08:14 Let's have a look. Right there.
08:16 There's Place right there. Okay, so, we're going to print out this string.
08:20 So, Place is inside Properties. So, let's go back to the code.
08:24 So we're going to do that for each one of the places that we find, alright,so let's
08:29 run this. Okay.
08:32 So you can see that there were 23 magnitude 2.5 or greater earthquakes,
08:38 right, so we've got one here in Mexico, Alaska, right, a few in Alaska looks like.
08:43 Hawaii has got a few going on today, okay. Alright.
08:46 So now, oh and you can see the distance too from where they happened.
08:52 Alright, let's get a little bit more advanced.
08:54 Now, let's go back to the snippets. So now we're going to print only the
08:57 events that have a magnitude greater than four.
09:00 So let's copy this and paste it and I'll explain the code here.
09:07 And let's comment down the one above it. So, same idea.
09:11 We're going to loop over each one of the events in the earthquake list.
09:16 But we're first going to check to see if the magnitude property that's inside the
09:20 Properties collection is greater than 4.0. And if it is.
09:25 Then we're going to print out. I'm using some formatting here just a two
09:28 digits and one decimal place are the floating point number.
09:31 I'm going to print out the magnitude followed by the place where it happened.
09:37 So let's go ahead and save, let's run this.
09:42 And you can see that there were 23 events recorded but it looks like there was only
09:45 about eight or nine who had a magnitude of four or greater and you can see that this
09:49 is the magnitude column over here. Okay pretty cool, so so far we're
09:53 manipulating and filtering the JSON data. Let's go back to the snippets.
09:57 Okay now we're going to print out only the events where at least one person reported
10:04 feeling something. So let's go ahead and copy these lines,
10:08 and we're going to paste these in, and let's comment out these other lines here.
10:19 So we're going to print events that were felt.
10:22 And inside the properties collection of this data feed there is a felt property
10:26 which counts the number of times a felt report was filed so somebody reports
10:31 feeling the earthquake. So we're only going to see if the number
10:36 of felt reports. Is greater than zero.
10:40 And so at first we have to make sure that the felt reports property actually exists.
10:44 So if it's not equal to the none type and then it's greater than zero, we're
10:48 going to do the same print operation and we're going to print out the magnitude.
10:51 We're going to print out the place where it occurred and we're going to print out
10:56 the number of times that people reported feeling it.
11:00 Okay, so let's save this and let's run it. And you can see that only five events out
11:09 of the 23 that were reported today were felt, so this one in Hawaii was a couple
11:14 of times, Oregon was one time. There was an earthquake today just over by
11:18 Oklahoma that 34 people reported feeling. And we've got one down here in Antigua
11:24 that was reported 14 times and it looks like Ferndale California got one that
11:28 somebody reported feeling. So you can see using Python to retrieve
11:32 JSON data from the internet and manipulate and process it is really easy.
11:37
Collapse this transcript
Parsing and processing HTML
00:00 Python provides a built-in way for parsing html data as well as other kinds of data.
00:06 In this example we're going to see how to create our own html parser based on the
00:11 html parser class that Python provides. So, here in the example snippets I'll
00:16 scroll down to the html section in chapter five.
00:19 So, let's go ahead htmlparsing_start.py. Now, you can see what I've done here is
00:26 I've created a function called name and I've got a variable here called parser and
00:31 I'm stantiating a myHTMLParser class. So, we're going to write that class and
00:37 feed it some html and then watch as it parses the information.
00:41 So, lets go back to the snippets. Okay.
00:43 So, before we do anything else let's scroll down here to line 513.
00:49 What we're going to do is copy lines 513 to 517, and we're going to go back to the
00:55 main file and we're going to paste that. Here, into the main function.
01:01 Now, we could use the URL lib to open up a URL and read the HTML data straight from
01:08 the URL, but I'm not going to do that. In this case, I'm going to just simply
01:11 open up a sample file that we have right here, called samplehtml.html.
01:16 And if we look at this for a moment, you can see that this is a pretty standard
01:19 HTML file. There's a head and a body.
01:21 In the head, we've got some meta information, and some title tags, and some
01:25 link tags. There's a comment in here.
01:26 You know, some body information. So, just a skeleton HTML file that we're
01:30 going to use to test out the parsing. Now, let's close that.
01:35 Okay, so what we're doing here is opening the html file using the built-in file
01:40 reading methods in Python. We're going to check to make sure that the
01:43 mode is r, so that it was opened correctly.
01:46 And then we're going to call the read function to read the entire file into a
01:51 variable (UNKNOWN) contents, and then we're going to pass the contents to our
01:55 parser class. And our parser class has a function called
01:58 feed on it. So, we're going to pass in the string that
02:01 represents the html and the parser's going to work on it.
02:03 Alright, so now, let's go back to the snippets, let's scroll up here.
02:08 So, the first thing we need to do is import the html parser module.
02:12 So, we'll copy this line. And we'll paste it.
02:15 Right, so now we have an HTML parser class.
02:18 The way that this works is, HTML parser is a base class that you sub-class.
02:23 And when you create your sub-class, that's what's going to handle the processing of
02:27 the HTML information. So, let's go back to the snippets.
02:31 And down here on line 476, let's copy a few lines.
02:35 So, first I'm going to copy the class definition and paste it in.
02:42 And then back in here, let's scroll down a little bit until we get to the handle
02:47 comment section here on line 505. So, let's copy these lines right here.
02:52 We're suppose to start off with something simple.
02:54 And we'll paste this in. Okay?
02:57 So, now I'm declaring a class called MyHTMLParser.
03:00 It's based on the HTMLParser class. And I've defined a method called handle_comment.
03:08 Now, what's going to happen is, when you pass the HTML content to this feed
03:12 function, which is defined in the HTML parser base class.
03:16 It's going to take the HTML content and run through it line by line, and each time
03:21 it encounters a specific kind of element inside the HTML code like comments or tags.
03:26 Or you have text data, whatever it is, it's going to call functions that you
03:31 override in your class. So, in this case, when it comes across a
03:35 comment, it's going to call my handle comment method and it's going to pass the
03:40 data that's inside the comment. So, all we're going to do is print out
03:44 encountered comment along with the comments data.
03:47 And then we're going to get the position in the file where the comment was found.
03:52 So, get pause comes back with two things. It comes back with a line number and a
03:57 character position in the data where the, in this case, the comment was encountered.
04:03 So, now that we've got something we can run.
04:04 Let's save it. And let's run this.
04:08 And we'll do Python run. Okay, and you can see that there's only
04:13 one comment in the file. It says, encounter comment, and here's the
04:15 contents of the comment at line 9, position four.
04:19 And let's make sure that's correct. Sure enough, here's line 9 right here.
04:24 And there's character index number four, and this is the HTML comment.
04:28 Okay. So, we see that it's working.
04:30 Okay, let's go back to the snippets file. Let's copy and paste a couple of other
04:35 things in here. So, the first thing I want to do is copy
04:38 and paste these functions right here on 493.
04:42 This is the function to handle the ending tag in the data.
04:47 And we've got handle data here, so let's copy these two, and let's paste them in
04:54 above handle comment. Okay.
05:00 And let's go back and get the start tag as well.
05:06 So, what were going to do is just for now, let's just copy the function definition of
05:11 handle start tag, paste that in here, and back in the snippets let's copy everything else.
05:19 Okay, and let's paste that in here. There we go.
05:23 Alright, let's take a look at what we've done.
05:27 So, we went back to the snippets and copied a few more items from the file, and
05:34 let's make sure to at least save everything.
05:39 Okay. So, we've copied over a few more things
05:42 from the snippets. This function handle_starttag, gets called
05:46 when the closing angle bracket of an opening tag is reached.
05:50 So, for example, when the HTML parser reaches that bracket right there of this
05:54 title tag. Or when it reaches this angle bracket
05:58 right here of this link tag, it's going to call the handle start tag.
06:03 Handle end tag gets called when the ending tag of something gets encountered, so
06:08 again back in here, when you have a tittle tag that has contents snide it that's this
06:13 guy right here, that's the end tag. And let's see, we've got handle data.
06:18 So, data is textural data. So, it will be called for text like this.
06:22 And text like this inside this h1. Okay.
06:23 So, all we're doing in each one of these examples is basically getting the position
06:29 where the tag, or data, or whatever was encountered.
06:33 Printing out the line number and character position.
06:36 And in the case of a start tag, if there are attributes right?
06:41 Attributes get passed into this argument here in the function.
06:44 If the attributes list is greater than zero in length, we're going to print out
06:49 all of the attributes as well. So, we'll print attributes, and then for,
06:53 we have a for loop looping over all the attributes in the attributes list.
06:58 And we'll just print a tab along with the name of the attribute, and the value of
07:02 the attribute. Okay.
07:04 So, let's save, and let's run. Okay, so you can see it's processed the
07:09 entire file. Scroll all the way back up.
07:12 So, we've got some data here, right, this is all text data.
07:15 Some of these are going to be blank lines for text data.
07:18 But you can see here that we've got the HTML element, counted a meta tag, we've
07:24 got some data here, some text data. Right, here's a tag with some attributes
07:30 on it. So, let's go back to the snippets and copy
07:35 the rest of this up here. Now, what we're going to do is count the
07:39 number of meta tags that we encounter. So, I'm going to copy this line right here.
07:46 And paste it in, so now we have a global variable named metacount, and down here in
07:51 handle_starttag I'm going to copy these lines right here and going to paste it in.
08:01 Okay. So, now I'm telling the interpreter that
08:04 there's a global variable named metacount and that's right up here.
08:08 And then when we encounter a starttag we'll print out the name of the tag.
08:11 If the tag is named meta, we're going to increase the count of meta tags that we
08:16 found and then down here at the bottom, we're going to print out the number of
08:25 meta tags that we encountered. And that's going to go in the main
08:31 function down here. So, after the parser gets finished
08:35 parching the file, we're going to print out the total number of meta tags that we
08:39 encountered were. And we're going to print out the meta
08:41 account variable in this placeholder right here.
08:45 Alright. So, lets save.
08:46 Lets scroll back up. Lets run this.
08:49 Okay. So, once again you can see that we start
08:54 off with the HTML tags. Got a language attribute on it.
08:57 Alright, we have the head tag right here. There's no attributes.
09:00 There's some data. The data is a carriage return.
09:03 So, here's a meta tag right here with the information in it.
09:07 Here's a meta tag. Here's the title.
09:09 Right. Here's another meta tag right here.
09:11 This one has some attributes on it. And then all the way down at the bottom,
09:17 scroll all the way down. You can see that we encountered a total of
09:22 four meta tags. I see that's correct.
09:25 There's one, there's two, there's three, there's four.
09:29 So, it looks like it worked properly. Alright.
09:31 Well, that's an example of using Python to process HTML by building your own HTML
09:37 parser subclass based on the HTML parser class provided by the Python standard library.
09:43
Collapse this transcript
Manipulating XML
00:00 Sometimes when you're processing markup like XML or HTML, you don't want to build
00:05 a parser that just runs through the document one line at a time.
00:08 What you'll need to do is have the entire document in memory.
00:11 In other words you'll need to operate on the document's dom.
00:14 And in this example, we'll see how the use the XML minidom class that Python provides
00:20 to load an XML file and then operate on the document while it's in memory.
00:24 So let's open up the xmlparsing_start.py file and over here in the snippets, let's
00:31 copy this line right here 523 and paste it in.
00:37 So now I'm importing the xml.dom.minidom module and I'm going to use the minidom
00:43 class to parse an XML file. And the XML file I'm going to be parsing
00:47 is this one right here, samplexml.xml. So let's open it up and take a look at it,
00:52 and you can see that it's a pretty standard XML file.
00:55 It's just got some basic information about a person in it.
00:58 So you can see there's my name, where I live, various skills that I have, that
01:03 kind of stuff. Again just a sample XML file for parsing.
01:07 Alright so let's go back, let's save... All right, let's go back to the snippets.
01:12 Okay so now, we're going to use the minidom to parse the file.
01:18 Let's copy these lines here, paste them in.
01:21 So, here in my main function, I'm going to use the parse function on the XML minidom
01:25 to load and parse an XML file. So we have a variable here called doc.
01:31 And doc gets the result of the parse function.
01:34 And all I do is give it the name of the file that I want to parse.
01:37 And because the name of the file that I want to parse happens to be in the same
01:40 directory as this example, I don't have to do any fancy path manipulation.
01:45 Alright. So back in the snippets, let's copy the
01:48 next few lines here, on 529. And paste them in over here.
01:53 So just to make sure that everything's working okay.
01:55 Once we've parsed the document, let's print out the node name of the root of the document.
02:01 And the tag name of the first child property on the document object.
02:06 Now if these names don't look familiar to you, these are standard names that are
02:10 used in the document object model. Things like Node name and First Child and
02:15 Tag name, these are all standard properties of an XML dom.
02:19 So all I'm doing is working with the existing dom API as it is defined by the W3C.
02:25 So I'm going to save this, and I'm going to run it, because now we've got
02:29 something we can run. I'll choose Python run.
02:32 Alright, and you can see that the node name of the doc is #document just like the
02:38 W3C spec says it should be. And the first child tag in the document,
02:44 the tag name of that is Person. And that should be correct.
02:47 Yes that's absolute correct. Person is the very first tag in the document.
02:52 Alright, so far we're off to a good start. Now we're going to get a list of XML tags
02:58 from the document and print each one. So lets copy lines 533 and we'll paste
03:06 them in here. So now I'm going to use the dom standard
03:09 function called getElementsByTagName. Again standard W3C function.
03:14 I'm going to ask the document for all the elements named skill and then I'm going to
03:19 print out the number of skills that I've found using this formatting string right here.
03:25 So this place holder is going to be filled in by skills length.
03:29 And then I'm going to loop over each one of the skill tags and print out the name attribute.
03:35 So, let's go back to the XML. You see that each skill tag has a name,
03:38 and then the name attribute has the content of some skill.
03:42 So let's go back here, let's save, let's run.
03:46 And you can see I've got four skills and I've listed out the attributes of the name
03:52 attribute on each one. So looks like again everything seems to be working.
03:56 Alright let's go back to the snippets. Now we're going to create a new XML tag
04:00 and add it into the document. So we'll copy this.
04:07 And we'll paste. So you can see that I'm adding a new
04:11 skill, so, using the Create element. The Create element function is again W3C
04:16 standard function as is set attribute. So I'm creating a new skill tag, setting
04:21 the name attribute to be j-query. And then appending this new skill tag Into
04:28 the first child of the document which, remember, is the person tag.
04:32 So I'm going to add this new skill right here after this guy before the closing tag
04:39 of the person tag right here. Alright, so let's go back.
04:43 And then just to make sure everything worked okay, let's copy these lines.
04:48 And let's paste them in down here. So first, we'll print out the list of
04:54 skills before the new one is added. And then we'll add the new skill.
04:57 And then we'll print out the list after it's been added to make sure everything
05:00 was fine. In fact, let's put a blank line in here to
05:06 separate out the two things. Alright, so let's save, let's run, and
05:12 sure enough let's scroll back up. You can see that there's the four skills,
05:17 JavaScript, Python, C-sharp and HTML, and then I add the new one, now I've got five
05:21 skills and there's jquery at the end. So that should give you an idea of how you
05:25 can use the dom in Python to manipulate XML documents in memory...
05:31
Collapse this transcript
Conclusion
Goodbye
00:00 Well, that brings us to the conclusion of Up and Running with Python.
00:03 If you like what you've seen in this course, and think that Python might be a
00:06 good fit for projects that you are working on, there are a few places you can go to
00:11 next from here. First, be sure to check out Bill Weinman's
00:14 Python 3 Essential Training course here on lynda.com.
00:18 It provides deep comprehensive coverage of the Python programming language.
00:22 Second, be sure to stay up to date with Python, and learn more about the features
00:26 provided at the language here at python.org.
00:30 Here you'll find comprehensive documentation on all the features I showed
00:33 in this course, along with many others that I didn't.
00:35 If you need Python to do something, chances are it's covered by the standard
00:39 Python library. Finally, if you find you need help with
00:42 specific concepts, such as working with classes and objects, be sure to check out
00:47 the foundations of programming series here on lynda.com.
00:51 Python is rapidly becoming the go to language for programmers of all stripes.
00:54 Both on the clients and in the Cloud. Take what you've learned, go out, and
00:58 build great apps. Happy coding.
00:59
Collapse this transcript


Suggested courses to watch next:

Python 3 Essential Training (6h 36m)
Bill Weinman


SPSS Statistics Essential Training (5h 5m)
Barton Poulson

Up and Running with R (2h 25m)
Barton Poulson


Are you sure you want to delete this bookmark?

cancel

Bookmark this Tutorial

Name

Description

{0} characters left

Tags

Separate tags with a space. Use quotes around multi-word tags. Suggested Tags:
loading
cancel

bookmark this course

{0} characters left Separate tags with a space. Use quotes around multi-word tags. Suggested Tags:
loading

Error:

go to playlists »

Create new playlist

name:
description:
save cancel

You must be a lynda.com member to watch this video.

Every course in the lynda.com library contains free videos that let you assess the quality of our tutorials before you subscribe—just click on the blue links to watch them. Become a member to access all 104,069 instructional videos.

get started learn more

If you are already an active lynda.com member, please log in to access the lynda.com library.

Get access to all lynda.com videos

You are currently signed into your admin account, which doesn't let you view lynda.com videos. For full access to the lynda.com library, log in through iplogin.lynda.com, or sign in through your organization's portal. You may also request a user account by calling 1 1 (888) 335-9632 or emailing us at cs@lynda.com.

Get access to all lynda.com videos

You are currently signed into your admin account, which doesn't let you view lynda.com videos. For full access to the lynda.com library, log in through iplogin.lynda.com, or sign in through your organization's portal. You may also request a user account by calling 1 1 (888) 335-9632 or emailing us at cs@lynda.com.

Access to lynda.com videos

Your organization has a limited access membership to the lynda.com library that allows access to only a specific, limited selection of courses.

You don't have access to this video.

You're logged in as an account administrator, but your membership is not active.

Contact a Training Solutions Advisor at 1 (888) 335-9632.

How to access this video.

If this course is one of your five classes, then your class currently isn't in session.

If you want to watch this video and it is not part of your class, upgrade your membership for unlimited access to the full library of 2,024 courses anytime, anywhere.

learn more upgrade

You can always watch the free content included in every course.

Questions? Call Customer Service at 1 1 (888) 335-9632 or email cs@lynda.com.

You don't have access to this video.

You're logged in as an account administrator, but your membership is no longer active. You can still access reports and account information.

To reactivate your account, contact a Training Solutions Advisor at 1 1 (888) 335-9632.

Need help accessing this video?

You can't access this video from your master administrator account.

Call Customer Service at 1 1 (888) 335-9632 or email cs@lynda.com for help accessing this video.

preview image of new course page

Try our new course pages

Explore our redesigned course pages, and tell us about your experience.

If you want to switch back to the old view, change your site preferences from the my account menu.

Try the new pages No, thanks

site feedback

Thanks for signing up.

We’ll send you a confirmation email shortly.


By signing up, you’ll receive about four emails per month, including

We’ll only use your email address to send you these mailings.

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

By signing up, you’ll receive about four emails per month, including

We’ll only use your email address to send you these mailings.

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked