UNISYS 3RD ONE Python Development: Getting Started with Programming in Python

 

Python Development: Getting Started with Programming in Python

Python is a beneficial language for use in a lot of development projects, particularly Java/C++ development. In this course, you'll learn the basics of Python programming. You'll start by installing Python on your local machine and practice writing code using the Python shell. Next, you'll perform basic math and logical operations in Python. You'll create Python variables and see how you can assign and access values stored in these variables. You'll then use built-in functions, which are part of the core Python programming language, to perform simple calculations and operations. Finally, you'll explore strings in Python work, creating strings using single, double, and triple quotes depending on the use case. You'll then briefly examine the use of complex data types, such as lists, tuples, sets, and dictionaries. When you're finished with this course, you'll be able to execute simple Python commands on Jupiter notebooks.

Course Overview

[Video description begins] Topic title: Course Overview [Video description ends]

Hi, and welcome to this course getting started with programming in Python. My name is Vitthal Srinivasan and I will be your instructor for this course.

[Video description begins] Your host for this session is Vitthal Srinivasan. He is a Software engineer and big data expert. [Video description ends]

A little bit about myself first, I did my master's from Stanford University and have worked at various companies including Google and Credit Suisse. I presently work for Looneycorn, a studio for high quality video content. Python is a powerful and popular programming language, and the roots of its popularity probably lie in its ease of use and the seamless integration of constructs from both functional as well as object oriented programming.

As C++ and Java developers, you are probably very comfortable with complex programming languages and so Python will likely pleasantly surprise you. The Python programming language shares many common constructs with Java but does differ in some specific and significant aspects and it is these differences that will be the focus of our study. In this course, you will start of by installing Python on your local machine on both Windows as well as MacOS platforms. You will see how you can write code using the Python shell and then launch your first Jupyter Notebook.

Next, you will see how you can perform basic math and logical operations in Python. We'll create Python variables, assign values to them, and then access those values. We will also explore the use of built-in functions which are a part of the core Python programming language and then explore how strings in Python work. We will learn that strings can be created using single, double, and triple quotes, and each of these have slightly different use cases.

We will also be introduced to complex data types such as lists, tupples, sets and dictionaries which allow you to store elections rather than individual elements. When you are finished with this course you will understand the basics of simple Python commands and will know how to execute these commands on Jupyter notebooks.

Installing Anaconda Python on Windows

[Video description begins] Topic title: Installing Anaconda Python on Windows. Your host for this session is Vitthal Srinivasan [Video description ends]

[Video description begins] The blank Command Prompt window displays. [Video description ends]

Let's begin our exploration of Python from a Windows command prompt, here we run the simple command Python, but nothing happens. This is a sign that we need to install Python in order to work with it on this Windows machine. Let's switch over to a browser and there we Google the simple phrase, install Anaconda on Windows. We'll be using Jupyter Notebooks in most of the upcoming demos and installing Anaconda is what's going to enable us to do so. We click on the first link, and that takes us to docs.anaconda.com, we take a moment to orient ourselves with this website, we can scroll up and down and see what the different sections are.

[Video description begins] The left pane contains various tabs, including: Home, Anaconda Individual Edition, User guide, and Reference. The Anaconda Individual Edition has the following sub sections, including: Installing on Windows, Installing on macOS, and Installing on Linux. Currently, Installing on Windows is selected. The windows pane displays corresponding details. [Video description ends]

But what we really need is available right up top in step one, which is download the Anaconda installer.

[Video description begins] He clicks on the Download the Anaconda installer link. [Video description ends]

This does not begin the download or rather it takes us to anaconda.com. Once again we orient ourselves here we scroll down to the bottom, and here are the installers, these are available for Windows, MacOS and Linux. Let's click on the 64 bit graphical installer, this is for Windows, and

[Video description begins] The Save As explorer window displays. [Video description ends]

the process begins, we download that installer, you can see that it's an application of Type exe. The newly downloaded file is visible in the bottom left of our screen, we right-click on it and choose the open option. Because this is an executable file, this will trigger the beginning of the install process.

[Video description begins] The Anaconda setup wizard opens. He selects the Next button. The License Agreement section displays on the setup wizard. [Video description ends]

If you've ever installed anything on Windows, you should not find this a very difficult process, we go through all of the steps and change virtually none of the defaults.

[Video description begins] He selects the I Agree button. The Select Installation Type section opens. It contains two radio buttons, labelled as: Just Me (recommended), and All Users (requires admin privileges). [Video description ends]

The one change that we do make is to install for all users rather than for just me. So we override the default choice here and then keep moving forward.

[Video description begins] He clicks on the Next button. The Choose Install Location section opens. [Video description ends]

Here now is the destination folder where Anaconda is going to be installed, by default this is C:\ProgramData\Anaconda3. You can jot down this location if you can't remember it, we need it in just a minute to run the activate base script.

[Video description begins] He clicks on the Next button. The Advanced Installation Options section opens. It contains two radio buttons. He selects the Install button. The Installing section opens. [Video description ends]

Other than these very small notes, everything else is pretty smooth, we just keep hitting next. The one place where this process took some time was in the setting of the package cache step. But even that moves on pretty quickly, and we get to the end of the process and can hit finish. That terminates the execution of the installer, we can now switch back to the command prompt which is where we started out. Before we rerun Python, let's just do a little setup, let's create a directory. This is called Skillsoft intro to Python, and then we cd into this directory.

[Video description begins] The command reads: mkdir SkillsoftIntroToPython. [Video description ends]

[Video description begins] The command reads: cd SkillsoftIntroToPython. [Video description ends]

And their we perform one important but one-of step, and that is to run the activate base script.

[Video description begins] The command reads: C:\ProgramData\Anaconda3\Scripts\activate base. [Video description ends]

You can see that the precise location of this activate base script is in C:\ProgramData\Anaconda3\Scripts.

So here we make use of the install directory which we just noted down a moment ago. We add on the scripts directory inside this and the name of the script is activate, the command line argument that we pass in is the word base. This is a one time step required to configure Jupyter and Anaconda on your Windows platform. At this point we can retry the command which kick this entire demo off. We are now rerunning Python from the command line on Windows and this time it actually does something Python 3.8.5 has indeed been installed on our Windows system and we have a Python terminal prompt in front of us. This is the Python interactive shell, we'll come back to this, but not now.

For now let's just exit out by typing the exit command followed by parentheses. This exits the Python interactive shell and takes us back to the main windows command prompt. Let's clear screen and then run Jupyter, to begin with, we are just going to confirm that we have the correct versions of all of the Jupyter libraries. So this command is Jupyter --version, and various libraries and their associated numbers appear on screen before us. Next we run the command Jupyter Notebook, and this is going to launch the Jupyter Notebook server. From the output we can see that there is a URL available at the bottom of the screen, the note at the bottom of the screen gives us three different ways of accessing the notebook. First is to open a specific file in a browser, second is to copy or paste one of the URLs that is then provided. These URLs both specify local host or the local IP address 127.0.0.1, followed by the port number 8888 followed by a token. Also just above this message, you can see the command Ctrl C to stop the server and track down all kernels and as that message tells us, hitting Ctrl C twice will kill kernels skipping confirmation.

Let's copy paste one of these URLs into a browser, and this now hits our Jupyter Notebook server.

[Video description begins] The url reads: http://localhost:8888/tree. The windows pane displays three tabs, namely: Files, Running, and Clusters. Currently, the Files tab is active. The New button is present towards the right side on the windows pane. [Video description ends]

We can click on the new button over on the right, it's towards the top of your screen. And this provides us with a choice of the different technologies that are costed within Jupyter. We are going to go with Python 3, but other choices include PySpark, PySpark3, Spark R, and Spark Scala. In any case, let's click Python 3 and our first Jupyter Notebook opens up.

At this point it's untitled, we can change that by clicking on the title in the top towards the left of your screen. This opens up a prompt where we type in a descriptive name, MyFirstPythonProgram. We then hit rename, and we find ourselves at the Python prompt, the first command that we are going to run is !python --version. The bang here refers to that exclamation point, which indicates to Jupyter that this is a shell command.

In order to execute commands in Python, all you have to do is hit Shift Enter. You can also hit Ctrl Enter in order to execute multiple selected cells. So we hit Shift Enter, and we successfully get the output, Python 3.8.5 is what we've installed on Windows.

Installing Anaconda Python on macOS

[Video description begins] Topic title: Installing Anaconda Python on macOS. Your host for this session is Vitthal Srinivasan. [Video description ends]

We are now ready to get up and running with Python on Windows. Let's just repeat the process for MacOS. We start with the URL that you see on screen now, this is anaconda.com/products/individual#macos. That's the current URL for downloading Anaconda for MacOS, but in case it's changed by the time you watch this video, fear not just google Anaconda for MacOS, and most likely you will end up on the updated URL. Scroll down towards the bottom of this page and there is a list of Anaconda installers. We've actually visited this page previously when we were installing Anaconda for Windows. This time, it's the MacOS installers we care about.

Let's click on the 64-Bit Graphical Installer for macOS. This downloads the .pkg file to our local Mac machine. It's visible in the browser, or at the bottom left.

[Video description begins] He right clicks on the downloaded file. The context menu appears. It contains the following options, including: Open, Show in Finder, and Cancel. [Video description ends]

We click on it and choose the Show in Finder command. This in turn opens up a Finder window, we double click on the .pkg file and the install process commences.

[Video description begins] The wizard titled: Install Anaconda3 appears. A message: This package will run a program to determine if the software can be installed displays over the wizard. He selects the Continue button. The left side of the wizard displays the following sections, including: Introduction, Read Me, Licence, and Destination type. Currently, the Introduction section is selected. He clicks on the Continue button. The Read Me section opens. [Video description ends]

This is a fairly typical and straightforward MacOS install. So, we'll just go through all of the steps, at various points, we'll have to scroll up and down, and then hit Continue. The basic idea is to keep hitting Continue.

[Video description begins] The Software Licence Agreement section opens. [Video description ends]

Along the way, we agree to the terms of the software license agreement.

[Video description begins] He clicks on the Continue button. The Installation Type section opens. [Video description ends]

Notice, that this Standard Install takes 456 MB right now, so, it's not small, especially given how disk space tends to be a little more constrained on Mac platforms, thanks to the use of SSD. In any case, we keep moving forward through the install process.

[Video description begins] He clicks on the Install button. The Installation section opens. [Video description ends]

We have a big picture sense of where we are in the install process by looking at the left there, there is a set of bullet points. For instance, we are currently on the installation step, and all of the previous steps have been completed, the two upcoming steps still show up in that light gray font because we've yet to get to them. This running package scripts can take a while, and so do some of the other steps, but in any case, we eventually get to the end of the process.

[Video description begins] The Summary section opens. [Video description ends]

At that point, we hit Close in the bottom left and we

[Video description begins] The following message appears over the wizard: Do you want to move the "Anaconda3" Installer to the Trash? [Video description ends]

can also move the installer to the trash. It helps to save a little bit of space.

At this point, Python has been installed, we can now switch over to a terminal window, and there we run python --version. This confirms that we do indeed have Python version 3.8.5 installed on our Mac machine. Now, at this point, we try a little experiment, we first run the command, where is python, and we note that the result is /usr/bin/python. Then, we try a different command, which python, and this gives us a different part. This one is inside Anaconda bin. Do we need to worry about this? And the answer is no. The reason for the difference between these two paths is because MacOS comes with its own default installation of Python, and it's that default installation which is referenced in the where is return value.

That default installation used to be Python 2.7, but it may update with different versions of MacOS. What's important from our perspective is that we have the correct and latest version of Python installed and available in the path, and the which command tells us what's going to be in the path. As long as that's the one from Anaconda, which we just installed, all is well. Here, I'm now going to do just a little bit of setup.

[Video description begins] He enters the command, that reads: cd ~. [Video description ends]

This is specific to the directory structure which I would like to have while running the Python code. So, I tilde into the home directory, then into Projects/Skillsoft, make a directory there, cd into it,

[Video description begins] The first command reads: cd Projects/Skillsoft. The second command reads: mkdir SkillsoftIntroToPython. [Video description ends]

and we are ready to launch the Python command, which will

[Video description begins] The command reads: cd SkillsoftIntroToPython. [Video description ends]

open up the Python interactive shell right here in our terminal Window.

Running Commands on the Python Shell

[Video description begins] Topic title: Running Commands on the Python Shell. Your host for this session is Vitthal Srinivasan. [Video description ends]

Let's go ahead and get started and run Python from the command line. This is a simple command just python and when I hit Enter, the Python interactive shell opens up, and from here on, we can start typing out Python commands. Let's start with just a few really simple ones to get our feet wet. 2 + 3 is evaluated to 5, 2- 6 gives -4, and so on with any other expression that we type in here. Please note, that in order to clear the screen inside the Python terminal, the keyboard shortcut is Ctrl+L. Ctrl+L is what you can use in order to get back to an empty screen with the command prompt still in front of you. One very quick note, on screen now, you can see the command False and False. There are two things worth noting here.

The first is the use of the words AND, OR and NOT as logical operators, rather than the symbols such as the double ampersand or the double pipe symbol in Java or other languages. So again, in Python, you actually use the words AND, OR and NOT. The second has to do with the precise capitalization of Boolean values. In Python, these are False and True, with uppercase F and uppercase T respectively. You can see that that's what we've used on screen now. What happens if we try and use the lowercase versions? Try and find out for ourselves. Well, we get an error, specifically a name error. The name true with the lowercase T shows up as not defined. Then we again hit Ctrl+L in order to clear screen and get back to a new fresh window and there type out a few more commands.

[Video description begins] The command reads: (3==4). [Video description ends]

3 == 4 returns False with a capital F, not (3 == 4) returns True with a capital T.

[Video description begins] The command reads: not (3==4). [Video description ends]

At this point, we've had our fill of warming up, and we type out the exit() command followed by the parentheses in order to exit out of the Python interactive shell.

Now, let's pick up and run Python from a Jupyter Notebook. We begin by running the jupyter --version command just as we did in the windows install. This is a handy way of ensuring that we have the correct versions of all the required Jupyter libraries. Next, we run the Jupyter notebook command. That's Jupyter space notebook, and this is a command we will get very familiar with. Exactly as on Windows, we have various messages, we can see that we can use Ctrl+C to stop this server and shutdown kernels. Down below are various URLs which can be used to access the Jupyter Notebook server. We copy one of them and paste it into a browser. As soon as we do this, we get redirected to a much simpler URL,

[Video description begins] The url reads: 127.0.0.1:8890/tree. [Video description ends]

and the familiar UI of the Jupyter Notebooks opens up in front of us. Let's click on the New button over on the top right. On this particular Mac system, we do not have the other bits of software that you can run from Anaconda installed. And so the only choice of technology there is Python three.

You might recall that when we had clicked on the same new button in the windows install. Various other choices, such as Scala R and PI spark had appeared there as well. In any case, here Python 3 is the only option. So, that's what we select our first Untitled Jupyter notebook on a Mac machine opens up in front of us. We can edit that title by clicking on the word untitled. The Rename Notebook dialog opens up, we type in the name MyFirstPythonProgram and click the Rename button.

And this now brings up a prompt in front of us exactly as on Windows, we can add additional code cells by hitting Ctrl+Enter. Going so brings up many more code windows. In the first of these we type the same command that we ended the windows install with, which is bank python --version. As before the bank or exclamation point indicates to Jupyter that, this is meant to be a shell command, and we can see that it runs through successfully when we hit Shift+Enter.

Please remember again, that on Jupyter Notebooks in order to run the contents of a particular code cell, you hit Shift+Enter, and the result is Python 3.8.5. We've successfully installed Python and gotten our Jupyter Notebooks up and running on both Mac and Windows platforms.

Performing Basic Math Operations in Python

[Video description begins] Topic title: Performing Basic Math Operations in Python. Your host for this session is Vitthal Srinivasan. [Video description ends]

We've already seen how to install a Jupyter Notebook and get up and running with a few simple commands in a notebook. Let's now pick up with an entirely new notebook and start with some basic Python constructs. Let's start by

[Video description begins] The page with url: 127.0.0.1:8890/tree displays. [Video description ends]

clicking on the New button over on the right and choosing Python 3. As you can see from this menu, you can also use the New button in order to open up new files of a few specific types. These include text files and new folders. You can also choose to open up a new terminal window in this way. In any case we choose Python 3 and this causes a new untitled Jupyter Notebook to open up. We can change the title by clicking up top and

[Video description begins] The wizard titled: Rename Notebook appears. It contains a text box. [Video description ends]

let's change the title of this notebook from Untitled to Variables.

So, we type in the new title into that text box and then hit Rename. This leaves us with our cursor blinking in one of the input cells in the Jupyter Notebook. Remember, that all commands in a Jupyter Notebook are executed by typing them into a cell like this one and then hitting Ctrl+Enter. Let's go ahead and add new cells into our Jupyter Notebook. We can do this by hitting the Escape+A keystroke combination. This will cause new cells to be added below the current cell location. If you'd like to add a new cell up above, you can do this using the Escape+B keyboard shortcut. And you can also make use of the plus icon which you see in the toolbar ribbon up top, it's the second icon from the left.

Having added all of these cells, let's scroll back up to the top and type something into the first cell. Here, we've simply typed the number 50,000. To evaluate the cell we use the Shift+Enter keystroke combination, and at this point you can see that the cell changes appearance a little bit, there is now a number in the square brackets next to the cell. That number is currently 1. That shows up as In [1] and the output after evaluating the expression is called Out [1] and you can see that, that value is 50,000 is well. This little bit of code has an important lesson. It shows us how every line in Jupyter Notebook can be individually evaluated, and that of course is exactly how Python works. Python is an interpreted language and the beauty of this is that it allows us to get instant feedback for whatever bit of code we happen to have typed. Jupyter notebooks are known as REPL environments where a REPL is an acronym for Read, Evaluate, Print, Loop. Let's now go ahead and start with a few really simple operations. For instance, 50,000 - 15,000 is 35,000, 35,000 - 8000 is 27,000. All of these simple operations are dealing with objects, numbers are all objects.

If you're coming from Java where you have some primitive types and some reference types. You should keep in mind that there is no such concept in Python. Everything in Java is an object. Also, if you're used to thinking in terms of the stack and the heap, you should be aware that in Python that distinction is not relevant either. You never really care or are told about where a particular variable exists. So again, you can forget about the distinction between primitive and reference data types. You can forget about the difference between stack and heap variables. Speaking of variables, this is an appropriate place to define our first variable, we've called it gross_salary and assigned it the value of 50000.

[Video description begins] underscore is present in between gross and salary. [Video description ends]

Having done this, we can now go ahead and examine its value by simply typing out the name of the variable in the next cell and hitting Ctrl+Enter, and this evaluates to whatever we just placed into that variable, which of course, is the number 50000. At this point, what probably jumped out at you was the fact that we did not declare a type associated with this variable, and this is another basic feature of Python. Python is dynamically typed.

The terms dynamic and static typing refer to whether the type of a variable is checked at runtime or at compile time. Remember, that Python is interpreted, and therefore any type checks can only be performed at runtime. There's no question of performing a check at compile time because there isn't a compilation phase, and that's why Python is a dynamically typed language. As an aside, the terms are strongly typed and weakly typed are often also used colloquially in order to describe languages. These terms are pretty ambiguous in the way they're used and defined, so, we'll steer clear of them, but you can unambiguously state that Python is a dynamically typed language. If you were forced to characterize Python as strongly or weakly typed, well, it falls somewhere in between. Python is weakly typed in the sense that there is no static or compile time type checking. So, there's no enforcement of type constraints. On the other hand, Python is strongly typed in a few ways.

For instance, there's very little implicit type conversion in Python and also type errors can be called out and prevented at runtime. We can examine the contents of a variable by printing it out to screen, this is done using the built in print() function.

[Video description begins] The line of code reads: print(gross_salary). [Video description ends]

We can see that we've now printed out gross_salary, and its value is still 50000, so, print is going to display the contents to the standard output. Variables do not need to be declared explicitly before use. We can see now, that we've created three new variables called income_tax, retirement_contribution and professional_tax.

We have not declared these before they were used for the first time, this is yet another important feature of Python.

[Video description begins] Line 1 reads: income_tax=5000. Line 2 reads: retirement_contribution=1800. Line 3 reads: professional_tax=300. [Video description ends]

When we hit Shift+Enter this bit of code is going to be interpreted and those variables will come into existence. These variable names are now bound to corresponding values in the local or global namespaces and can be used in subsequent calculations. In the next cell, we have made use of all of these variables in order to set the value of a new variable called net_salary, and the result of that computation is for the value of net_salary to be 42,900. Notice, how in this particular input cell we have two lines of code. The first line of code was an assignment. On the left hand side of that assignment, we had the variable name and on the right hand side we had an arithmetic expression.

[Video description begins] The line of code reads: net_salary=gross_salary - (income_tax + retirement_contribution + professional_tax). [Video description ends]

The second line of code consisted merely of the variable name, net_salary, and that caused net_salary to be evaluated,

[Video description begins] The line of code reads: net_salary. [Video description ends]

and its value to be printed down below. This is a common pattern, we'll often have multiple lines of code in the same input cell of a Jupyter Notebook, and in particular, it's common to define variables, perform computations, and then print out the value of the variable with the last line of code in that cell.

In any case, let's move on and perform some more simple computations. We've now created two new variables, student_score1 and student_score2.

[Video description begins] Line 1 reads: student_score1=89. Line 2 reads: student_score2=75. [Video description ends]

We now use these in order to compute a total score, and you can see the same pattern at work.

[Video description begins] Line 1 reads: total_score = student_score1 + student_score2. Line 2 reads: total_score. [Video description ends]

Note, how we've made use of the + arithmetic operator. + is an overloaded operator and it will figure out the correct operation to be performed based on the types of the variables being added. We'll see what this means in a second when we try and add two strings together. That will lead to string concatenation rather than arithmetic addition. In this instance, the two variables we are adding are numeric and that's why the result is the sum of those two numeric values. These numeric values were all integers but if we perform a division operation, the result is going to be a floating point value.

[Video description begins] Line 1 reads: average_score = (student_score1 + student_score2) / 2. Line 2 reads: average_score. [Video description ends]

We can see here that we've computed the average of these two scores by adding them and dividing the sum by 2, and that average_score variable when printed out to screen is displayed as 82.0.

The presence of the decimal point and the one digit after the decimal point tells us that average_score is a floating point value. If you look at the output of the cell right above, total score is displayed as just 164 without a decimal point, and that is an indication that, that is an integer value. Both integer and floating point values are types of numeric values supported in Python. Let's now try the use of the + operator but with string variables. We have defined two string variables, first_name and last_name, we then add these using the plus operator,

[Video description begins] Line 1 reads: first_ name = "Alice". Line 2 reads: last_name = "Bond". [Video description ends]

and as we can see below, the result is the string concatenation of Alice and Bond.

[Video description begins] The line of code reads: first_ name + last_name. [Video description ends]

Notice, how the plus operator was overloaded, it figured out the types of the operands.

That is the variables being used on the left and right hand side of the + operator, and here correctly performed string concatenation. We can see here, that strings can be delimited using double quotes. That's what we've used for delimit Alice as well as Bond. They can also be delimited using single quotes and that's how the output has been delimited by Jupyter. We can chain together the results of the + operator. We can see that we've done that now.

[Video description begins] The line of code reads: full_name = first_name + " " + last_name. [Video description ends]

We have two + operators, the first concatenates first_name with a space and that space is enclosed within a pair of double quotes. We then concatenate that result using the + symbol with the last_name variable, and the net result of all of this is to place Alice space Bond into the variable called full_name. [Video description begins] The line of code reads: full_name. [Video description ends]

That gets us to the end of this little demo in which we saw how variables could be defined and simple operations could be performed on them. We'll continue with the same theme in the demo coming up ahead.

Executing Arithmetic Operations on Python Variables

[Video description begins] Topic title: Executing Arithmetic Operations on Python Variables. Your host for this session is Vitthal Srinivasan. [Video description ends]

We had ended the last demo by using the + operator in a chain fashion.

[Video description begins] The Jupyter notebook page, titled: Variables displays. [Video description ends]

We had two uses of the + operator in the same operation. Let's now go ahead and do something similar with the = sign. On screen now, we've defined multiple variables, and we've set all of them to hold the same value of 10,000.

[Video description begins] The line of code reads: salary_1 = salary_2 = salary_3 = 10000. [Video description ends]

This is done using the chaining of the assignment operator, and you can see that at the end of this process, if we examine the contents of each of these variables individually, they all evaluate to 10,000.

[Video description begins] The line of code reads: salary_1. [Video description ends]

So, the lesson from this is that the assignment operator can be chained just as it can be in other languages such as Java or C++. Please note, of course, that we've made use of the single = operator for assignment. In order to test for equality, we've got to make use of the == operator. That's what we've done on screen now.

[Video description begins] The line of code reads: salary_1 == salary_2. [Video description ends]

We are testing whether salary_1 == salary_2, and when we evaluate this, the return value is True. Notice, the casing, the first character is uppercase, the others are all in lowercase. This is our first brush with Python's Boolean data type, which of course accepts the values true and false. We'll come back to Booleans in a minute, but before that, let's just round out the list of arithmetic operations.

[Video description begins] Line 1 reads: salary_1 = salary_1 + 1000. Line 2 reads: salary_1. [Video description ends]

In addition to the + operator which you see on screen now, we can also make use of the *, that is the multiplied by operator.

[Video description begins] Line 1 reads: salary_2 = salary_2 * 1.12. Line 2 reads: salary_2. [Video description ends]

Notice, how if you multiply an integer value by a floating point value, the result is automatically of floating point type. This principle holds true in general, the type of the result is going to take the type of the most complex type of its input arguments. Here for instance, we've set salary_3 to be equal to salary_3 - salary_3 multiplied by 0.03.

[Video description begins] Line 1 reads: salary_3 = salary_3 - salary_3 * 0.03. Line 2 reads: salary_3. [Video description ends]

Of the operations on the right hand side of the equal to sign, the first which is simply salary_3 is an integer value. However, the second is a floating-point value, and that's why the final result is a floating point type. How do we know? Well, because of the presence of the decimal point and the 0 after 9,700, and at this point, if we reevaluate salary_1 and salary_2 for equality using the == operator, the return value is going to be False.

[Video description begins] The line of code reads: salary_1 == salary_2. [Video description ends]

Note, how this is the other acceptable Boolean value, False with an uppercase F.

It's possible to assign values to multiple variables using a single = sign.

[Video description begins] The line of code reads: my_int, my_float, my_bool, my_string = 12, 3.2, False, "Hello World!". [Video description ends]

Here, we've defined four variables, my_int, my_float, my_bool, and my_string. These four variable names appear on the left hand side of the equal to sign. On the right hand side, we have the corresponding values, 12, 3.2, False, and Hello World. These assignments are going to be carried out in the order in which the variables are created. If you now go ahead and use the built-in type function in order to examine the type of my_int, this comes back as int. This is the built-in Python integer type.

[Video description begins] The line of code reads: type(my_int). [Video description ends]

In similar fashion, we can also examine the type of my_float, that's float,

[Video description begins] The line of code reads: type(my_float). [Video description ends]

and the type of my_bool is bool.

[Video description begins] The line of code reads: type(my_bool). [Video description ends]

Note, the exact spelling of the Boolean type in Python, this is b-o-o-l with a lowercase b. In Python, everything is an object, and there's no distinction between primitive and reference types as there is in Java. In Java, variables of types int, float, and boolean would have been primitive variables that resided on the stack, while in contrast, the string variable would have been a reference type, which existed on the heap and would have been subject to garbage collection. This distinction does not exist in Python. So, if we now use the type function with my_string, [Video description begins] The line of code reads: type(my_string). [Video description ends]

the type that comes back is str, and that is the built-in Python type. All of these variables that we've now defined are objects. That's just the way Python works. Let's now try and overload the + operator and try and use it to add my_int and my_float.

[Video description begins] Line 1 reads: result = my_int + my_float. Line 2 reads: print("The final result is: ", result). [Video description ends]

This is an easy overload and the result is 15.2. Let's try it with a slightly more complex overload,

[Video description begins] Line 1 reads: result = my_int + my_bool. Line 2 reads: print("The final result is: ", result). [Video description ends]

this one between my_int and my_bool. The result comes back, this is numeric as well, and this gives us the answer 12. We had defined my_int as 12 and my_bool as False, so the return value is 12, and that's because my_bool was converted to the numeric value 0. The lesson from this is that the False Boolean value evaluates to 0 if it's treated as a numeric type.

Let's now try and overload the + operator with an int and a string, but this time an error results. [Video description begins] Line 1 reads: result = my_int + my_string. Line 2 reads: print("The final result is: ", result). [Video description ends]

Let's look closely at the error message, it's a type error, and the message tells us that we've used unsupported operand type(s) for the + operator, int and str. This error is an example of why Python is said to be strongly typed in some senses, because here, no implicit type conversion was performed. This also demonstrates why Python is dynamically typed. This error only resulted when we tried to run this code, the error did not occur at compilation time because there is no compilation phase in Python, and that's why this is an example of a dynamically typed language. Let's try a different experiment. Let's reference a variable which we've not defined. Number is a variable that we have not defined so far. If we just type this out into an input cell and hit Shift+Enter, we get a name error.

The name number is not defined. So, let's go ahead and define this variable. We have number, which is now equal to 10.

[Video description begins] Line 1 reads: number = 10. Line 2 reads: number. [Video description ends]

If we retry our evaluation of number, then it works fine and we do indeed get the result 10. Let's try and add 100 and re-evaluate it, and this works out to 110.

[Video description begins] Line 1 reads: number += 100. Line 2 reads: number. [Video description ends]

This bit of code that you see on screen now shows the use of the += operator. Here, we've got just one variable, the += operator takes whatever value we have on the right-hand side and adds that to the variable, and that's why += is said to be a unary operator. It just takes in the one operand.

No great surprise here, relative to what you would expect from Java or another similar programming language. In similar fashion, we have unary operators for *=, /=, and so on.

[Video description begins] Line 1 reads: number *= 10. Line 2 reads: number. [Video description ends]

[Video description begins] Line 1 reads: number /= 11. Line 2 reads: number. [Video description ends]

Note carefully, the use of the / operator, this on-screen now has a single forward slash, and this performs the typical kind of division that you would expect. Number was initially equal to 1,100, we divided it by 11, and so the result was a 100. Notice, that the result is a floating point type as demonstrated by the presence of the decimal point. In a moment, we are going to check out a division operator with two forward slashes, and that is going to provide an integer division.

We'll get to that in a moment, but first, let's quickly try out the -= operator which does exactly what you would expect.

[Video description begins] Line 1 reads: number -= 18. Line 2 reads: number. [Video description ends]

Number -= 18 results in 82, and that's because before we subtracted 18 from it, number was equal to a 100. So, at this point, number is 82.0. Let's see what happens if we perform number divided by four, but this time using two forward slashes instead of one,

[Video description begins] Line 1 reads: number //= 4. Line 2 reads: number. [Video description ends]

and when we do this operation, we see that number is equal to 20.0. This is an example of integer division or floor division. When we make use of the two forward slashes, we lose the remainder. We only have the quotient, 82 divided by 4 is exactly equal to 20.5, but that 0.5 has been lost, and that's why the resulting value is just 20.0.

The // operator loses the remainder, but the % operator, also known as the modulo operator, leaves only the remainder.

[Video description begins] Line 1 reads: number %= 3. Line 2 reads: number. [Video description ends]

So now, number % divided by 3 gives us the value 2, and that's because when 20 is divided by 3, we have the quotient 6 and the remainder 2. By using the %= operator, we've extracted only the remainder and that's why 2 is displayed on screen now. There's also an operator for the power operation and this is the ** operator.

[Video description begins] Line 1 reads: number **= 4. Line 2 reads: number. [Video description ends]

Here, number **=4 is taking the number which is 2, raising it to the power 4 and displaying the result, which is 16. There's also a built-in function called pow P-O-W, and you can choose to use either of these ways of performing a power operation. For small numbers without a modulus, the ** is a bit more efficient, for large numbers, pow is a bit more efficient. Let's round up this demo by exploring named bindings. At this point, we have various variable names which are available in the local namespace.

net_salary is a variable which we used up above, and that's why we can evaluate the variable and we get a resulting value. The same is true for first_name.

[Video description begins] The line of code reads: first_name. [Video description ends]

This also is a variable which has currently been bound to the value Alice. In order to delete a binding from the namespace, we can make use of the keyword del.

[Video description begins] Line 1 reads: del net_salary. Line 2 reads: net_salary. [Video description ends]

del net_salary is going to eliminate net_salary from the current list of namespace bindings. If we try to evaluate net_salary after invoking the del keyword on it, we get a name error telling us that net_salary is no longer defined. You should be aware that using the del operation is different, entirely different from assigning a value like none to a variable. Assigning a value of none does not result in a name error if you try and evaluate that variable, but using the del keyword does. In similar fashion, we can del first_name, and if we now try and examine the contents of the variable first_name, we get the same name error.

Invoking and Using Built-in Functions in Python

[Video description begins] Topic title: Invoking and Using Built-in Functions in Python. Your host for this session is Vitthal Srinivasan. [Video description ends]

In this demo, we will turn our attention from variables to the use of built-in functions. What exactly is a built-in function? Well, here's a little note explaining the answer to that question, and

[Video description begins] The Jupyter notebook page, titled: BuiltInFunctions displays. [Video description ends]

I'm inserting it in the form of markdown. So, I've used the Cell menu up top, navigated to Cell Type and

[Video description begins] A context menu appears. It contains various options, including: Run Cells, Run All, Run All Above, and Cell Type. He selects the option Cell Type. Three options appear, namely: Code, Markdown, and Raw NBConvert. [Video description ends]

from the sub menu inserted Markdown. As its name would suggest, Markdown can be inserted with a little bit of basic formatting using just special characters, and that is then going to be rendered nicely to screen by Jupyter. In any case, let's come back to the contents of this markdown. Built-in functions are part of the core Python programming language.

They do not require any special import statements and they are available for use right out of the box. They exist in the global namespace, and you as a programmer should be careful to not name variables which have the same name as built-in functions. That will lead to unexpected behavior, it will not cause errors out of the box as we shall see, which is why this is especially important to keep in mind. Now, we've already invoked one built-in function and that was print. Let's see what happens if we just type out the name of this built-in function and hit Shift+Enter without actually invoking it. And you can see that this seems to return some kind of object and that, of course, is because in Python, everything, absolutely everything is an object.

The print() function is an object as well. Functions are objects, just like any other kind of object. They are first class citizens in Python. In any case, coming back to the print function, if you'd like to invoke it, we have got to follow it up with a pair of parentheses. Now, in the cell that you see, we have the keyboard print followed by empty parentheses with nothing in between, and now when we hit Shift+Enter, the output is blank. This means that we have invoked the print() function, but we aren't printing anything out to the screen. And that's why we have that blank output. Let's try again. Let's pass in some input argument print, and this is the string, This is a beautiful day!

[Video description begins] The line of code reads: print ("This is a beautiful day!"). [Video description ends]

Hitting Shift+Enter now gives us the exact string which we passed in.

The print built-in function is going to display whatever was passed in to the standard output stream, and that whatever could be a numeric type. Here, we have a simple addition, 2 + 45. We print that out and we can see that the result is 47.

[Video description begins] Line 1 reads: result = 2 + 45. Line 2 reads: print ("The final result is", result). [Video description ends]

The important bit here, is that the input arguments are separated by a comma. The first input argument to print is the string. The final result is, the second input argument is result, and these are separated by the comma that you see on screen. Print takes in any number of input arguments, that's called an example of a varargs function.

[Video description begins] The line of code reads: print ("The final result is", result, sep=":"). [Video description ends]

In addition, we can also specify named parameters.

For instance, on screen now, we've specified the specific name parameter called sep, S-E-P, and we've set that value to be equal to colon. sep is going to be interpreted by the print function as the character which we would like delimiting the different inputs passed in and that's why when we print this out, we can see that the output is now, The final result is, followed by a colon, followed by 47. The default value of the named parameter sep is simply the space, and that's why it's not mandatory that you include it. In addition, there's also another named parameter called end. On-screen now you can see that we've specified end to be equal to *.

[Video description begins] The line of code reads: print ("The final result is", result, sep=":", end="*"). [Video description ends]

That's the star character, and that's why when we invoke this, we now have an * over at the end of the output. As before, we specified sep to be equal to colon, and that's why we see the colon between the final result is, and the number 47. Now, in the world of Java, any statement which prints out variables to the standard output is commonly referred to as a print statement.

However, it turns out in Python, that the term print statement has a specific meaning. Let me really quickly add in a bit of markdown in order to explain this. So, I use the Cell command up top and insert the Markdown and paste in the message. And that message tells us that the print statement used to be supported in Python 2, but is no longer supported in Python 3. Python 3 only supports the print function.

We can see from this the difference, the precise difference between a print statement and an invocation of the print() function. All of our uses of the print function up above have had various input arguments passed in the print() function, and those have been enclosed within parentheses. What you now see on screen is a print statement, and that print statement is no longer supported in Python 3, and

[Video description begins] The line of code reads: print "This is a beautiful day!". [Video description ends]

that's why we have the syntax error, Missing parentheses in call to print, and Python helpfully asks us whether we meant to invoke the print function instead, with the use of the parentheses. Please note again, that we are currently in Python 3, and you can confirm that by glancing at the top right corner of your screen. Now, that we've covered the precise semantics of the terms, print statement and print function, we can go back to using the term print statement to refer to pretty much any line of code which invokes the print statement. We don't need to be too pedantic about this.

Now, on line 8, we have a print statement in which we invoke the print function, and we pass in a string, followed by an arithmetic expression,

[Video description begins] The line of code reads: print ("The final result is: ", 56 + 25). [Video description ends]

and this does exactly what we'd expect. Let's try out another print statement, this time where we pass in a more complex arithmetic operation,

[Video description begins] The line of code reads: print ("The final result is: ", (56 + 25) / 9). [Video description ends]

and this works just as we'd expected to as well. Let's now move on from the print built-in function to the type built-in function. Let's start by just using the keyboard type and hitting Shift+Enter, and somewhat to our surprise, this returns the same keyboard. What just happened? Well, it turns out that in Python, type is also a class. Type is a base class which serves as the root of the type system, and that's why the type of type is type, quite mind-bending.

Let's now go ahead and invoke the type built-in function. This is a lot more straightforward. We invoke the type function with parentheses, and we pass in a string. When we hit Shift+Enter, the return value of this is str,

[Video description begins] The line of code reads: type ("This is a string"). [Video description ends]

and that's the type of the input argument. Let's repeat this experiment with some other numeric and non numeric types.

[Video description begins] The line of code reads: type (23). [Video description ends]

The type of 23 is int. The type of 23.5 is, you guessed it, float,

[Video description begins] The line of code reads: type (23.5). [Video description ends]

and the types of True and False would return bool. Here, we are using type of True. Notice, the capitalization uppercase T, and the return type is bool,

[Video description begins] The line of code reads: type (True). [Video description ends]

B-O-O-L, all in lowercase.

That's the name of the Boolean type in Python. Let's move on to another powerful built-in function and that's the len function.

[Video description begins] The line of code reads: len ("Python is an interpreted language"). [Video description ends]

Here, we've passed in a string, which reads Python is an interpreted language, and the return value of invoking len on this string is 33. When invoked on strings, len is going to return the total number of characters. More generally, len can be used with a list of any type, it's going to return the number of elements in that list. A string can be thought of as a list of individual characters, and that's why it worked just fine with a string. In similar fashion, if we try a second string, which reads Python is an untyped language, the len function is going to return 29. Python has some other aggregate functions such as min, max, and so on.

[Video description begins] The line of code reads: min(5.7, 9, 2.8, 29, -4). [Video description ends]

Here, we've made use of the min function, which does exactly what the name would suggest. Note, how we've just passed in the individual input arguments, separated by commas. There was no need to wrap them up in a list or any other kind of collection. In similar fashion, we can use the max function in order to get the largest of a set of numeric types.

[Video description begins] The line of code reads: max(5.7, 9, 2.8, 29, -4, 45). [Video description ends]

Some other common mathematical operations are supported by built-in functions as well.

[Video description begins] The line of code reads: round(6.6). [Video description ends]

Here, is the round function in action, a round(6.6), and that gives us 7, no great surprises. Let's round(6.3) and that returns 6. Now, what happens if we invoke the round function on a negative number? Round of -5.6 is going to return the nearest integer and that nearest integer is -6. Notice, how each of our invocations of the round function has returned an integer value.

How do we know that these are integers? Well, because they do not have a decimal point in them, what we pass into round does have a decimal point, so, those are floating point values, what comes back out of round does not have the decimal point. It's also possible for us to specify a specific number of digits after the decimal point that we would wish to round two. In those cases, the return value from round is going to be a floating point value. Just like we have a round built-in function, we also have an abs built-in function.

[Video description begins] The line of code reads: abs(4.5). [Video description ends]

As its name would suggest, this is going to return the absolute value of whatever was passed in. If what we passed in was positive, the absolute value is the same as that input argument.

If what we passed in was negative, then what comes back is going to be positive. so, abs of minus 4.5 is 4.5. What happens, if we create a variable which has the same name as the built-in function? Well, a conflict results. Unfortunately, this conflict will not be immediately apparent in the form of an error. On-screen now, we've defined a variable called abs, and

[Video description begins] Line 1 reads: abs= "assign some value to the abs variable". Line 2 reads: abs. [Video description ends]

we have assigned a string to it. That string reads, assign some value to the abs variable. If we examine abs, we now see that it contains the string we passed in. Note, that no error resulted at this point, and we have just masked the built-in function abs. The error will only appear when we try to invoke the built in abs function. So, if we retry abs of -4.5, we get the error of type, TypeError, which tells us that the string object is not callable. In case you're wondering what this is about, well, now abs is a string object, and that cannot be called, cannot be invoked by passing in parentheses and input arguments, that's what this type error is trying to tell us. So, as we saw from this, when we define a variable with the same name as a built-in function, no error is going to result at the point of definition. The error will happen when we try to invoke the built-in function.

Let's quickly round out this demo by introducing the input built-in function.

[Video description begins] The line of code reads: favorite_color = input(). [Video description ends]

We can see on-screen now, that we've invoked the input function, and stored the return value in a variable called favorite_color. When we hit Shift+Enter, a little input box will appear where we can type in whatever we'd like. We hit Enter when we are done. And if we now examine the contents of that variable called favorite_color,

[Video description begins] The line of code reads: favorite_color. [Video description ends]

we can confirm that it contains the string red. We can also specify a message while invoking the input function. That message is going to be displayed as a prompt.

[Video description begins] Line 1 reads: favorite_color = input("Please enter your favorite color:"). Line 2 reads: favorite_color. [Video description ends]

Here, the prompt is, please enter your favorite color, and that makes it really clear to users what they are expected to type in. There's no difference in the way that this input function works. We'll type out our response and hit Enter, and that's what gets assigned into the variable on the left of the equal to sign. Also, please note that the return value from the input function is always going to be a string. Here, we have an input function, we have typed in a number 34, and hit Enter,

[Video description begins] Line 1 reads: age = input("How old are you?"). Line 2 reads: age. [Video description ends]

but the type of this return value is still going to be string.

[Video description begins] The line of code reads: type(age). [Video description ends]

We can confirm this by invoking the type built-in function on the age variable, which is what we had on the left hand side of the input function invocation. The type is str, and this means that if you'd like to convert age into a number, we'll have to do this explicitly. We'll see how to do that in demos coming up ahead.

Working with Primitive Data Types in Python

[Video description begins] Topic title: Working with Primitive Data Types in Python. Your host for this session is Vitthal Srinivasan. [Video description ends]

We rounded out the previous demo by exploring how the input function always returned a variable of type str, that is, of type string. Let's understand data types in Python in a little more detail.

[Video description begins] The Jupyter notebook page, titled: DataTypes displays. [Video description ends]

Let's begin by defining a string variable called some_string assigning

[Video description begins] The line of code reads: some_string = "Programming in Python is quite intuitive". [Video description ends]

a string into it, and then invoking the type built-in function on it.

[Video description begins] The line of code reads: type(some_string). [Video description ends]

The result is str, and this is the type function telling us that the type of the variable some_string is string. Let's take this one step further. Let's see what happens if we invoke the print function on the type function, which in turn is applied to our variable.

[Video description begins] The line of code reads: print(type(some_string)). [Video description ends]

The output looks a little different this time around that's because it's a class. What we can see now, is enclosed within a pair of angled brackets. We see the word class followed by the same type str. What just happened? When we invoke the print function that in turn reached into whatever was passed in and invoked something known as the repr-function. Repr, R-E-P-R, is short for representation, and this is a function or a method to be precise, which can be implemented by every class in order to return a nice printable string representation.

That string representation of the type is what you see on screen now. We'll have more to say on the repr function when we get to classes, but for now, let's focus on the types of different variables. So, the type of a string is str. In similar fashion, that type of a number can be int, float, or complex. Here, we have a variable some_number, which is defined to contain the value 4 and the type of some number is int.

[Video description begins] Line 1 reads: some_number = 4. Line 2 reads: type(some_number). [Video description ends]

If you re-invoke print on the type, we can see that we get the string representation, which is class of int.

[Video description begins] The line of code reads: print(type(some_number)). [Video description ends]

What we see on screen now, drives home the point that even the built-in data types in Python are all classes, and that in turn means that all data items are objects of those classes. Strings or objects of the str class, ints our objects of the int class. Again, this is different from Java, there is no distinction between the primitive and the reference types.

Strings are also known as text variables. Python has numeric types for ints, floats, and complex numbers. Let's go ahead and create a variable containing a float value. This is 4.8, the type of float is float,

[Video description begins] The line of code reads: some_number = 4.0. [Video description ends]

and when we invoke print on the type we get class float.

[Video description begins] The line of code reads: type(some_number). [Video description ends]

[Video description begins] The line of code reads: print(type(some_number)). [Video description ends]

In similar fashion, we can define a complex number. Complex numbers have a real as well as imaginary parts. Here, we have a variable called sum_complex_number, which is used to hold the value of 20j.

[Video description begins] The line of code reads: some_complex_number = 20j. [Video description ends]

Here, j refers to the square root of -1, and so 20j can be thought of as a complex number, which has only an imaginary part.

We can invoke the built-in type function on this complex number and it returns complex.

[Video description begins] The line of code reads: type(some_complex_number). [Video description ends]

In identical fashion, if we print out this type, we are going to get the class complex.

[Video description begins] The line of code reads: print(type(some_complex_number)). [Video description ends]

So again, there are three numeric types in Python, int, float, and complex. We've already experimented with the Boolean type. Boolean types have the values True or False.

[Video description begins] The line of code reads: some_boolean = True. [Video description ends]

We can invoke type on a Boolean variable and we will get bool, lowercase b,

[Video description begins] The line of code reads: type(some_boolean). [Video description ends]

and if we invoke print, we'll get class bool.

[Video description begins] The line of code reads: print(type(some_boolean)). [Video description ends]

Let's now move on to some of the binary types supported in Python. It turns out that there are three binary types, byte, bytearray, and memoryview. Let's start by defining a variable of type bytes.

[Video description begins] Line 1 reads: some_bytes = bytes(10). Line 2 reads: some_bytes. [Video description ends]

On screen now, we've defined a variable called some_bytes, and we've set this to be equal to bytes with the input argument 10.

When we print this out, we can see that this is a sequence of 10 bytes. The character lowercase b is prefixed before that sequence, and each of the individual bytes is preceded by the escape sequence \x, which tells us that each of these is a hexadecimal value. Right now, each of these hexadecimal values is set to 0, and so, we have the sequence of 10 bytes, each of which is 0. Each individual byte, as its name suggests can contain a value between 0 and 255, and in this way the bytes type is used to represent an immutable sequence of small unsigned integers, unsigned because they are in the range 0 through to 255.

Remember again, that the type bytes is not mutable. Let's go ahead, and invoke the type built-in function,

[Video description begins] The line of code reads: type(some_bytes). [Video description ends]

what we get back is bytes. This is the first of the three binary types supported in Python. Let's go ahead and create a variable of the second binary type, which is bytearray.

[Video description begins] The line of code reads: some_bytes = bytearray(10). [Video description ends]

This is very similar to bytes, the difference is that a byte array is mutable. So, byte array can be thought of as a sequence of mutable unsigned integers, each in the range 0 through 255.

If we print out the value of a byte array variable,

[Video description begins] The line of code reads: some_bytes. [Video description ends]

we see, that we once again have that value preceded by the lowercase b. We once again have each of the individual bytes preceded by the escape characters \x. But the difference is that this time around, all of that is contained between a pair of parentheses and that in turn is preceded by the word byte array. Let's go ahead and invoke the type method on this variable called some_bytes, and we can see that it returns a bytearray rather than bytes. Finally, there's another binary type in Python known as the memoryview.

[Video description begins] The line of code reads: some_memoryview = memoryview(bytes(10)). [Video description ends]

A memory view can be constructed off a bytes or a byte array object, or indeed of pretty much any object at all. As the term memory view suggests, this is a way of representing all of the bytes that make up an object as a binary type.

Memory view objects come in handy when we're working with very large objects, and where it's very inefficient to create copies of those objects. Here, you can see that we have created a memory view of a bytes sequence. When we print it out, what we get is pretty much a memory location, that's about as low level as you can get.

[Video description begins] The line of code reads: some_memoryview. [Video description ends]

Let's invoke the type built-in function on this variable called some_memoryview, and this is of type you guessed it, memoryview.

[Video description begins] The line of code reads: type(some_memoryview). [Video description ends]

You should be aware that each of these three binary types, bytes, bytearray, and memoryview can be indexed using square brackets, so that, you can reach into the sequences in order to access individual bytes.

There are also various other operations that you can perform on them, which we will not discuss in detail for now. But now, that we've introduced the idea of sequences and of indexing into sequences, the stage is set for us to turn our discussion to maybe the most important and commonly used data type in Python, which is the list. We'll get to list in the demo coming up ahead.

Using Complex Data Types in Python

[Video description begins] Topic title: Using Complex Data Types in Python. Your host for this session is Vitthal Srinivasan. [Video description ends]

If you are coming to Python from Java, you probably have a lot of experience creating array lists. If you're coming to Python from C++, you probably worked with STL, vectors and lists as well. So, it's a pretty universal idea in programming languages to have sequential containers which can change in size, and that is exactly what lists are in Python.

[Video description begins] The Jupyter notebook page, titled: DataTypes displays. [Video description ends]

On screen now, we've defined a simple list called numbers_list. On the right hand side of the equal to operator,

[Video description begins] Line 1 reads: numbers_list = [3,5,7,9]. Line 2 reads: numbers_list. [Video description ends] we have a pair of square brackets, and enclosed within those square brackets are the integers

3, 5, 7 and 9. The square brackets are the defining characteristic of lists in Python.

If we now invoke type on numbers_list, the return value is going to be list.

[Video description begins] The line of code reads: type(numbers_list). [Video description ends]

List is one of the built-in Python types. Specifically, it's one of the sequential built-in Python types. The other sequential built-in Python types are range and tuple. Lists, ranges and tuples all have elements which appear in a specific order. Lists are mutable, and like array lists in Java, you can add elements to lists and get rid of elements from list. So, their size changes over time. Lists like array list in Java, are containers.

So the type of the list is list, but the type of the elements contained within the list can vary.

[Video description begins] The line of code reads: type(numbers_list[2]). [Video description ends]

Here, we have accessed the second element in our list using the index operator, that's 2 enclosed within square brackets, and we can see that the type of this is int. Indexing into list is zero based. This is the same as in Java or C++. So, when we index into our variable numbers_list using 2 as the index value, we are going to get the number 7. The zeroth element would return 3, the first element would return 5, and the second element would return 7. So again, indexing of lists in Python is zero based. There's absolutely no compulsion that every element in the list be of the same type. On screen now, we've defined a mixed_list.

[Video description begins] The line of code reads: mixed_list = [1, 2, 3, "John", False]. [Video description ends]

The first element here is an int, the second is a float, the third is a string, and the fourth is a bool.

We then use the type function in order to get the type of this mixed_list,

[Video description begins] The line of code reads: type(mixed_list). [Video description ends]

and when we hit Shift+Enter, there's no error, everything works just fine, and the type once again is list. So, you can think of the list in Python as analogas to a Java array list, which is missing a type parameter. That type of array list in Java could hold any object, and that's also true of a list. Of course, one difference is that array list in Java need to hold objects of reference types. Remember that, that distinction does not apply in Python you can store objects of any type at all in a list.

Importantly, the individual elements retain their individual types. Here, we are invoking the type function on the element at index position 1,

[Video description begins] The line of code reads: type(mixed_list[1]). [Video description ends]

and the type returned is float. If you do this with the element at index position 2, the type returned is going to be str.

[Video description begins] The line of code reads: type(mixed_list[2]). [Video description ends]

So again, a mixed_list can hold objects of different types. Those individual objects contained within the list do not lose their types in any way. So, there is no up casting or type erasure going on when you put objects of different types into a list. Lists are the most common and important type of sequential container in Python. Let's now move on to tuples.

[Video description begins] The line of code reads: record = ("Jane", 34, 56000, True). [Video description ends]

On screen now, we've defined a tuple called record. This tuple is delimited by parentheses rather than square brackets.

Like with a list, we have many different values of different types separated by commas enclosed within the parentheses. The difference between a tuple and a list is that a tuple is immutable. So, it's not possible for us to change the contents of a tuple once it's been created. It is possible for a tuple to hold values of different types. The individual values within a tuple are often referred to as fields. And again, remember that lists are delimited using square brackets, tuples are delimited using ordinary parentheses. Here, when we print out the value of a record, we get back the same values enclosed within parentheses.

If we invoke type on this record, the type is tuple.

[Video description begins] The line of code reads: type(record). [Video description ends]

So, a tuple is the second sequential type in Python. Once again, we can access the individual elements contained within the tuple using the square brackets.

[Video description begins] The line of code reads: type(record[0]). [Video description ends]

So, even though the tuple itself is delimited using parentheses, to index into a tuple, you'd use square brackets just as you would for a list. Here, we have indexed into the tuple with the index 0, that's going to give us the zeroth element, which is Jane. We've then passed that into the type built-in function, and that's why the return value is str.

Let's repeat the experiment but now indexing into it with the index 3.

[Video description begins] The line of code reads: type(record[3]). [Video description ends]

And what we get back is bool, and that's because in the tuple which we defined up above, at index position 3, we had the value true, and the type of true is bool. Tuples, just like lists, are indexed starting from 0. It's also possible to create a sequence using the range function in Python. Range is both a built-in type, a sequential type and a generator function.

[Video description begins] Line 1 reads: range_of_numbers = range(4). Line 2 reads: range_of_numbers. [Video description ends]

Here, range(4), is going to return, all of the integers 0 through 4. In case you're wondering how this is different from a list, well, a list is mutable, but a range is not mutable. We can easily convert a range into a list, we'll come back to this topic later. but for now, just understand that range is yet another sequential type in Python, and it's defined using a generator function. That generator function is the range function. And if we invoke the built-in type function on this variable called range_of_numbers, what we're going to get back is range.

[Video description begins] The line of code reads: type(range_of_numbers). [Video description ends]

So again, range is one of the sequential built-in types in Python. Let's now move on from sequential types to sets. On screen now, we've defined our first set. Notice, how we've done so using curly braces.

[Video description begins] Line 1 reads: colors = { "red", "green", "blue"}. Line 2 reads: colors. [Video description ends]

So, sets are delimited using curly braces, lists are delimited using square brackets, and tuples are delimited using ordinary parentheses. Here, we've specified three elements in our set. These are three colors. The defining characteristic of a set is that it is unordered and unindexed. You cannot rely on the elements in the set being accessed in a specific order, and you cannot index into them using the square brackets and the indexing operator.

The unordered nature of a set jumps out as soon as we define the set and print its value back to screen. While defining the set, we have specified the elements in the order red, green and blue, but when we print the values, they are in a different order, blue, green, and red. So again, sets will not preserve order of their elements. Let's invoke the built-in function type on this variable, and we can see that what we get back is set.

[Video description begins] The line of code reads: type(colors). [Video description ends]

Let's define another set, this time containing numeric types. This is the set of numbers, we have 1, 2.5, 6, 7.8, but when we print this

[Video description begins] Line 1 reads: numbers = { 1, 2.5, 6, 7.8}. Line 2 reads: numbers. [Video description ends]

set back out, we can see that the order of those elements has been preserved. Again, there's absolutely no information in this fact. Just do not rely on the order of the elements in the set following any set pattern. Sometimes, the order might appear to have been preserved, sometimes it might not. If we now invoke the type built-in function on this variable,

[Video description begins] The line of code reads: type(numbers). [Video description ends]

we get back set. So, we can see that whether our set contains strings or numeric types, its basic type remain the same.

Changing Data Types Using Python's Type Conversion

[Video description begins] Topic title: Changing Data Types Using Python's Type Conversion. Your host for this session is Vitthal Srinivasan. [Video description ends]

We ended the last demo by introducing the type set. We saw how sets are unindexed, unordered collections, we cannot rely on the order of the elements in a set. Sets are closely related to another really powerful and important type in Python, and that's the dictionary. Dictionaries are an associative data type. They are used in order to map from keys to values, and in this way, dictionaries in Python are analogues to maps in Java.

[Video description begins] The Jupyter notebook page, titled: DataTypes displays. [Video description ends]

On-screen now, we've defined a dictionary called Interview_scores that are three keys, Alex, Mary, and Jim, and

[Video description begins] The line of code reads: interview_scores = {"Alex": 4.5, "Mary": 4.8, "Jim": 3}. [Video description ends]

each of those keys is associated with a value those other numbers, 4.5, 4.8, and 3. Note, how dictionaries just like sets are delimited using curly braces.

The important difference is that the entries in a dictionary are pairs. The first element in each pair is called the key, the second element in each pair is called the value, and the key and the value are separated by a colon, Just like ordinary maps in Java and like sets in Python, you cannot rely on the keys being accessed or ordered in any specific order. So again, there's no structure to the order of the keys in a dictionary. If we now use the type keyword in order to test the type of this dictionary, what we get back is dict.

[Video description begins] The line of code reads: type(interview_scores). [Video description ends]

Dict is short for dictionary, and again, this is maybe the second most important type in Python after the list. Keys in a dictionary must be unique. No duplicates are allowed, but they can be of any type.

On-screen now, we've defined a second dictionary called employees_map.

[Video description begins] Line 1 reads: employees_map = {1001: "Greg House", 1002: "James Wilson", 1003: "Lisa Cuddy"}. Line 2 reads: employees_map. [Video description ends]

This time the keys are numeric specifically they are integers 1001, 1002 and 1003. The values are strings, and as before the keys and the values are separated by colons, and key value pairs are separated by commas. The type of this employees_map variable is also dict.

[Video description begins] The line of code reads: type(employees_map). [Video description ends]

That did not change just because the keys and the values were of different types and in the previous example. Let's now move on to some simple type conversions. Let's first create a string, this holds the numeric value 1000,

[Video description begins] Line 1 reads: some_string = "1000". Line 2 reads: some_string. [Video description ends]

but even though this is a numeric value, it's now being treated as a string because it was enclosed within a pair of double quotes.

And that's why if we invoke type on this variable, some string, what we are going to get is going to be str.

[Video description begins] The line of code reads: type(some_string). [Video description ends]

Let's now convert this into an integer value. We do this using the int function.

[Video description begins] Line 1 reads: some_int = int(some_string). Line 2 reads: some_int. [Video description ends]

Int, which takes in a string is going to try and convert whatever was passed in into an integer value. In this particular case a conversion was successful. Some string was easy to convert to an integer with the value 1000. We've saved this in a variable called some int, and when we now invoke type on it, that type is int.

[Video description begins] The line of code reads: type(some_int). [Video description ends]

So, you can convert from a string to an int using the int function.

In similar fashion, we can use the float function to perform conversions to

[Video description begins] Line 1 reads: some_float(some_string). Line 2 reads: some_float. [Video description ends]

a floating point type. Here, we've passed in the same string, which was the string 1000. The conversion was successful this time as well, with the difference that the returned value was a floating point value. How do we know the difference? Well, because some float has a decimal point and 0 after it, some int did not have the decimal point at all. If we now try the type built in function on some float, it's going to return float rather than int.

[Video description begins] The line of code reads: type(some_float). [Video description ends]

We've now seen how to convert from strings to numeric types. Let's go in the other direction. And this again is pretty simple to do, we just make use of a function, which is str. Note, how in each of these cases we carried out the conversion using

[Video description begins] Line 1 reads: another_string = str(10000). Line 2 reads: another_string. [Video description ends]

a function with the same name as the target type. To convert to int use the function int, to convert to float use the function float, to convert to strings use the function str. We've invoke this function with the numeric value 10000, and the output is of type string.

We know that because when we print it out, it's enclosed within single quotes. And we can confirm this by invoking type on the variable, another string, this returns, you guessed it, str.

[Video description begins] The line of code reads: type(another_string). [Video description ends]

Type conversions in Python are noticeably easier than corresponding type conversions in say Java. Python tries its best to make these conversions intuitive. Now, for instance, we've converted a floating point value 10,000.45 into a string.

[Video description begins] Line 1 reads: yet_another_string = str(10000.45). Line 2 reads: yet_another_string. [Video description ends]

Once again, all we had to do was invoke the function str. If you confirm the type, this has exactly what we expected.

[Video description begins] The line of code reads: type(yet_another_string). [Video description ends]

In similar fashion, we can convert boolean variables into strings using the same str function.

[Video description begins] Line 1 reads: boolean_string = str(False). Line 2 reads: boolean_string. [Video description ends]

We've now invoked str with the value False, and what we get back is the string representation of this which is False enclosed within single quotes. We can do the same with the other boolean value True and we get the same result.

[Video description begins] Line 1 reads: boolean_string = str(True). Line 2 reads: boolean_string. [Video description ends]

The output of invoking str(True) is the string True. We know it's a string because it's enclosed within single quotes.

Using Quotes to Create Python Strings

[Video description begins] Topic title: Using Quotes to Create Python Strings. Your host for this session is Vitthal Srinivasan. [Video description ends]

In this demo, we'll turn our attention from data types of different variables

[Video description begins] The Jupyter notebook page, titled: Strings displays. [Video description ends]

in Python, specifically to strings.

[Video description begins] Line 1 reads: string_1 = 'Python allows you to define strings using single quotes'. Line 2 reads: string_1. [Video description ends]

On screen now, we've defined a string variable called string_1. As the right hand side of the equal to sign tells us, Python allows you to define strings using single quotes. So, string_1 has been defined using single quotes, and when we print it out, the value is displayed with single quotes as well. In similar fashion, we can use double quotes. We've done that with this variable you see on screen now called string_2.

[Video description begins] Line 1 reads: string_2 = "Python allows you to define strings using double quotes". Line 2 reads: string_2. [Video description ends]

The right hand side also informs us that Python allows you to define strings using double quotes as well.

When we print out string_2, we can see that it's been printed out by Python using single quotes. There's no real difference between single quotes and double quotes in Python, you can think of these as perfectly interchangeable. Let's now go ahead and create a third variable called string_3,

[Video description begins] Line 1 reads: string_3 = """Python allows you to define strings using triple quotes""". Line 2 reads: string_3. [Video description ends]

and this one looks a little odd. On the right hand side of the equal to sign we have not one, not two, but three double quotes at the start, and again at the end. Enclosed within those triple quotes is the string. Python allows you to define strings using triple quotes.

This seems rather strange, but we go ahead and hit Shift+Enter, and we can see that this is a string, just like the others, then Python returns its string representation and it's just the single quotes in there. So, triple quotes seem to work just fine. string_1, string_2 and string_3 are all displayed by Python using single quotes. Does that mean the triple quotes are also perfectly interchangeable with single and double quotes? Well, not quite. Let's try this out with a multiline_string.

[Video description begins] Line 1 reads: multiline_string = 'Strings cannot span multiple Line 2 reads: lines when enclosed in single quotes'. [Video description ends]

Here, you can see that we get an error. That's a SyntaxError telling us that an end of line, that's EOL, was found while scanning the string literal. And if we look closely, we can see why our variable multiline_string was opened, that is, delimited on the left with a single quote. That string extended up to the end of the line. There was no single quote on the same line. The string then moved on to the second line, and there was a single quote at the end of the second line. So, this is a multiline_string which spans more than one line of the input, and that's not okay with single quotes.

So, as the string here tells us, strings cannot span multiple lines when enclosed in single quotes. Let's go ahead and repeat this experiment, but this time with double quotes instead of single quotes.

[Video description begins] Line 1 reads: multiline_string = "Strings cannot span multiple Line 2 reads: lines when enclosed in double quotes". [Video description ends]

Again, the result is the same, we get a SyntaxError telling us that an EOL was encountered while scanning the string literal. If we look really closely at the cells 4 and 5, we can see that there is a subtle difference in the formatting of the first and the second lines.

On the first line, everything which appears after the code is in red font, but whatever appears on the second line is in ordinary font, and this signifies to us that Python was not able to pick up the second line of these two multiline_strings. Let's now try again, this time with triple quotes at the start and at the end. Right away, we see some reason for hope.

[Video description begins] Line 1 reads: multiline_string = """Strings can span multiple Line 2 reads: lines when enclosed in triple quotes""". Line 3 reads: multiline_string. [Video description ends]

We now have the same red font all through the string that's present on line one as well as on line two. And then when we try and print back out the variable multiline_string and hit Shift+Enter, it actually works.

As the output tells us, strings can span multiple lines when enclosed in triple quotes. If we look really closely, we notice something slightly odd. We see a \n in there just before the word lines, and this tells us how exactly multiline_strings are treated in Python. A multiline_string, which is enclosed in triple quotes is going to encode the line break character as \n. That's why you see that \n, the output here on screen now. As this example demonstrates, triple quotes can be used in order to enclose multiline_strings. We cannot use single or double quotes in this context.

One little point here, when you use triple quotes, those quotes could be either single or double quotes as long you use the same delimiter on the left and on the right. Triple quotes can also be used in order to enclose single or double quotes.

[Video description begins] Line 1 reads: nicely_formatted_string = """ Line 2 reads: Triples quotes are useful because Line 3 reads: you can format and display your strings nicely in code Line 4 reads: you can include 'single quotes' and "double quotes" Line 5 reads: within the string Line 6 reads: """. [Video description ends]

An example of this is visible on screen now. We have a variable called nicely_formatted_string. On the right hand side of the equal to sign, we have three opening double quotes. These form the left delimiter of our nicely_formatted_string. At the very end, we have three double quotes again, those form the right delimiter. Between these left and right delimiters, we have the text. That text reads triple quotes are useful because you can format and display your strings nicely in code.

Our string continues, you can also include single quotes and double quotes within the string, and note the use of the single quotes and the double quotes around the corresponding words. Note, how the line breaks have been placed strategically, and also note the use of the single and double quotes within the string. Let's try and print out our variable called nicely_formatted_string,

[Video description begins] The line of code reads: nicely_formatted_string. [Video description ends]

and we have good news and bad news. The good news is that we have the single quotes and the double quotes, which have appeared perfectly with no error at all. The bad news is that the output is full of strange formatting, and our line breaks do not seem to have been preserved. The \ character has been used ahead of all line breaks. That's the \n character, and it's also been used in order to escape the single quotes and the double quotes. From this output, you might be tempted to wonder, what the point of these triple quotes was? Where is the pretty formatting which we've just spent the last few minutes talking about? To see that special formatting, let's now try again, but this time with the print function.

[Video description begins] The line of code reads: print(nicely_formatted_string). [Video description ends]

So, we'll invoke print on our variable called nicely_formatted_string, and this time, we do indeed have the perfect formatting that we wanted. All of the strange escape characters have gone away. The single quotes are displayed as single quotes, the double quotes are displayed as double quotes, and the line breaks up here exactly where we had them when we define the variable in cell 7 up above.

Working with triple quotes has also shown us how we can escape characters contained within strings which are defined using either single or double quotes, and this can be done using the \ character. Let's add this into our notebook using Markdown.

[Video description begins] He selects the Cell option in the menu. A context menu appears. It contains various options, including: Run Cells, Run All, Run All Above, and Cell Type. He selects the option Cell Type. Three options appear, namely: Code, Markdown, and Raw NBConvert. [Video description ends]

This is a good practice to document your code this way. We click on the Cell menu up top, choose the submenu item Cell Type, and from the menu over on the right, choose to insert Markdown, and this Markdown is simply going to have a message.

The first line of the message has four hash symbols. This is going to cause that line to be highlighted in bold. Escaping special characters in strings can be performed using the \ character. Let's quickly go ahead and try this out. We define a variable called some_string.

[Video description begins] Line 1 reads: some_string = 'That happened to be Jack\'s baseball bat'. Line 2 reads: some_string. [Video description ends]

On the right hand side of the equal to sign, we have a string. Within that string, note, that we have the \ character preceding a single quote. And that's why when we print out some_string, we see that that single quote has indeed appeared nicely as an apostrophe. The value of some_string is That happened to be Jack's baseball bat. Again, you can escape special characters by preceding them with the \. Let's try another little experiment. Let's again define a variable called some_string.

[Video description begins] Line 1 reads: some_string = "That happened to be Jack's baseball bat". Line 2 reads: some_string. [Video description ends]

Let's again embed a single code within it, and then let's try and print it out. It so happens that this works as well.

We can see that some_string again reads, That happened to be Jack's baseball bat. Now, at this point, you might be wondering why then we had to use a \ in cell 10 when we did not do so in cell 11. If you look really closely, you can tell that it's because of the choice of the delimiter in these two cells. In cell 10, we've chosen to delimit our string with single quotes, and that's why when we had an embedded single quote within it, we needed to escape it using the \. In cell 11, we chose to delimit our string using double quotes, and that's why we could use a single quote within that string without the escape character. This can get a little complicated, but just remember this, if you choose double quotes to delimit your string, you can safely embed single quotes. If you choose single quotes, you can safely embed double quotes without the need for escape characters. If you'd like to embed the exact same character that you happen to have used as your string delimiter, then you need the escape sequence with the \. Here's a variable called another string.

[Video description begins] Line 1 reads: another_string = "I assigned the value of that variable to be\"red\"". Line 2 reads: another_string. [Video description ends]

We have the right and left delimiters to be double quotes. We also would like to make use of double quotes inside the body of the string, and that's why we need the \ in there. And when we print out the value of another string, we can find that it does indeed have the word red contained within double quotes. To drive home the same point, here on screen now, is yet another example. This time we've chosen to use single quotes around the string.

[Video description begins] Line 1 reads: another_string = 'I assigned the value of that variable to be"red"'. Line 2 reads: another_string. [Video description ends]

We've embedded double quotes inside the string. We did not need the backslash escape character. Before we move on, one quick note, just as we use the \ character in order to escape other characters, we can also use single quotes and double quotes. So, you can use two single quotes in order to escape a single quote. Let's not go too deep into escape characters. As long as you clearly understand how the backslash works, that's probably sufficient.

Using String Formatting in Python

[Video description begins] Topic title: Using String Formatting in Python. Your host for this session is Vitthal Srinivasan. [Video description ends]

The previous demo was all about working in strings in Python, and we had wrapped up that demo by focusing on escaping delimiters such as single and double quotes.

[Video description begins] The Jupyter notebook page, titled: Strings displays. [Video description ends]

There is another use case which is so common that we must cover it, and that is the use of Windows style paths. These contain \\ as a file separator,

[Video description begins] The line of code reads: print('C:\\Users\\Projects'). [Video description ends]

and that's why if you'd like to print or create strings which contain \, we escape them with another \. So, we've created the string with escape backslashes. When we print it out, we see just the single \.

Let's also quickly see how we can embed special characters such as tabs.

[Video description begins] Line 1 reads: some_text = "Did you watch the game last night?\t I stayed up to watch the end!". Line 2 reads: print(some_text). [Video description ends]

Here's an example on screen now, we've used the character \t, and in the output that appears in the form of a tab. If you'd like to create nicely formatted strings, a common way of doing this is using curly braces, and placeholders and the .format method.

[Video description begins] Line 1 reads: favorite_sport = "baseball". Line 2 reads: time_spent = 2. Line 3 reads: "I love watching {} on TV - yesterday I watched for {} hours".format(favorite_sport, time_spent). [Video description ends]

Here, on screen now, we've defined two variables, favorite_sport which is set to baseball, time_spent which is set 2. We then would like to print out a form message which reads, I love watching baseball on TV - yesterday I've watched for 2 hours. The way we've chosen to do this is using a format string. This involves the use of the .format method, that's way over on the right.

That method takes in two input arguments, favorite_sport and time_spent. Those input arguments are going to be spliced in to replace the two pairs of curly braces within the double quotes. Then we print this out, we see that we have exactly what we wanted. We have a nicely formatted string, in which the placeholders, that's the pairs of curly braces have been replaced with the values of the variables. An alternative way of achieving something similar is by using the % operator.

In the example on screen now, we've defined one variable called favorite_sport which is set to soccer.

[Video description begins] The line of code reads: favorite_sport = "soccer". [Video description ends]

Then we have a string which contains two uses of the % operator,

[Video description begins] The line of code reads: "I love watching on %s TV - yesterday I watched for %d hours" % favorite_sport. [Video description ends]

that's %s, and then way over towards the right is %d. After the string itself, we have the % operator by itself. Followed by the name of just one variable, which is favorite_sport. When we run this code, we get an error, and that's because the string itself has 2 % operators, %s and %d, these are two placeholders. We've only specified the value for one of those two placeholders, and that's why we see this error. Not enough arguments for format string.

As an aside note from this how the first part of the string which contains the placeholders is referred to as the format string in Python. Let's try again and fix this error.

[Video description begins] Line 1 reads: favorite_sport = "cricket". Line 2 reads: time_spent = 3. Line 3 reads: "I love watching %s on TV - yesterday I watched for %d hours" % (favorite_sport, time_spent). [Video description ends]

We define the second variable called time_spent and we reinvoke our placeholder with the format string. That format string has %s and %d. After that format string, we have the % operator, then, we have two values contained within parentheses, and these two values are favorite_sport and time_spent. This time when we hit Shift+Enter, it runs successfully. There's no error, and we can see that the value of favorite_sport has been correctly spliced in, that's cricket, and the value of time spent has been spliced in as well, that's the integer value 3.

As you can see, these methods of formatting strings suffer from weaknesses, because, we have got to correctly match up the placeholders along with the variables to replace those placeholders. In order to mitigate these weaknesses, Python in recent years has added a new way of formatting strings. These are known as f strings. You can see an f string on screen now, as before,

[Video description begins] Line 1 reads: favorite_sport = "basketball". Line 2 reads: time_spent = 2.5. Line 3 reads: f"I love watching {favorite_sport} on TV - yesterday I watched for {time_spent} hours". [Video description ends]

we have defined two variables favorite_sport and time_spent.

As before, we have a format string, which then prints out the values of the favorite_sport and the time_spent with a form message, there are two big differences. However, the first of these is the use of the character f just before the format string, it's way over to the left of the format string, and the second big difference is that now, we no longer have to match up the placeholders with the variables.

Instead, we have embedded those variables directly into our f string. We've done this by placing them within curly braces. We have two such variables spliced in, favorite_sport and time_spent. When we run this code, we get the exact same message as we had a moment ago. It's a form message, I love watching basketball on TV - yesterday I watched for 2.5 hours. F strings, which have been present in the Python language since 2015, are a great way of avoiding errors, where we fail to match up input arguments with the format string.

Course Summary

[Video description begins] Topic title: Course Summary [Video description ends]

We have now come to the end of this course getting started with programming in Python. We started this course by seeing how we could install Anaconda and Python on Microsoft Windows as well as on the Mac platform. We ran Python from the command line using the interactive shell environment and also created our first brand new Jupyter Notebook. While taking our first baby steps with the Python language we also learned about how we could perform logical operations in Python and noted the slight differences in syntax from Java.

We also run a few simple lines of code. We then looked at the use of variables in Python. We created a few simple variables and performed simple operations with those variables such as assigning and accessing variable values. We saw how Python, like Java and other languages, supports the assignment of multiple variables at one go and how variable reassignment occurs as well. We then moved on to a more detailed exploration of data types in Python.

We started with the basic numeric types such as integer, float, and complex, as well as ways of working with byte values. We then went through a very brief introduction to complex data types, lists, tuples, sets, and dictionaries. These differ from each other in whether they are ordered or not, mutable or immutable, and associative or not.

We also covered various examples that involve strings and understood the use of single, double, and triple quotes. As we learned, single and double quotes are both acceptable delimiters for strings. If you delimit a string with double quotes, it can contain single quotes and vice-versa.

Triple quotes are different. They allow the creation of strings spanning multiple lines. We then briefly discuss the use of format strings, including the F string construct, which has been added to the Python language relatively recently. You now understand the basics of simple Python commands. And are ready to move on to a more detailed discussion of lists, sets, tuples, and dictionaries in the next course performing operations with complex data types coming up next.

Comments

Popular posts from this blog

java chapter11 practice question on abstruct class and interfaces

DAY 12 -AZURE DP900(Microsoft Azure Data Fundamentals: Explore non-relational data in Azure)

java exercise4