
Installing Python and Checking Your Setup. Every journey in programming starts with getting the right tools onto your computer. In this lecture you install Python and confirm that it works, so that every later lesson can focus on writing code and not on fixing your setup.
We begin by explaining what Python is. It is a programming language, which means a way of giving a computer instructions in text that a person can read. To run those instructions, your computer needs a program called the Python interpreter. You will download the current version of Python 3 from the official website, run the installer for your operating system and make sure the option that adds Python to your path is selected on Windows, since forgetting it is the most common beginner problem.
Next you will check the installation. You will open a terminal or command prompt and type a short command that asks Python for its version number. Seeing a version number appear means the interpreter can be found. We also talk about the difference between the python and python3 commands on different systems, so that you know which to use.
You will also choose a code editor. We discuss free options such as Visual Studio Code and IDLE, which comes with Python, and how to create a folder for your course files.
If something goes wrong, we look at the usual causes and their fixes.
By the end of this lecture you will have a working Python installation, a place to save your files and confidence that your setup is ready.
Your First Script: Hello, World. Nearly every programmer begins with the same tiny program, one that displays the words Hello, World. It is a tradition, and it is also a genuinely useful test, because it proves that you can write a program, save it and run it. This lecture walks you through every step.
You will open your editor, create a new file and save it with a name that ends in .py, which tells your computer that it holds Python code. Then you will type a single line that uses the print function, with the message placed inside quotation marks and parentheses. We explain each piece slowly. The word print is the name of a function, which is a ready-made action. The parentheses hold what the function should work with. The quotation marks tell Python that the contents are text and not a command.
Next you will run the file from the terminal and watch the message appear. We discuss what actually happens: Python reads the file from top to bottom and carries out each line in order. You will also see that the file can be run again and again, with the same result every time.
We then experiment. You will change the message, add a second print line and see the output grow, which shows that the order of lines matters.
By the end of this lecture you will be able to write, save and run a Python script that displays a message of your choice.
Printing Text with Strings. Text is one of the most common kinds of information in any program, and in Python a piece of text is called a string. This lecture teaches you how to create strings and display them using print.
You will begin by writing strings with single quotation marks and with double quotation marks, and discover that they behave the same way. We explain why both exist. If your text contains an apostrophe, such as in the word it's, wrapping it in double quotation marks avoids confusion, and the reverse is also true. You will see the error that appears when quotation marks do not match, and learn how to read it.
Next we look at special characters. A backslash followed by a letter creates effects such as a new line or a tab, and a backslash before a quotation mark lets you include that mark inside your text. You will try the new line, the tab and the escaped quotation mark, and see exactly how they change the output.
We also discuss empty strings, strings that contain spaces and how Python treats a string that looks like a number. The important lesson is that quotation marks turn anything into text.
You will practice by printing a short greeting, a sentence containing an apostrophe and a line of text split across two lines.
By the end of this lecture you will be able to create and print strings confidently, including text with quotation marks and special characters.
Printing Multiple Lines and Values. Programs rarely display just one thing. They show several lines, mix words with numbers and arrange output so a person can read it. This lecture explores the print function in more depth, so that you can control exactly what appears on the screen.
You will start by calling print several times to produce several lines, and then learn that a single call can display many values at once when you separate them with commas. Python places a space between them automatically, and you will see how to mix text and numbers in the same call without any trouble.
Next we meet two options of the print function. The sep option changes the separator placed between values, so you can use a dash, a comma or nothing at all. The end option changes what is printed after the message, which normally is a new line. By setting it to something else, you can keep several print calls on the same line. You will try each option and predict the result before running the code, which is a valuable habit.
We also discuss printing blank lines to space out your output, and using the new line character inside a string to create several lines with a single call.
You will finish with a small exercise that prints a tidy receipt-style summary made of several lines and values.
By the end of this lecture you will be able to display multiple lines and values and control their layout with sep and end.
Printing Numbers and Simple Math. Python is also a powerful calculator. In this lecture you use it to do arithmetic, and you learn how numbers differ from text when you print them.
You will begin by printing a number directly, noticing that it needs no quotation marks. Then you will print the result of simple sums: addition with the plus sign, subtraction with the minus sign, multiplication with an asterisk and division with a forward slash. We point out that the asterisk and slash differ from the symbols you may have used in school, and why.
Next we meet other useful operators. Double slash performs division and discards the remainder, the percent sign gives the remainder itself, and double asterisks raise a number to a power. You will try each one with small numbers where you can check the answer in your head. We explain that dividing with a single slash always gives a decimal result, even when the numbers divide evenly.
We discuss the order of operations. Python follows the same rules as mathematics, multiplying before adding, and you can use parentheses to control the order. You will compare an expression with and without parentheses and see that the answers differ.
Finally, you will see the difference between printing the text 2 + 3 in quotation marks and printing the expression 2 + 3 without them. One is displayed as written, and the other is calculated.
By the end of this lecture you will be able to perform basic arithmetic in Python and print the results correctly.
Adding Comments to Your Code. Code is read far more often than it is written, by other people and by your future self. Comments are notes inside your code that Python ignores, and they help readers understand what the code is for. This lecture teaches you to write them well.
You will begin with the hash symbol. Anything after it on a line is a comment, so Python skips it completely. You will add a comment on its own line above some code, and a short one at the end of a line of code, and run the program to confirm that the output does not change.
We then discuss what makes a good comment. A comment should explain why something is done, or what a section is trying to achieve, not simply repeat the code in words. We compare a useless comment, such as one that says print a message above a print call, with a helpful one that explains the purpose of a calculation. Short, clear comments are better than long ones.
You will also learn to use comments to disable a line of code temporarily, which is a useful technique when you are testing and want to see what happens without that line. We mention that the comment should be removed or restored afterward, so that the file stays tidy.
We introduce the idea of a header comment at the top of a file, giving its name and purpose.
By the end of this lecture you will be able to write helpful comments and use them to organize and temporarily disable code.
Reading Your First Error Message. Every programmer makes mistakes, and every programmer sees error messages. The difference between a beginner and an experienced developer is not that the experienced one avoids errors, but that they know how to read them. This lecture removes the fear of errors.
You will start by causing some on purpose. You will leave out a closing quotation mark, misspell the word print, forget a closing parenthesis and use a name that does not exist. Each produces a different message, and you will run each one and look at the result slowly.
We teach you how to read a traceback, which is the report Python prints when something goes wrong. The most useful part is at the bottom, where Python names the type of error and describes the problem in a sentence. Above that, it shows the file name and the line number where the problem was found, and often a caret that points at the spot. You will learn to start from the bottom, go to the line mentioned and check the line above as well, since the real mistake sometimes sits just before the place where Python noticed it.
We introduce the two broad families you will meet: syntax errors, where the code is not written correctly and cannot run at all, and runtime errors, where the code starts but fails partway through.
We finish with a calm routine for fixing errors, one change at a time.
By the end of this lecture you will be able to read an error message and use it to find and fix the problem.
Your First Variable. Programs need to remember things. A variable is a name that you attach to a piece of information so that you can use it again later. This lecture introduces variables, one of the most important ideas in all of programming.
You will create your first variable by choosing a name, writing an equals sign and giving a value, such as a name or an age. We explain that the equals sign in Python does not mean equal in the mathematical sense. It means store the value on the right under the name on the left, and we call this an assignment. A helpful picture is a labeled box into which you put something.
You will then use the variable. Printing the name displays the value stored inside, and you can use the variable in a calculation or combine it with text. We show that using a variable is better than typing the same value in several places, because you can change it once and everything that uses it follows.
You will learn that a variable must be created before it is used, and you will see the error that appears if you try to print one that does not exist. We also discuss the order of execution. Python reads from top to bottom, so a variable only exists from the line where it is created.
You will practice by storing a name, a city and a number, and printing a sentence that uses all three.
By the end of this lecture you will be able to create variables, store values in them and use them in your programs.
Changing a Variable's Value. The word variable means that its value can vary. A variable is not fixed forever when you first create it. You can give it a new value whenever you like, and this lecture explores how that works and why it is so useful.
You will begin by assigning a value to a variable, printing it, assigning a different value and printing again. The second assignment replaces the first, and the old value is gone. We explain this with the labeled box picture: putting something new in the box removes what was there before.
Next you will meet one of the most common patterns in programming, using a variable's current value to calculate its new one. A line such as score equals score plus one looks strange at first, but it reads naturally once you remember that the right side is worked out first, using the old value, and then stored back. You will trace several examples by hand, writing down the value after each line, which builds a skill that you will use for the rest of your programming life.
We introduce the shortcut operators, such as plus equals and minus equals, which do the same thing with less typing. You will use them to build a counter, to reduce a balance and to double a number.
We also show that a variable can change its kind of value, and discuss why doing so is usually confusing.
By the end of this lecture you will be able to update variables and predict what their values will be after a series of changes.
Naming Variables Well. The computer does not care what you call a variable, but people do. Good names make a program easy to read, while poor names make even a short program a puzzle. This lecture covers both the rules Python enforces and the habits that make code clear.
We start with the rules. A name may contain letters, digits and underscores, it cannot begin with a digit, it cannot contain spaces or most symbols and it cannot be one of Python's reserved words, such as for or if. You will try breaking each rule and read the error message that results, so that you can recognize them later. We also point out that names are case sensitive, so score and Score are two different variables, a fact that causes many puzzling bugs.
Then we move to style. Python programmers conventionally write names in lowercase, using underscores to separate words, which is called snake case. You will compare names like x and a with descriptive names such as total_price and student_name, and see how much more readable the second kind is. A name should say what the variable holds, not how it is stored.
We discuss other good habits: avoiding names that are too long, avoiding confusing look-alike letters, and never reusing the names of built-in functions such as print or len, because that would hide the original.
We also introduce the convention of writing constants in capital letters.
By the end of this lecture you will be able to choose clear, valid variable names that follow Python conventions.
Whole Numbers and Decimals. Numbers come in different kinds, and Python treats them differently. This lecture introduces the two most common types, integers and floating-point numbers, and shows how to tell them apart and use them together.
An integer is a whole number, such as 7 or minus 12, with no decimal point. A float is a number with a decimal point, such as 3.14 or 2.0. You will create both, print them and use the type function to ask Python which kind each one is. Seeing the word int or float appear makes the idea concrete. We emphasize that 5 and 5.0 look similar but are different types.
You will explore how they interact in calculations. Adding two integers gives an integer, but as soon as a float is involved, the result becomes a float. Division with a single slash always gives a float, even when the answer is a whole number, while double slash division gives a whole number. You will test each one and note the type of the result.
We discuss a surprise that catches many beginners. Some decimal sums, such as 0.1 plus 0.2, do not give exactly the answer you expect, because computers store decimals in a binary form that cannot represent every value exactly. You will see this and learn to round results with the round function for display.
We also mention writing large numbers with underscores to make them readable.
By the end of this lecture you will be able to recognize integers and floats, predict the type of a result and round decimals for display.
Doing Math with Variables. Variables become powerful when you use them in calculations. Instead of working with fixed numbers, you can store values, calculate with the stored names and change the inputs to get new answers without rewriting anything. This lecture combines variables with arithmetic.
You will begin with a simple example, a shopping scenario in which the price of an item and the quantity are stored in variables. You will multiply them to find a total, store the result in a new variable and print it. We stress that the result of a calculation can itself be stored, which lets you build up a program from small steps, each of which is easy to check.
Next you will work through further everyday calculations: converting a temperature from Celsius to Fahrenheit, finding the average of three numbers, adding a percentage tax to a price and working out an area from a length and a width. For each, you will write the formula in plain words first, translate it into Python and confirm the answer by hand. We practice using parentheses to make sure the order of operations is correct.
You will see the real advantage when you change one of the starting values and run the program again, and every result updates automatically.
We discuss the importance of printing a clear label with each result, so that the output explains itself, and rounding values for tidy display.
By the end of this lecture you will be able to translate simple formulas into Python and use variables to make them reusable.
Joining Strings Together. Programs often need to build sentences from smaller pieces, such as a greeting that includes someone's name. Joining strings is called concatenation, and this lecture shows how to do it with the plus operator and why you must take care with spaces.
You will begin by joining two strings with a plus sign and printing the result. The pieces are joined exactly as they are, with nothing added between them, so you will notice that two words run together unless you include a space. You will fix this by adding a space inside one of the strings, or by joining a separate string that contains only a space.
Next you will combine variables with text. You will store a first name and a last name in variables and join them into a full name, build a greeting that uses the name and construct a longer sentence from several parts. We compare the result with the comma approach used in print, noting that commas add spaces automatically but do not create a single new string that you can store and reuse.
We introduce the plus equals operator for strings, which adds to the end of an existing string and is useful for building up a message step by step.
You will also see what happens if you try to join a string and a number, which produces an error. We do not fix it yet, because it leads directly into the next lecture, but you will read the message and think about what it is telling you.
By the end of this lecture you will be able to build new strings by joining smaller ones.
When Types Collide: TypeError. Python is strict about the kinds of values it combines. Some operations make sense for numbers but not for text, and when you mix them wrongly, Python stops with a TypeError. This lecture explains why it happens and how to read the message.
You will begin by recreating the problem from the previous lecture. Joining a string and a number with the plus sign fails, and Python explains that it can only concatenate a string to another string. You will read the full message slowly and identify the three things it tells you: the type of error, the operation that failed and the kinds of values involved.
We then explore other collisions. You will try subtracting a string from a number, multiplying two strings together and adding a number to the text that looks like a number, such as the characters 5 and 3. The last case is especially instructive. Adding the numbers 5 and 3 gives 8, while adding the strings 5 and 3 gives 53, because the plus sign means joining for strings and adding for numbers.
You will use the type function to inspect values and discover which kinds they hold, which is the first step in diagnosing this error. We discuss common sources of the problem, including values that arrive as text from user input.
You will learn the general approach to solving it: check the types, decide what you really want and convert one of the values, which is the topic of the next two lectures.
By the end of this lecture you will be able to recognize a TypeError, explain its cause and find the values that collided.
Converting Numbers to Strings with str(). The cure for many type problems is to convert a value from one type to another. This lecture introduces str, which turns a number into text, and shows how to use it when you need to join numbers with words.
You will start with the problem from the last lecture: building a sentence that includes an age stored as a number. By wrapping the number in str, you create a string version of it, which can be joined to other text with the plus sign. You will write several examples, including a message that reports a score, one that lists a price and one that combines several numbers and words.
We explain an important point. The conversion does not change the original variable. It produces a new value, which you can use immediately or store in another variable. You will check this by printing the type of the variable before and after, seeing that the original remains a number.
You will also learn when conversion is unnecessary. The print function can display numbers and strings together when separated by commas, with no conversion at all, so you can choose the approach that makes the code clearest. We mention that f-strings, which come later in the course, provide an even tidier way.
We also look at converting other kinds of values, such as the Boolean values True and False, and observe how they appear as text.
By the end of this lecture you will be able to convert numbers to strings and use them to build messages.
Converting Strings to Numbers with int() and float(). The opposite problem is just as common. Text that looks like a number cannot be used in arithmetic until it has been converted. This lecture introduces int and float, which turn strings into numbers.
You will begin with the characters 42 stored in quotation marks. Trying to add one to it fails, because it is text. By passing the string to int, you obtain the whole number 42, and the calculation works. You will do the same with float for text such as 3.5, producing a decimal number. We explain which function to choose: int for whole numbers and float when a decimal point is involved.
This skill matters because information often arrives as text. Input typed by a user, values read from a file and data copied from a website are all strings. You will use the input function to ask the user for a number, see that the answer arrives as text and convert it before calculating, building a small program such as an age calculator or a simple price total.
Not every string can be converted. You will see the ValueError that appears when you try to convert a word, or the text 3.5 with int, and learn to read it. We mention that handling such errors gracefully is a topic for the later section on exceptions.
You will also learn that converting a float with int discards the decimal part, rather than rounding.
By the end of this lecture you will be able to convert text to whole numbers and decimals and recognize when conversion will fail.
Multi-Line Strings with Triple Quotes. So far, strings have fitted on a single line. Sometimes you need text that spans several lines, such as a poem, a menu or a block of instructions. Triple quotation marks make that easy, and this lecture shows how to use them.
You will begin by writing a string that starts and ends with three double quotation marks, or three single ones, and spans several lines of your file. When you print it, the line breaks you typed appear in the output exactly as you wrote them. Compare this with the older approach of placing new line characters inside a normal string, which works but is harder to read and edit.
We look at the details. Every character between the triple quotes is part of the string, including spaces at the start of lines, so indentation affects the output. You will experiment by indenting the lines differently and seeing the result. You will also discover that a string can contain ordinary quotation marks without any trouble, which makes triple quotes convenient for text full of apostrophes and quotation marks.
You will store a multi-line string in a variable and use it later, and you will print a banner, a short letter and a simple menu to see practical uses.
We also mention the other place that you will meet triple quotes. A string placed at the beginning of a function is a docstring, which documents what the function does, a topic that returns in the section on functions.
We discuss avoiding a blank first line, by starting the text immediately after the opening quotes.
By the end of this lecture you will be able to create, store and print strings that span several lines.
Measuring Strings with len(). It is often useful to know how long a piece of text is. A password may need a minimum number of characters, a message may have a maximum length, and a loop may need to know when to stop. The len function gives you the answer, and this lecture shows how to use it.
You will begin by passing a string to len and printing the result. For the text hello, the answer is five. We explain what is being counted: every character, including letters, digits, punctuation and spaces. You will test this with a sentence and count by hand to confirm that spaces are included, a detail that surprises many beginners.
Next you will try some special cases. An empty string has a length of zero. A string containing only spaces is not empty, and its length equals the number of spaces. A string with a new line character counts that character as one. You will measure each case and predict the answer before running the code.
You will then use the length in practical ways. You will build a simple check that a password is long enough, compare the lengths of two words to find the longer one and calculate how many characters remain before a message reaches a limit. We combine len with variables and with f-strings or print to show readable results.
We also note that len works on other things, such as lists, which you will meet later.
By the end of this lecture you will be able to measure strings and use their lengths in simple checks.
Repeating Strings with the * Operator. The multiplication sign has a second meaning when it is used with a string. It repeats the text a given number of times. This lecture shows how this small feature makes certain tasks very easy.
You will start with a short word and multiply it by three, and see the word repeated three times in a row with nothing between the copies. You will then add a space or a separator to the word first, so that the repetition looks tidy. We emphasize that the number must be a whole number, and you will see the error that appears when you use a decimal, or when you try to multiply two strings together, which is not allowed.
You will use repetition to create visual elements. A line of dashes or equals signs makes a neat divider for a report, and you will build a title with a divider above and below it, whose length matches the title by using len. A row of stars, a simple border and a short bar chart made of repeated characters are fun ways to see the idea at work.
We discuss special values. Multiplying a string by zero gives an empty string, and multiplying by a negative number also gives an empty string. You will check these cases.
We also compare repeating with joining. Both use symbols you already know, but they work differently, and we learn to tell them apart by reading the types on each side.
By the end of this lecture you will be able to repeat strings to create separators, borders and simple patterns.
Getting a Single Character with Indexing. A string is an ordered sequence of characters, and each character has a position. Indexing lets you pick out one of them by its position. This lecture introduces the idea, and the surprising fact that counting starts from zero.
You will begin with a word, such as python, and use square brackets to retrieve its first character. The position of the first character is zero, not one, and the position of the second is one. We explain why programming languages count from zero and give you a picture that helps: the index measures how far a character is from the start. You will print the characters at several positions and write the index numbers beneath the word to see the pattern.
Next you will use negative indexes. Position minus one is the last character, minus two is the one before it and so on. This is a convenient way to reach the end of a string without knowing its length. You will compare it with using len minus one, which gives the same character.
You will meet the IndexError that appears when you ask for a position beyond the end of the string, and learn to read the message. We discuss how to avoid it by checking the length first.
You will use indexing to get the first letter of a name, the last digit of a number written as text and the middle character of a word.
We note that strings cannot be changed by assigning to an index.
By the end of this lecture you will be able to retrieve individual characters using positive and negative indexes.
Slicing Strings. Indexing retrieves a single character, but often you want a section of text, such as the first three letters, the last four digits or everything after a certain point. Slicing does this, and it is one of the most useful tools for handling text.
A slice uses square brackets with a start and an end, separated by a colon. You will write a slice for the first few characters of a word and learn the rule that surprises most beginners: the start position is included, and the end position is not. We explain it with a picture in which indexes mark the gaps between characters, so that a slice takes everything between two gaps.
Next you will use shortcuts. If you leave out the start, the slice begins at the start of the string, and if you leave out the end, it continues to the end. You will use these to take a prefix, a suffix and a copy of the whole string. Negative numbers work in slices too, and you will use them to take the last few characters.
We introduce the optional step, a third number that selects every second or third character, and a step of minus one, which reverses a string. You will reverse a word and check whether it reads the same backward.
You will see that a slice never causes an error when it goes out of range, unlike a single index. Python simply returns what exists.
You will practice by extracting parts of a date, a file name and a phone number written as text.
By the end of this lecture you will be able to extract any part of a string using slices.
Changing Case with String Methods. Python strings come with built-in actions called methods, and some of the most useful change the case of letters. This lecture introduces the method syntax and the main case methods.
You will begin with the dot notation. A method is called by writing the string, a dot, the method name and parentheses, as in the case of upper, which returns a version of the text in capital letters. You will try upper, lower, title, which capitalizes each word, and capitalize, which changes only the first letter of the string. You will run each on the same sentence and compare the results.
We explain an important point about strings: they cannot be changed in place, so a method returns a new string and leaves the original untouched. You will see that calling upper on a variable without storing the result appears to do nothing, and fix the problem by assigning the result to a variable. This is the most common beginner mistake with methods, and understanding it will help you throughout the course.
Case methods have practical uses. When comparing text typed by a user, converting both sides to lowercase makes the comparison fair, so that Yes, YES and yes are all treated alike. You will build a small check that does exactly this. You will also format names and titles consistently.
We also mention methods that test case, such as isupper and islower.
By the end of this lecture you will be able to use string methods to change and check case, and remember to store the results.
Cleaning Text with strip() and replace(). Real text is messy. It arrives with extra spaces at the ends, inconsistent punctuation and unwanted characters. Before a program can use it, the text must be cleaned. This lecture introduces two methods that handle most everyday cleaning, strip and replace.
You will begin with strip, which removes whitespace from both ends of a string. Spaces, tabs and new lines at the edges all disappear, while spaces inside the text are left alone. You will practice on text with generous padding and use len before and after to see the difference. We also meet lstrip and rstrip, which clean only the left or right side, and learn that strip can be given a set of characters to remove from the ends instead of whitespace.
Next comes replace, which swaps every occurrence of one piece of text for another. You will replace a word in a sentence, remove unwanted characters by replacing them with an empty string and change dashes to spaces. We discuss the optional count argument, which limits how many replacements are made, and that replace is case sensitive, so replacing cat does not affect Cat.
You will chain the methods, such as applying strip and then lower and then replace in a single line, and learn how to read a chain from left to right.
We remind you that each method returns a new string, so the result must be stored.
You will finish by cleaning a messy product name and a phone number.
By the end of this lecture you will be able to clean text using strip and replace.
Searching Inside Strings. A common task is finding out whether a piece of text contains something, or where it appears. This lecture introduces the tools Python provides for searching within strings.
You will begin with the in operator, which answers a yes or no question. Is the word cat in this sentence? The result is a Boolean, either True or False, and you will print it and use it in simple checks. We point out that the search is case sensitive, so you will combine it with lower when you want a fair comparison.
Next you will learn the find method, which returns the position of the first match, or minus one when the text is not found. You will use the result with slicing to extract the part of a string that follows a particular marker, such as the portion of an email address after the at sign. We compare find with index, which does the same job but raises an error when nothing is found, and discuss which to choose.
You will also use count, which tells you how many times a piece of text occurs, and startswith and endswith, which check the beginning and end of a string. These are perfect for checking file extensions, prefixes and greetings.
We build a small exercise that examines a sentence, reporting whether it contains a word, where the word begins and how many times a letter appears.
We also discuss that searching for an empty string always succeeds.
By the end of this lecture you will be able to search strings for text, positions and counts.
Formatting Strings with f-strings. Building sentences from variables by joining pieces with plus signs and conversions becomes clumsy quickly. F-strings offer a cleaner way. You write the text and place variables directly inside it, and Python fills in their values. This lecture teaches the technique that most modern Python code uses.
You will start by placing the letter f before the opening quotation mark and writing a variable name inside curly braces. When the program runs, the braces are replaced with the value of the variable. You will rewrite earlier examples that used str and plus signs and see how much shorter and clearer they become. Numbers need no conversion, because the f-string takes care of it.
Curly braces can hold more than a single name. You can place a calculation, such as a price multiplied by a quantity, or a method call, such as a name converted to uppercase, directly inside. We keep these simple, for readability.
Next you will learn format specifications, which follow a colon inside the braces. You will show a number with two decimal places, add thousands separators, display a percentage and pad text to a fixed width with alignment, so that you can print neat tables of values. You will build a small receipt that lines up its columns.
We discuss common mistakes, such as forgetting the f, which prints the braces literally, and how to include a literal brace by doubling it.
By the end of this lecture you will be able to build clear, well-formatted text with f-strings.
True and False: Booleans. Decisions in a program depend on questions that have a yes or no answer. Python represents those answers with a special type, the Boolean, which has exactly two values, True and False. This lecture introduces them.
You will begin by printing True and False and checking their type, which is bool. We emphasize the capital first letter, since true in lowercase is not recognized, and you will see the error that appears. The values are not strings, so they have no quotation marks.
Next you will see where Booleans come from. Comparisons and questions produce them. You will print the result of expressions such as whether five is greater than three, whether a string is empty or whether a word contains a letter, and store the answer in a variable. We explain that a Boolean is simply a value like any other, which can be stored, printed and passed around.
You will meet the idea of truthiness. Python treats certain values as false when asked a yes or no question, including zero, an empty string and the special value None, and treats most other values as true. You will test several with the bool function and note the results.
We also show that True and False behave like the numbers one and zero in arithmetic, which allows you to add them to count how many conditions are true, and we consider when that is clear and when it is confusing.
By the end of this lecture you will be able to create, store and interpret Boolean values.
Comparing Numbers. To make decisions, a program has to compare values. Comparison operators ask questions about two values and produce a Boolean answer. This lecture introduces the operators for numbers and the traps to avoid.
You will learn the six operators: equal to, written with two equals signs, not equal to, written with an exclamation mark and an equals sign, greater than, less than, greater than or equal to and less than or equal to. You will print the result of each comparison with small numbers where the answer is obvious, and then with variables. We spend time on the most common beginner mistake, which is using a single equals sign, the assignment operator, when you mean to compare. You will see the error that appears in some contexts and the silent bug that appears in others.
Next you will compare integers with floats and find that five and five point zero are equal, even though their types differ. We revisit the surprise that some decimal results are not exactly what you expect, which means that comparing floats for exact equality can be unreliable, and you will learn to compare with a small tolerance or to round first.
You will also chain comparisons, such as checking whether a number lies between two limits in a single expression, which Python allows and which reads almost like mathematics.
You will practice with examples such as checking an age limit, comparing two scores and testing whether a number is within a range.
By the end of this lecture you will be able to compare numbers and interpret the results.
Comparing Strings. Strings can be compared too, but the rules are different from those for numbers, and they hold some surprises. This lecture explains how Python compares text.
You will begin with equality. Two strings are equal only if they match exactly, including their capital letters and spaces, so Python and python are not equal. You will test several pairs and observe the results, including strings that differ only by a trailing space. This leads naturally to the standard remedy: clean the text with strip and convert it to a single case before comparing.
Next you will use the ordering operators. Python compares strings character by character, using the numeric code assigned to each character. You will see that apple comes before banana, as in a dictionary, but that all capital letters come before all lowercase ones, so Zebra sorts before apple. We explain why, and show how to compare in lowercase to get a more natural order. You will also compare a short word with a longer word that starts the same way and see that the shorter one comes first.
We distinguish comparing strings from comparing numbers that happen to be written as text. The string 10 is less than the string 9, because the first characters are compared first. You will see this and learn to convert to numbers when the number is what matters.
You will finish with a small program that compares two names alphabetically.
By the end of this lecture you will be able to compare strings correctly and avoid common pitfalls.
Your First if Statement. Until now, every line of your programs has run, in order, every time. Real programs need to make choices, doing something only when a condition is true. The if statement provides that ability, and this lecture introduces it.
You will write your first if statement. It begins with the word if, followed by a condition, which is an expression that produces True or False, and a colon. The lines that should run only when the condition is true are indented beneath it. We spend time on this indentation, because Python uses it to understand which lines belong to the if. You will see what happens when the indentation is missing or inconsistent, and read the IndentationError message that results.
You will run examples. If a number is greater than ten, print a message. If a password is long enough, report that it is acceptable. If a string is empty, ask for input. For each, you will run the program with values that make the condition true and then with values that make it false, and observe that the indented lines are skipped in the second case. Changing the starting value and rerunning teaches the cause and effect clearly.
We show that several lines can be indented beneath one if, and that the lines after the block run regardless of the outcome.
We also discuss writing clear conditions and using variables to make them readable.
By the end of this lecture you will be able to write if statements and understand how indentation defines a block.
Adding an else Clause. An if statement does something when a condition is true and nothing otherwise. Often you need an alternative action for the other case. The else clause provides it, and this lecture shows how to use it to make two-way decisions.
You will extend an if statement by adding else, followed by a colon, at the same indentation level as the if. The indented block beneath else runs only when the condition is false. We emphasize that exactly one of the two blocks runs, never both and never neither, which makes the logic easy to reason about. You will test this by running the same program with different inputs and tracing which block executes.
You will build several small programs with two outcomes. A program decides whether a number is even or odd by using the remainder operator. Another checks whether someone is old enough for an activity. A third reports whether a password meets a length requirement and a fourth tells you whether a word starts with a vowel. For each, you will state the rule in plain English before writing the code.
We discuss common mistakes, including placing else at the wrong indentation, forgetting the colon and adding a condition after else, which is not allowed because else needs none.
We also show how to combine the decision with user input, converting the answer first.
By the end of this lecture you will be able to write two-way decisions with if and else and trace which branch runs.
Choosing Between Many Paths with elif. Many decisions have more than two outcomes. A grade might be A, B, C or fail, and a temperature might be cold, mild or hot. The elif clause, short for else if, lets you test several conditions in order. This lecture shows how.
You will begin with a chain of an if, one or more elif clauses and an optional final else. Python checks the conditions from top to bottom, runs the block belonging to the first condition that is true and skips the rest. We stress this behavior because it makes the order of the conditions important. You will see a program in which a broad condition placed first captures everything, so that the more specific ones below never run, and you will fix it by reordering.
You will build practical examples. A grade calculator turns a score into a letter, a ticket price program charges according to age bands and a simple weather advice tool responds to a temperature. For each, you will list the ranges on paper, translate them into conditions and test the boundaries, such as scores of exactly eighty or ninety, where mistakes hide.
We compare a chain of elif clauses with a series of separate if statements. With separate ifs, several blocks may run, which is sometimes what you want and sometimes a bug. You will try both and see the difference.
We also discuss the value of a final else as a catch-all for unexpected input.
By the end of this lecture you will be able to write multi-way decisions and order conditions correctly.
Combining Conditions with and, or, not. Real decisions often depend on several facts at once. You may be allowed to enter if you have a ticket and are old enough, or if you are on the guest list. Logical operators let you combine simple conditions into richer ones, and this lecture introduces and, or and not.
You will begin with and, which is true only when both sides are true. You will check a number against both a lower and an upper limit, and a username and password together. Next comes or, which is true when at least one side is true. You will test whether a day is Saturday or Sunday, and whether a letter is a vowel by comparing it with several options. Then you will use not, which reverses a Boolean, and see how it can make a condition read more naturally.
To make this concrete, we use truth tables. You will print the result of every combination of True and False for each operator and see the pattern. We then explain short-circuit evaluation: Python stops evaluating as soon as the answer is known, so in an and expression a false first part means the second part is never examined. This has practical uses, such as checking that a string is not empty before examining its first character.
We discuss precedence. Not is applied first, then and, then or, and parentheses make the intention clear, so you will use them generously.
You will build a small program that combines several conditions to decide on a discount.
By the end of this lecture you will be able to combine conditions using and, or and not.
Nested Decisions with Text Checks. Sometimes a decision depends on the outcome of an earlier decision. You first check one thing, and only then check another. Placing one if statement inside another is called nesting, and this lecture applies it to checking text.
You will begin with a simple example. A program asks for a password, first checks whether it is long enough and, only if it is, checks whether it contains a digit. We show how the inner if is indented further, so that it belongs to the outer block and runs only when the outer condition is true. You will trace the program with several inputs and note which messages appear for each.
Next you will combine nesting with the string tools from earlier lectures. You will check that an email address contains the at sign and then that the part after it contains a dot, and test whether a word starts with a capital letter and ends with a full stop. We use methods such as in, startswith, endswith, isdigit and isalpha to build the checks, and strip and lower to normalize the text first.
We discuss readability. Deep nesting quickly becomes hard to follow, so we show how to flatten some structures by using and, or by checking the unacceptable cases first and reporting them one at a time. You will rewrite a three-level nested program in a simpler form and compare the two versions.
We emphasize testing every path, including inputs that fail at each level.
By the end of this lecture you will be able to write nested decisions and decide when a simpler structure is clearer.
Your First for Loop with range(). Computers are excellent at repeating work, and a loop is how you ask for it. Instead of writing the same line fifty times, you write it once and tell Python how many times to repeat it. This lecture introduces the for loop and the range function.
You will begin with the structure. The word for is followed by a name for the loop variable, the word in, a collection of values and a colon, and the lines to repeat are indented beneath it. The range function produces a sequence of whole numbers, so that for i in range(5) runs the block five times. You will print a message inside such a loop and watch it appear five times.
Then you will look at the loop variable. On each pass, it takes the next value from the sequence, and you will print it to see the numbers zero to four. We stress that range starts at zero and stops before the number you give it, which echoes the way string indexes work, and that the loop variable is an ordinary name you can use in calculations. You will print a table of squares, a countdown message and a multiplication table for a chosen number.
We discuss choosing the loop variable name. Short names such as i are conventional for simple counters, while descriptive names are better when the value has meaning.
We also show that the variable keeps its last value after the loop ends, and what happens when the range is zero, in which case the block never runs.
By the end of this lecture you will be able to repeat actions a set number of times with a for loop.
Loop Variable and range() Start, Stop, Step. The range function can do more than count from zero. It accepts a start, a stop and a step, and with them you can produce a wide variety of sequences. This lecture explores those options and the loop variable that receives the values.
You will begin with two arguments, a start and a stop, so that range(1, 6) gives one to five. We repeat the rule that the stop value is not included, and you will practice converting a description, such as the numbers from ten to twenty, into the correct arguments, which means using twenty one as the stop. Counting from one is useful for human-friendly output, such as numbering a list.
Next you will add the third argument, the step. A step of two gives every second number, which can print even numbers or odd numbers depending on the start. A negative step counts downward, so that range(10, 0, minus one) produces a countdown. You will experiment with different values, and see that a step that moves away from the stop produces an empty sequence and so no repetitions.
You will use these in small programs: summing a series, printing a table of multiples of seven, listing every tenth number and counting down to a launch message. For each, you predict the output before running it.
We also show that range is not a list but produces numbers as needed, and how to see its contents by converting it with list, which is helpful for checking your understanding.
By the end of this lecture you will be able to control the start, stop and step of a loop.
Looping Over a String. A for loop can repeat over more than numbers. It can take each item of any sequence in turn, and a string is a sequence of characters. This lecture shows how to loop through text, one character at a time.
You will begin with a word and a loop that prints each character on its own line. On every pass, the loop variable holds the next character, so the loop needs no counting and no indexes. We compare this with the approach of looping over range of len and indexing, and show that looping directly over the string is shorter and clearer, while the indexed version is useful when you also need the position.
Looping over text solves many everyday problems. You will count how many times a particular letter appears, count the vowels in a sentence, build a new string with the characters separated by dashes and print a word with each letter repeated. We introduce the pattern of starting with an empty string or a counter before the loop and updating it inside, which becomes a template for much of your later code.
We combine the loop with decisions from the previous section, for example counting uppercase letters or digits with methods such as isupper and isdigit, and skipping spaces.
We also show how to reverse a string by building a new one from the characters, and compare it with slicing.
You will also learn to loop with enumerate, which supplies a counter alongside each character.
By the end of this lecture you will be able to loop over text and process it character by character.
Accumulating a Total in a Loop. Many loops exist to build up a result, such as a sum, a product or a running count. This pattern is called accumulation, and it is among the most important in programming. This lecture teaches it step by step.
The pattern has three parts. First, you create a variable before the loop and give it a starting value, which is zero for a sum or a count and one for a product. Second, inside the loop, you update the variable using the current value. Third, after the loop, you use the final result. You will write a loop that adds the numbers from one to ten and prints the total, and trace it on paper, writing down the value of the accumulator after every pass.
You will practice on several variations: summing the first hundred numbers, calculating a factorial, finding the average of a set of values by dividing the total by the count and adding up the prices of items. We explain the typical mistakes. Forgetting to set the starting value causes an error, putting the starting line inside the loop resets it on every pass so the answer is wrong, and printing inside the loop when you meant to print only at the end produces a stream of partial results.
We also show how to print a running total on every pass, which is a helpful way to watch the process, and how to compare the result with the formula you may know for the sum of consecutive numbers.
By the end of this lecture you will be able to accumulate sums, counts and products in a loop.
Using if Inside a Loop. Loops and decisions are powerful alone and even more powerful together. Placing an if statement inside a loop lets you treat each item differently, depending on its value. This lecture combines them.
You will begin with a loop over the numbers from one to twenty that prints only the even ones, using the remainder operator in the condition. We emphasize the indentation. The if is indented beneath the for, and the action is indented beneath the if, so that the structure is clear. You will trace several passes by hand, noting which pass takes the action and which skips it.
Next you will use the combination to filter and count. You will count how many numbers in a range are divisible by three, add up only the positive values, find the largest number seen so far by comparing each value with a stored maximum and count the words in a string that start with a capital letter. These examples reuse the accumulator pattern, with the update placed inside the if.
You will also add an else, so that every pass does something, such as labeling numbers as even or odd or printing fizz for multiples of three and buzz for multiples of five. We work through the classic fizz buzz exercise, taking care with the order of the conditions, since a number that is a multiple of both needs its own case.
We discuss testing a loop with different inputs, including an empty one.
By the end of this lecture you will be able to filter, count and classify items by combining loops and conditions.
The while Loop. A for loop repeats a known number of times, or once for each item in a sequence. Sometimes you do not know in advance how many repetitions are needed. You want to continue until something happens. The while loop does this, and this lecture introduces it.
A while loop begins with the word while, a condition and a colon. As long as the condition is true, the indented block runs, and then the condition is checked again. You will write a loop that counts from one to five using a counter variable, and see the three essential ingredients: a starting value, a condition and a change inside the loop that eventually makes the condition false.
The danger is an infinite loop, which occurs when the condition never becomes false, usually because the counter is not updated. You will create one on purpose, learn how to stop it from the keyboard and understand what went wrong. Developing the habit of checking that every while loop can end is one of the most valuable lessons here.
You will then use while loops for situations that really suit them. A program asks the user for a password and repeats until the right one is entered. Another keeps halving a number until it falls below one, counting the steps, and another keeps adding numbers until the total passes a target.
We compare for and while. Use for when you know the sequence, and while when you wait for a condition.
By the end of this lecture you will be able to write while loops that end correctly and recognize when to use them.
Stopping Early with break and Skipping with continue. Normal loops run until their condition or sequence is exhausted, but sometimes you need more control. You may want to stop as soon as you find what you are looking for, or skip an item that is not interesting. The break and continue statements provide this control.
You will start with break, which ends the loop immediately. You will search a list of numbers for the first one divisible by seven and stop as soon as it is found, instead of examining the rest. We show how this saves work and how to use a variable to remember what was found. You will also use break to leave a loop that would otherwise run forever, such as a while loop written with a condition that is always true, and which ends when the user types a quit command.
Next comes continue, which skips the rest of the current pass and moves on to the next one. You will print the numbers from one to ten except for the multiples of three, and process a sentence while ignoring spaces. We contrast the two statements by running the same loop with each, and trace the output.
You will learn about the else clause on a loop, which runs only if the loop finished without a break. It is an elegant way to handle the not found case, and we use it to check whether a number is prime.
We discuss clarity. Overusing these statements can make a loop harder to follow, so we compare versions with and without them.
By the end of this lecture you will be able to control loops using break and continue.
Nested Loops and Star Patterns. A loop inside another loop is called a nested loop. For each pass of the outer loop, the inner loop runs completely. This structure is perfect for grids, tables and patterns, and this lecture introduces it using star patterns, which make the behavior visible.
You will begin with a simple nested loop that prints a pair of values for each combination, such as a row number and a column number. Watching the output shows that the inner variable changes quickly while the outer changes slowly, like the hands of a clock. We trace the first several passes by hand.
Then you will draw shapes. A rectangle of stars uses an outer loop for the rows and an inner loop that prints the stars for each row on a single line, using the end option of print to avoid line breaks and a plain print to start a new row. You will modify the code to change the width and height. Next you will print a right-angled triangle, in which the number of stars in each row depends on the row number, and then an upside-down triangle and a pyramid with leading spaces. For each, you will first sketch the pattern on paper and work out the relationship between the row and the number of items.
We also build a multiplication table with aligned columns, using the formatting skills from earlier.
We discuss the cost of nesting. The inner block runs many times, so the number of operations multiplies.
By the end of this lecture you will be able to write nested loops and use them to print grids and patterns.
Creating Your First List. So far, each variable has held a single value. A list holds several values together, in order, under one name. Lists are one of the most important structures in Python, and this lecture introduces how to create and display them.
You will write a list using square brackets, with items separated by commas. You will create a list of names, a list of numbers and a list of mixed values, and print each one to see how Python displays it. We point out that a list can contain any kind of value, including other lists, though keeping the items similar usually makes a program easier to understand.
We explain the key properties. A list is ordered, so the items stay in the order you wrote them, it can contain duplicates and it can be changed after it is created, which sets it apart from strings. You will create an empty list, which is a common starting point for collecting results, and check its length with len.
You will see how to build a list from other things. The list function turns a string into a list of its characters and a range into a list of numbers, and the split method of a string breaks a sentence into a list of words. These are common ways to get data into a list.
We also discuss naming. A variable that holds several things is best given a plural name, such as names or scores, which makes the code read naturally.
By the end of this lecture you will be able to create lists, display them and measure their length.
Getting Items by Index. Each item in a list has a position, called its index, and you can retrieve an item by using that position in square brackets. This lecture applies what you learned about string indexing to lists.
You will begin with a list of colors and retrieve the first one, using index zero. We repeat the principle that counting starts at zero, and you will write the index numbers beneath a list to see which item each refers to. You will retrieve items from the middle and from the end, and use negative indexes, where minus one is the last item and minus two is the one before it, so that you can reach the end without knowing the length.
You will meet the IndexError that occurs when you ask for a position that does not exist. We read the message together and discuss how to avoid it, by checking the length before indexing, or by using the last valid index, which is len minus one. You will deliberately cause the error to recognize it later.
Next you will work with lists of lists. A list can hold other lists, so that a table can be represented as rows, and you can reach a single cell by using two sets of brackets, one after the other. You will build a small grid, such as a seating plan, and retrieve values from it.
We also show how to use an index in a calculation, for example the first and last items of a list of scores to find the range.
By the end of this lecture you will be able to retrieve items from lists using positive and negative indexes.
Changing Items and Adding with append(). Unlike strings, lists can be changed after they are created. You can replace an item, and you can make the list longer. This lecture shows how to do both, and introduces the append method, which you will use constantly.
You will start by replacing an item. Assigning to an index, as in names at position one equals a new value, overwrites what was there. You will print the list before and after to see the change. We contrast this with strings, which cannot be changed this way, and explain that this difference is called mutability.
Next comes append, which adds an item to the end of a list. You will begin with an empty list and add items one at a time, watching the list grow. We then combine append with a loop to collect results, such as the squares of the numbers from one to ten, the words of a sentence that are longer than four letters or the values a user types in until they enter a stop word. This pattern of creating an empty list, looping and appending is one of the most common in Python.
We also meet insert, which adds an item at a chosen position, and extend, which adds all the items of another list. You will compare extend with append when the thing being added is itself a list, and see why the results differ.
We discuss that these methods change the list in place and return nothing, a frequent source of confusion.
By the end of this lecture you will be able to change list items and grow lists with append, insert and extend.
Removing Items from a List. Lists grow and also shrink. You may need to delete an item you no longer want, remove a particular value or take items off the end one by one. This lecture shows the tools Python provides, and when to use each.
You will begin with remove, which deletes the first item that matches a given value. You will remove a name from a list of guests and see the remaining list. If the value is not present, Python raises a ValueError, so we show how to check with the in operator first. We note that remove deletes only the first match, and you will see what happens with duplicates.
Next you will meet pop, which removes the item at a given position and returns it, so that you can use it. Without an argument, pop removes the last item, which makes a list work like a stack, and you will build a small example, such as undoing the latest action. We also use pop with index zero to take items from the front, as in a queue.
The del statement deletes an item by its index, or a whole slice, and clear empties the entire list. You will compare all of these on the same starting list to see their effects side by side.
We discuss a classic trap: removing items from a list while looping over it, which causes items to be skipped. You will see the problem and learn the safe approach, which is to loop over a copy or build a new list of the items to keep.
By the end of this lecture you will be able to remove items from lists with remove, pop, del and clear.
Slicing Lists and Checking Membership. Slicing works on lists in just the same way as on strings, and the in operator lets you check whether a value is present. This lecture covers both, which together make many tasks simple.
You will start with slices. A slice such as the items from position one up to, but not including, position four produces a new list. You will use shortcuts to take the first few items, the last few and everything after a position, and use a step to select every second item. Negative indexes work as they do for strings. We emphasize that a slice creates a new list, so changing the slice does not affect the original, and you will confirm it.
You will learn useful idioms. A slice with no start or end copies the whole list, and a slice with a step of minus one produces a reversed copy. You can assign to a slice to replace several items at once, which we demonstrate carefully.
Next comes membership. The in operator returns True when a value appears in the list, and not in returns the opposite. You will use it in an if statement to check whether a username is on a list of allowed users, and to avoid adding a duplicate to a list of unique items. We compare it with the count method, which says how many times a value appears, and the index method, which reports where it first appears and raises an error if it is absent.
You will finish by writing a small program that cleans a list of entries.
By the end of this lecture you will be able to extract parts of lists and test whether values are present.
Looping Over a List. Lists exist to be processed, and loops are how you process them. This lecture shows the ways to loop over a list and when each is appropriate.
You will start with the simplest and most readable form, in which the loop variable takes each item in turn. You will print every name in a list, add up a list of numbers, find the largest value and build a new list of the doubled values. We emphasize choosing a good loop variable name, such as name for a list called names, which makes the code read like a sentence.
Sometimes you also need the position of each item. You will see the approach of looping over a range of the list's length and indexing, and then the better alternative, enumerate, which provides the index and the item together. You will use it to print a numbered list that begins at one by passing a start value. We also meet zip, which loops over two lists in parallel, for example names and scores, and discuss what happens when the lists have different lengths.
You will combine loops with conditions to filter, count and search. We discuss modifying a list while looping over it and show how to avoid trouble by building a new list.
We introduce list comprehensions briefly as a compact alternative for simple cases, so that you can recognize them, while keeping the focus on the explicit loop, which is clearer for beginners.
By the end of this lecture you will be able to process list items with loops, enumerate and zip.
Sorting Lists. Putting items in order is one of the most common tasks in programming, whether you are ranking scores, alphabetizing names or finding the smallest value. Python makes sorting easy, and this lecture shows the options.
You will begin with the sort method, which rearranges a list in place into ascending order. You will sort numbers and words, and see that the original order is lost. Then you will use the sorted function, which returns a new sorted list and leaves the original unchanged, and you will compare the two and decide which to use. We point out a common mistake, which is storing the result of sort in a variable, because the method returns None.
Next, you will sort in descending order using the reverse option, and learn about the reverse method, which simply flips the existing order without sorting. We revisit the rule for sorting text, in which all capital letters come before lowercase ones, and use the key option with a function such as str.lower to get a case-insensitive order. You will also sort words by their length with key set to len.
We discuss the error that occurs when a list mixes numbers and strings, which cannot be compared with each other, and how to fix it by converting.
You will use sorting to find the smallest and largest items, a top three and a median of a list of numbers, and compare with the built-in min and max functions.
By the end of this lecture you will be able to sort lists in several ways and choose between sort and sorted.
Tuples: Lists That Cannot Change. A tuple looks like a list, but once it is created, it cannot be changed. This lecture introduces tuples, explains why such a restriction is useful and shows how to work with them.
You will create a tuple using parentheses and commas, such as a pair of coordinates or a date made of three numbers, and print it. You will learn the odd-looking syntax for a tuple with a single item, which needs a trailing comma, and see that the parentheses are optional, since it is the commas that make a tuple. Indexing, slicing, len, the in operator and looping all work just as they do for lists, which you will confirm.
Then you will try to change an item and read the TypeError that Python raises. This is the defining feature. A tuple is immutable. We discuss why that matters. Immutability protects data that should stay fixed, such as the days of the week or the fixed settings of a program, and makes the intent of the code clear to readers. Tuples can also be used as dictionary keys, which lists cannot.
We compare tuples and lists. Use a list for a collection that grows, shrinks or is reordered, and a tuple for a fixed record of related values. You will convert between them with the list and tuple functions, which is the way to produce a changed version of a tuple.
You will also see that a tuple can contain a list, whose contents can still change.
By the end of this lecture you will be able to create and use tuples and choose between a tuple and a list.
Unpacking Tuples. Python lets you take a tuple apart and assign its items to separate variables in a single line. This feature, called unpacking, makes code shorter and clearer, and this lecture explains how to use it.
You will begin with a tuple of three values and a line that assigns them to three variables at once. The number of names on the left must match the number of items on the right, and you will see the ValueError that appears when it does not. Reading the message teaches you to count the values.
We then use unpacking in practical ways. You will swap the values of two variables in a single line, which avoids the need for a temporary variable, and you will see how it works behind the scenes. You will unpack the pair of values returned by a function, such as a minimum and a maximum, which prepares you for the section on functions. You will also unpack inside a loop, for example when looping over a list of pairs, so that each name and score is assigned to its own variable.
Next you will meet the starred form, which collects the remaining items into a list. You can capture the first item and the rest, or the first and the last with everything in between collected together. We also discuss the underscore convention for values that you do not need.
You will use unpacking with enumerate and zip, which you met in the lecture on loops, to see why those tools produce tuples.
By the end of this lecture you will be able to unpack tuples into variables, including with starred names.
Creating Your First Dictionary. A list stores items by position, which is awkward when each item has a meaning, such as a name, an age and a city. A dictionary stores values under labels called keys, so that you can ask for exactly what you need by name. This lecture introduces the dictionary.
You will create one with curly braces, where each entry is a key, a colon and a value, separated by commas. You will make a dictionary that describes a person, with keys such as name, age and city, and print it. We explain the vocabulary: a key and its value together form a pair, keys are usually strings or numbers, and the pairs are stored in the order in which they were added.
You will compare the dictionary with a list. To find the age in a list, you need to remember that it is the second item, whereas in a dictionary, you ask for the key age. The code explains itself, which is a major advantage. We also show that values can be of any type, including lists and other dictionaries, and that a dictionary can describe things like a product, a book or a student.
You will create an empty dictionary and see how to build one with the dict function and keyword arguments. We also show how to create a dictionary from two lists using zip.
We mention that keys must be unique and unchangeable, so that a list cannot be a key, and that a repeated key keeps only its last value.
By the end of this lecture you will be able to create dictionaries and describe things using key and value pairs.
Looking Up Values by Key. The purpose of a dictionary is to find a value quickly using its key. This lecture shows the ways to look values up, and how to handle keys that are missing.
You will begin with square brackets. Writing the dictionary name followed by a key in brackets returns the value. You will look up several entries in a dictionary of capital cities or product prices and use the values in sentences and calculations. Looking up a key is fast, even in a very large dictionary, which is one of the reasons dictionaries are so widely used.
Next you will see what happens when the key does not exist. Python raises a KeyError, and we read the message, which shows the missing key. We then introduce the safer alternative, the get method, which returns None when the key is missing, or a default value that you supply. You will use it to display a friendly message such as unknown, and compare the two approaches, deciding when an error is actually desirable because it exposes a mistake.
We examine keys more closely. Keys are case sensitive, so name and Name are different, and a small typo causes a failed lookup. You will see how a consistent naming style helps.
You will also look up values in nested dictionaries by chaining brackets, for example the street of a person's address, and work with a dictionary whose values are lists.
You will build a simple translator that looks up a word and reports when it has no translation.
By the end of this lecture you will be able to retrieve values by key and handle missing keys safely.
Adding, Changing, and Removing Items. Dictionaries can be changed after they are created. You can add new pairs, update existing ones and delete those you no longer need. This lecture shows each operation.
Adding and changing use the same syntax. Assigning a value to a key, using square brackets, creates the pair if the key is new and replaces the value if the key already exists. You will start with a dictionary describing a product, add a new field, such as its stock level, and change the price, printing the dictionary after each step. We point out that this means a typo in a key silently creates a new entry instead of reporting an error, so careful spelling matters.
You will learn the update method, which merges another dictionary or a set of keyword arguments into the first, adding new keys and overwriting existing ones. It is convenient for applying several changes at once.
Removing comes next. The del statement deletes a pair by key, and pop removes it and returns its value, with an optional default that avoids an error when the key is absent. You will use pop to take an item out of a dictionary while using its value, and clear to empty the whole dictionary. We also mention popitem, which removes the most recently added pair.
You will build a small inventory program that adds products, changes quantities after a sale and removes items that are sold out.
We discuss copying. Assigning a dictionary to another name does not copy it, so a change through one name appears in the other, and the copy method creates an independent version.
By the end of this lecture you will be able to add, change and remove dictionary items.
Checking for Keys and Measuring Size. Before using a key, it is often wise to check whether it exists, and it is useful to know how many pairs a dictionary holds. This lecture covers both, and introduces the views that let you look at keys and values separately.
You will begin with the in operator, which checks whether a key is present. You will use it in an if statement to avoid a KeyError, and to decide whether to add a new entry or update an existing one. We stress that in checks keys, not values, so asking whether a value is present requires a different approach, and you will see how to do that by checking against the values.
Next you will use len to count the pairs, and see how it changes as you add and remove entries. An empty dictionary has a length of zero, and Python treats it as false in a condition, which is a convenient way to test for emptiness.
You will meet the three views: keys, values and items. Each gives you a window onto the dictionary, and you will print them, convert them to lists and use them in loops. We explain that the views update automatically if the dictionary changes. You will find the largest value in a dictionary of scores by using max on the values, and then find the key that belongs to it.
We discuss checking several keys at once, comparing the keys of two dictionaries and verifying that a record has all required fields before processing it.
By the end of this lecture you will be able to test for keys, measure dictionary size and use the keys, values and items views.
Looping Through a Dictionary. A dictionary often holds a collection of related facts, and you will want to go through all of them. This lecture shows the ways to loop through a dictionary and the best choice in each situation.
You will start with the default behavior. A for loop over a dictionary gives you its keys, and you can use each key to look up the value. You will print the contents of a dictionary of prices this way. Then you will use the items method, which gives each key and its value together as a pair, and unpack them in the loop header, which is shorter and clearer. This unpacking draws on what you learned about tuples.
We also loop over the values alone, when the keys do not matter, such as to add up a collection of prices or find the highest score. You will practice using the accumulator and filtering patterns with dictionaries: totaling the values, listing only the items that exceed a threshold and building a new dictionary containing only the matches.
You will see how to sort the output. The sorted function can put keys in alphabetical order, and you can sort by value by supplying a key function, so that you can display a ranking from highest to lowest. We use this to print a neatly formatted leaderboard with f-strings.
We discuss the rule that you should not add or remove keys while looping over a dictionary, because Python raises an error, and show the safe alternative of looping over a copy of the keys.
By the end of this lecture you will be able to loop through keys, values and pairs and produce sorted, formatted output.
Counting Items with a Dictionary. One of the most popular uses of a dictionary is counting how often things occur: how many times each word appears in a text, how many votes each candidate received or how many items of each kind are in an order. This lecture builds that pattern.
You will begin with a list of fruits that contains repeats. The plan is to create an empty dictionary, loop through the list and, for each item, add one to its count. The first time an item appears, it has no entry yet, so you need to handle that case. You will write it in two ways. The first checks with in whether the key exists and either creates it with a count of one or adds one to the existing count. The second uses the get method with a default of zero, which does both in one line and is a very common idiom.
You will apply the pattern to text. You will count the letters in a word, the words in a sentence after converting them to lowercase and removing punctuation, and the occurrences of each category in a list of orders. Then you will find the most common item by looping through the counts or by using max with a key.
We print the results as a tidy report, sorted from the most frequent to the least, using f-strings for alignment.
We also mention that the Counter class, which you will meet later in the course, does this job automatically, and that understanding the manual version helps you appreciate it.
By the end of this lecture you will be able to count items using a dictionary and report the results.
Sets: Collections of Unique Items. Sometimes you care about which items are present and not about their order or how often they appear. A set is a collection of unique values, and it is perfect for removing duplicates and for asking membership questions. This lecture introduces sets.
You will create a set with curly braces, listing values separated by commas, and notice that duplicates disappear automatically. You will convert a list with repeated items into a set to find its unique values, and measure the difference in length to see how many duplicates there were. We point out that an empty pair of curly braces creates an empty dictionary, so an empty set must be made with the set function.
We explain the properties. A set is unordered, so it has no positions and cannot be indexed or sliced, and the order in which it prints may differ from the order you wrote. Its items must be unchangeable, so a set can contain numbers, strings and tuples but not lists. You will see the error that appears when you try to put a list in a set.
Checking membership with in is extremely fast on a set, even for a large collection, which makes sets a good choice for lookups, such as testing whether a word appears in a list of banned words. You will build that example.
You will also loop over a set, sort it into a list for ordered display and use the length to count distinct items.
By the end of this lecture you will be able to create sets, remove duplicates and test membership.
Adding to Sets and Comparing Them. Sets can be changed, and they can be compared using operations borrowed from mathematics. This lecture shows how to add and remove items, and how to combine sets to answer useful questions.
You will begin with add, which inserts one item, and update, which adds many at once. You will see that adding an item that is already present has no effect. For removal, we compare remove, which raises an error when the item is missing, with discard, which does not, and pop, which removes an arbitrary item. We also show clear.
Next comes the heart of the lecture, the set operations. The union of two sets contains every item that is in either one. The intersection contains the items that are in both. The difference contains the items in the first set but not in the second, and the symmetric difference contains those in exactly one. You will try each with two small sets, such as the students enrolled in two courses, and read the result in plain language. We show both the operator form, using symbols, and the method form, using names, and discuss which reads better.
You will also test relationships with issubset, issuperset and isdisjoint, which answer whether one set is contained in another or whether they have nothing in common.
You will solve practical problems: finding the customers who bought both products, the items in stock that are missing from an order and the unique words that two texts share.
By the end of this lecture you will be able to modify sets and combine them using union, intersection and difference.
Functions are one of the most important ideas in programming. A function is a named block of code that you write once and run whenever you need it. Instead of copying the same lines again and again, you give those lines a name and call that name. This keeps your programs shorter, easier to read and much easier to fix when something goes wrong.
In this lecture you will meet the building blocks of a function and see how Python treats them. You will learn why functions exist and how they help you think about a problem in small pieces.
You will begin with the def keyword, which tells Python that you are creating a new function. Next you will choose a clear name, add a pair of parentheses and finish the line with a colon. You will then see why the indented lines underneath belong to the function and why the indentation matters so much in Python.
After that you will learn an important point that surprises many beginners: defining a function does not run it. The code inside only runs when you call the function by writing its name followed by parentheses. You will define a simple greeting function, call it once, then call it several times to see how reuse works.
You will also practise reading the output and tracing the order in which Python executes your lines, which is a habit that will help you in every later lesson.
By the end of this lecture you will be able to define a basic function with def, call it by name, explain the difference between defining and calling, and use functions to avoid repeating code.
A function becomes far more useful when it can work with information that you give it. Without inputs, a function does the same thing every time. With inputs, one function can handle many different situations. In Python, those inputs are called parameters, and they are the focus of this lecture.
You will begin with the simple greeting function from the previous lesson and notice its limitation: it can only greet one fixed name. You will then add a parameter inside the parentheses of the definition so that the function can greet anyone you choose.
Next you will learn the difference between a parameter and an argument. A parameter is the placeholder name written in the definition, and an argument is the real value you pass in when you call the function. Keeping these two words straight will make documentation and error messages much easier to understand.
You will call the function with different arguments, such as several names and a few text values, and watch how the same code produces different results. You will also see what happens when you forget to pass an argument, and you will read the error message that Python shows so that it feels familiar rather than scary.
Finally you will practise choosing good parameter names that describe what the value means, which makes your functions readable to other people and to your future self.
By the end of this lecture you will be able to add a parameter to a function, pass an argument when calling it, tell parameters and arguments apart, and read the error for a missing argument.
Many real tasks need more than one piece of information. A function that calculates a total price needs a price and a quantity. A function that builds a full name needs a first name and a last name. In this lecture you will learn how to give a function several parameters and how Python matches your arguments to them.
You will start by separating parameters with commas inside the parentheses of the definition. Then you will write a function that uses two values together, such as multiplying a price by a quantity and printing the result. You will call it and see how each argument lands in the matching parameter.
An important idea here is position. When you pass arguments in the usual way, Python matches the first argument to the first parameter, the second to the second, and so on. You will see how swapping the order changes the result and why this can cause quiet mistakes even when the program runs without errors.
You will also see what happens when you pass too few or too many arguments, and you will read the resulting message so you can quickly diagnose the problem in your own code.
To finish, you will build a small function with three parameters and test it with several sets of values, checking that the output matches what you expect by working through the arithmetic by hand.
By the end of this lecture you will be able to write functions with several parameters, understand positional matching, and spot the common mistakes caused by wrong argument counts or order.
So far your functions have printed their results to the screen. Printing is useful for showing information to a person, but it does not let the rest of your program use the answer. To pass a result back to the code that called the function, you use the return statement, and that is the topic of this lecture.
You will begin by writing a function that adds two numbers and prints the total. Then you will rewrite it so that it returns the total instead. You will call the new version and store the answer in a variable, which shows how a function can feed its output into other parts of your program.
You will learn that return does two things at once: it sends a value back to the caller and it immediately ends the function. You will see this by placing a line after the return statement and confirming that it never runs. This helps you understand the flow of execution inside a function.
You will also discover what a function gives back when it has no return statement at all. Python quietly returns a special value called None, and you will see why that explains some confusing results that beginners meet when they try to use the output of a function that only prints.
Along the way you will combine returned values inside larger expressions, such as using one function's answer as the argument to another.
By the end of this lecture you will be able to use return to send values back, store and reuse returned results, and explain what None means.
Two of the most commonly confused ideas in beginner Python are printing a value and returning a value. They can look identical when you run a small script, yet they behave very differently inside a larger program. This lecture compares them side by side so that the difference becomes clear and lasting.
You will begin with two tiny functions that appear to do the same job. One prints a result, and the other returns it. When you simply call each one on its own line, the screen output looks the same, which is exactly why the confusion starts.
Then you will try to use each function inside a calculation, such as adding ten to its answer. With the returning version the calculation works. With the printing version you will see an error or an unexpected None, and you will understand why. This experiment is the heart of the lesson.
You will also learn a simple rule of thumb: print is for showing information to a person, while return is for handing information to other code. Most well designed functions return values and let the caller decide whether to print them.
To finish, you will refactor a small function that mixes both behaviours into a cleaner version that returns its answer, and you will print the answer outside the function.
By the end of this lecture you will be able to explain the difference between print and return, choose the right one for a given job, and fix functions that print when they should return.
Sometimes a parameter has a value that is right most of the time, and forcing the caller to provide it every time becomes tedious. Python lets you set a default value for a parameter so that the argument becomes optional. In this lecture you will learn how defaults work and when they make your functions friendlier.
You will start with a greeting function that takes a name and a greeting word. Then you will give the greeting word a default of hello by writing an equals sign and a value in the definition. You will call the function with and without the second argument and compare the results.
You will learn the rule that parameters with defaults must come after parameters without defaults, and you will see the error Python gives if you break it. Understanding this rule helps you design function signatures that are both flexible and valid.
Next you will explore how a caller can override a default by supplying their own value, and why this makes a function easy to use in simple cases while still allowing customisation. You will practise with a function that calculates a price with an optional tax rate.
You will also touch on good judgement: defaults should be sensible, simple values such as numbers, text or True and False, so that the behaviour of the function is easy to predict.
By the end of this lecture you will be able to give parameters default values, call functions with optional arguments, follow the ordering rule for defaults, and design more convenient functions.
When a function has several parameters, remembering their order can be hard, and a call with many plain values can be difficult to read. Keyword arguments solve this by letting you name each value at the moment you call the function. This lecture shows you how to use them to write clearer, safer code.
You will begin with a function that takes three parameters, such as a name, an age and a city. First you will call it with positional arguments and notice how easy it is to mix up the order without realising. Then you will call it again using the parameter names, written as name equals value, and see how the meaning of each value becomes obvious.
You will learn that keyword arguments can appear in any order, because Python matches them by name rather than by position. You will test this by shuffling the order and confirming that the output stays the same.
You will also see how to combine both styles in one call. The rule is that positional arguments come first, followed by keyword arguments, and you will read the error message that appears when you reverse them.
Finally you will combine keyword arguments with default values from the previous lesson to build a function that is easy to call in short form but still lets you adjust individual options by name.
By the end of this lecture you will be able to call functions with keyword arguments, mix them with positional arguments correctly, and use names to make calls easier to read and less error prone.
Many problems have more than one answer. A function that analyses a list of numbers might need to report the smallest value, the largest value and the average. You might think a function can only return one thing, but Python offers a neat way to send back several values at once. This lecture explains how.
You will start by writing a function that calculates two results, such as the sum and the average of a few numbers. Then you will return both of them separated by a comma. You will learn that Python quietly packs these values together into a single tuple, which you already met when studying lists and tuples.
Next you will see how to receive the results. You will assign the returned values to several variables in one line, a technique called unpacking, and you will confirm that each variable holds the correct piece. You will also look at what happens if you store the whole result in a single variable and index into it.
You will practise with a function that takes a list of numbers and returns the minimum, maximum and count, then print each piece with a descriptive label. You will also learn what error appears when the number of variables does not match the number of returned values.
This technique is common in real programs, and learning it now will help you read code written by other people.
By the end of this lecture you will be able to return several values from one function, unpack them into separate variables, and avoid mismatch errors.
Not every variable in a program can be seen from every place. Python has rules about where a name is available, and these rules are called scope. In this lecture you will learn about local variables, the names created inside a function, and why they behave differently from the variables you create at the top of a script.
You will begin with a function that creates a variable inside its body. You will print that variable from within the function and see that it works. Then you will try to print the same name outside the function and watch Python raise a NameError. This simple experiment shows that local variables live only while the function runs.
You will learn why this design is helpful. Because each function has its own private workspace, two functions can use the same variable name without interfering with each other, and you can change one function without worrying that it will break another.
You will also see how parameters count as local variables, and how a function can read a variable defined outside it, while a new variable with the same name created inside simply hides the outer one for the duration of the call.
To reinforce the idea you will trace a short program by hand, writing down which names exist at each step, a skill that makes debugging much easier.
By the end of this lecture you will be able to explain local scope, predict when a NameError will occur, and keep function variables separate from the rest of your program.
In the previous lesson you saw that variables created inside a function stay inside it. Sometimes, though, a value needs to be shared across the whole program, such as a settings value or a running total. Python handles this with global variables, and this lecture shows how they work together with functions.
You will begin by defining a variable at the top level of a script and reading it from inside a function. You will see that reading a global value just works. Then you will try to change it from inside a function and discover that Python creates a new local variable instead, leaving the original untouched. This surprising result is a classic source of beginner bugs, and you will learn exactly why it happens.
To change a global value on purpose, you will use the global keyword, which tells Python that a name inside the function refers to the outer variable. You will build a small counter function that updates a global total each time it is called.
You will also reflect on good practice. Heavy use of global variables can make a program hard to follow, because any function might change them. You will compare the global approach with a cleaner one that passes values in as arguments and returns the updated value.
By the end of this lecture you will be able to read and modify global variables safely, explain why assignment inside a function creates a local name, and choose between globals and parameters with return values.
Programs become much more useful when they can remember things after they stop running. Files are how that happens. In this lecture you will take your first step into file handling by learning how to create a text file and write information into it using Python.
You will start with the built-in open function, which connects your program to a file on disk. You will learn the meaning of the mode argument and use write mode, written as w, to create a new file. You will then call the write method to place a line of text inside it and close the file so that the data is safely stored.
You will see that write does not add a new line automatically, so you will practise adding the newline character yourself to put several lines in the file. You will also learn an important warning: opening an existing file in write mode erases its previous contents, so you should choose file names with care and use a practice folder for your experiments.
After running your script you will open the new file in a normal text editor to confirm that Python really created it. This step makes the idea concrete and helps you check your work.
You will finish by writing a small shopping list from a Python list, one item per line, using a loop.
By the end of this lecture you will be able to open a file for writing, write several lines of text, close the file, and explain what write mode does to existing content.
Once you can write information into a file, the next step is getting it back. Reading is the other half of file handling, and Python makes the simplest case very easy. In this lecture you will open a text file and read its entire contents into a single string.
You will begin with the file you created in the previous lesson. You will open it in read mode, written as r, and call the read method. The whole file arrives as one piece of text, which you will store in a variable and print. You will see how the newline characters inside the text are displayed when the string is printed normally.
You will then work with the text you have read. For example, you will use string methods that you already know to count the characters, convert the text to uppercase and split it into a list of lines. This shows how file reading connects to everything you have learned about strings and lists.
You will also learn why closing a file matters and what happens if you forget. Then you will see the common error that appears when you try to read from a file opened for writing, and how the mode controls what you are allowed to do.
To finish, you will think about when reading a whole file at once is a good idea, and when a very large file might make that approach impractical.
By the end of this lecture you will be able to open a file for reading, load its contents into a string, and process the text with the string tools you already know.
Reading an entire file at once is simple, but it is not always the best choice. Often you want to handle one line at a time, for example to process each record in a list or to look for a particular word. In this lecture you will learn how to read a file line by line.
You will begin by seeing that a file object can be used directly in a for loop. Each pass through the loop gives you the next line, so you can print it, count it or test it. You will use this to display a numbered list of the lines in your practice file.
You will notice that each line ends with a newline character, which causes extra blank lines when you print it. You will learn to remove it with the strip method, a small trick that you will use again and again when working with text files.
Next you will compare this approach with the readlines method, which returns all the lines as a list. You will discuss when each option is suitable. Looping is gentle on memory because it handles one line at a time, while a list lets you jump around and use indexes.
You will practise by searching a file for lines that contain a chosen word and counting how many matches you find.
By the end of this lecture you will be able to loop over a file, clean up line endings with strip, use readlines when you need a list, and filter lines using conditions.
This lecture covers two ideas that make your file code safer and more professional: appending to a file without erasing it, and the with statement, which looks after closing the file for you.
You will begin with append mode, written as a. Unlike write mode, which wipes the file, append mode keeps the existing content and adds new text at the end. You will add several new lines to your practice file and read it back to confirm that the old lines are still there. This is the right tool for things like logs, where you keep adding entries over time.
Next you will look at a weakness in the earlier approach. If your program has a problem between opening and closing a file, the close call might never happen, and the file could remain locked or incompletely saved. The with statement solves this by closing the file automatically as soon as its indented block finishes, even if something goes wrong inside it.
You will rewrite your earlier write, read and append examples using with and see how much tidier and safer they become. You will learn the meaning of the as keyword that gives the file a name inside the block.
You will also compare the different modes in a short table so you can choose the correct one quickly.
By the end of this lecture you will be able to append text to an existing file, use the with statement for automatic closing, and pick the right file mode for each task.
Real programs run into problems. A file might not exist, a name might be mistyped or a folder might have moved. Without protection, Python stops the program with an error message. In this lecture you will learn how to handle one of the most common problems, a missing file, using try and except.
You will begin by deliberately opening a file that does not exist and reading the FileNotFoundError that Python raises. Seeing the error first helps you understand exactly what you are trying to catch, and how to read the traceback that explains where the problem happened.
Next you will wrap the risky code inside a try block and add an except block that names the error. When the file is missing, your program no longer crashes. Instead it prints a friendly message and carries on. You will learn how the flow of control jumps from the try block straight to the matching except block when something goes wrong.
You will then improve the design by asking the user for a file name, trying to open it and offering a helpful message when the name is wrong. You will also learn why catching a specific error is better than catching everything, because a broad handler can hide real mistakes.
To finish, you will add an else block that runs only when no error occurred.
By the end of this lecture you will be able to use try and except to handle a missing file, read an error type from a traceback, and write programs that fail gracefully.
Another common source of errors is text that cannot be turned into a number. When a program asks a person to type a number, they might enter letters, leave the answer blank or add stray symbols. If you pass that text to int or float, Python raises a ValueError. In this lecture you will learn how to catch that error and respond sensibly.
You will begin by writing a short script that asks for an age and converts the answer with int. You will run it with a valid number and then with something invalid, and read the ValueError message so that it becomes familiar.
Next you will place the conversion inside a try block and add an except ValueError block that prints a clear message. You will then combine this with a while loop so that the program keeps asking until the person gives a valid number. This pattern is called input validation, and it is used in almost every interactive program.
You will also practise handling more than one kind of error. For instance, you will convert a list of text values into numbers, skip the ones that fail and report how many were rejected.
You will see why a good error message tells the user what went wrong and what to do next.
By the end of this lecture you will be able to catch a ValueError, validate user input with a retry loop, and write messages that guide people toward a correct answer.
Comma separated values, usually called CSV, are one of the most common formats for storing tables of data. Spreadsheets, exports from other tools and simple data sets are often saved this way. In this lecture you will learn how to write a CSV file using Python's built-in csv module.
You will begin by looking at what a CSV file actually is: plain text where each line is a row and commas separate the columns. You will see why writing this by hand with string joining can go wrong, for instance when a value itself contains a comma, and why a dedicated module is a better choice.
Next you will import the csv module and create a writer object attached to an open file. You will use the writerow method to add a header row and then several data rows, such as names, scores and cities. You will learn the importance of opening the file with newline set to an empty string so that you do not get blank lines between rows on some systems.
You will also discover writerows, which writes a list of rows in a single call, and you will use it with a list of lists built in your own code.
Finally you will open the finished file in a text editor and a spreadsheet program to confirm that it looks right.
By the end of this lecture you will be able to create a CSV file, write header and data rows, use writerow and writerows, and check your result.
After creating a CSV file, you will want to read it back and work with the data. The csv module makes this straightforward, and in this lecture you will learn how to load rows from a file and use them in your programs.
You will begin by opening the file you wrote in the previous lesson and creating a reader object. You will loop over the reader and print each row, and you will see that every row arrives as a list of strings. You will use list indexes to pick out particular columns, such as a name or a score.
You will notice that numbers read from a CSV file are still text, so you will convert them with int or float before doing any arithmetic. This is a common stumbling block, and handling it early will save you confusion later. You will calculate a total and an average from a column of scores to see it in action.
Next you will meet DictReader, which uses the header row to give each value a name. Instead of remembering that the score is in column two, you can write row with the key score. You will compare the two approaches and see why dictionaries make the code easier to read.
You will also skip the header row correctly when you use the plain reader.
By the end of this lecture you will be able to read CSV files with reader and DictReader, convert text values into numbers, and compute simple summaries from the data.
Real data is rarely perfect. A CSV file might contain a blank score, a word where a number should be or a row with missing columns. If your program assumes that every row is valid, a single bad line can stop the whole run. In this lecture you will combine your file, CSV and error handling skills to process messy data safely.
You will begin with a small sample file that deliberately includes a few bad rows. You will run a simple reading script and see it fail with a ValueError, which shows why defensive code matters.
Next you will wrap the conversion step for each row in a try block and use except ValueError to skip the row that caused the problem. You will keep a counter of rows that were skipped and a list of the good values, so that the final report is accurate.
You will then show the error to the user in a helpful way. Instead of silently ignoring bad rows, you will print the line number and the reason it was rejected, which makes it easy for someone to fix the source file. You will use the enumerate function to track line numbers.
To finish, you will print a short summary with the number of valid rows, the number of rejected rows and the average of the valid scores.
By the end of this lecture you will be able to skip invalid CSV rows, report errors clearly with line numbers, and produce reliable results from imperfect data.
Python comes with a large collection of ready-made tools called the standard library, and one of the most useful for numbers is the math module. Instead of writing your own code for square roots or rounding, you can import the module and use well tested functions. In this lecture you will learn how importing works and how to use math in your programs.
You will begin with the import statement and see what it does: it loads a module so that its contents become available under the module name. You will then use dot notation, such as math followed by a dot and a function name, to reach the tools inside.
Next you will try several common functions. You will calculate a square root with sqrt, round numbers up with ceil and down with floor, and raise values to a power with pow. You will compare floor and ceil on positive and negative numbers so that the difference is clear. You will also use constants such as pi to calculate the area of a circle.
You will learn how to explore a module with the dir and help functions, which let you discover what else is available without leaving Python. This habit will serve you well whenever you meet a new module.
You will also see the error that appears when you forget the import line.
By the end of this lecture you will be able to import a module, call its functions with dot notation, use math constants, and explore unfamiliar modules on your own.
Importing a whole module is not the only option. Sometimes you only need one or two tools, and typing the module name each time becomes tiring. Python offers other import styles that make code shorter and, used carefully, clearer. In this lecture you will learn how to import specific names and how to give modules and names aliases.
You will begin with the from keyword and import only the function you need, for example sqrt from the math module. You will then call it directly without the module prefix, and you will see how this shortens your lines. You will also import several names in one statement by separating them with commas.
Next you will learn about aliases using the as keyword. You will give a module a shorter name, which is a common habit in the Python community, and you will give a function a new name when the original is too long or might clash with another name in your program.
You will also consider the trade-offs. Importing everything with a star can fill your program with names you did not choose and make it hard to see where a function came from, so you will see why it is usually avoided. Explicit imports make code easier to read and maintain.
To finish, you will compare three versions of the same small program and decide which style communicates best.
By the end of this lecture you will be able to use from imports, create aliases with as, and choose import styles that keep your code clear.
Dates and times appear in almost every real application, from logging events to calculating ages or deadlines. Working with them by hand is tricky, so Python provides the datetime module. In this lecture you will learn how to get the current date and time, create specific dates and do simple arithmetic with them.
You will begin by importing the datetime class and calling now to capture the current moment. You will print it and see its default format, then read individual parts such as the year, month, day, hour and minute using attributes.
Next you will create a date of your own by passing the year, month and day. You will learn why it is better to use real date objects than plain text, because they know how many days each month has and can be compared and sorted correctly.
You will then meet timedelta, which represents a length of time. You will add seven days to a date to find next week, subtract two dates to count the days between them and compare dates to see which is earlier. This is the foundation for things like countdowns and due dates.
Finally you will format dates for display with strftime, using codes for the day, month name and year, and you will practise producing a few common layouts.
By the end of this lecture you will be able to read the current date and time, build dates, calculate differences with timedelta, and format dates for people to read.
Counting how often something appears is one of the most common tasks in programming. You might count words in a text, votes in a poll or letters in a name. You already know how to do this with a dictionary and a loop, but Python offers a faster tool in the collections module called Counter. In this lecture you will learn how to use it.
You will begin by writing the traditional dictionary approach so you can see how many lines it needs, including the check for whether a key already exists. Then you will replace all of it with a single call to Counter on a list or a string, and compare the two versions.
You will explore what a Counter gives you. It behaves like a dictionary where each key is an item and each value is its count. You will look up individual counts, notice that missing items return zero rather than an error and loop through the results.
Next you will use the most_common method to list the items that appear most often, which is perfect for finding the top words in a sentence. You will practise by splitting a short paragraph into words, converting to lowercase and counting them.
You will also see how to update a Counter with more data and combine counts from different sources.
By the end of this lecture you will be able to import Counter, count items in lists and strings, and find the most common values quickly.
Programs often need to exchange data with other programs, save structured information or read settings. A very popular format for this is JSON, which looks a lot like Python dictionaries and lists. Python's json module converts between your data and JSON text, and in this lecture you will learn the basics.
You will begin by looking at a small piece of JSON and noticing how closely it resembles a dictionary, with keys, values, lists and nested structures. You will also learn the small differences, such as JSON using true and false in lowercase and null instead of None.
Next you will use dumps to turn a Python dictionary into a JSON string. You will add the indent option to make the output easy to read, and you will print it. Then you will go the other way with loads, which turns JSON text back into a dictionary that you can search and update.
You will also practise with files. You will use dump to save a dictionary to a file and load to read it back, which gives your programs a simple way to remember information between runs.
You will learn what happens when the text is not valid JSON and how a try and except block can handle the resulting error.
By the end of this lecture you will be able to convert Python data to JSON and back, save and load JSON files, and handle invalid JSON safely.
Python's standard library is large, but it is only the beginning. Thousands of extra packages are shared by the community, and pip is the tool that installs them. In this lecture you will learn what packages are, where they come from and how to install and use one in a safe way.
You will begin with the idea of a package index, an online catalogue where developers publish their work, and with pip, the command line program that downloads packages from it. You will learn how to open a terminal, check that pip is available and read its version.
Next you will install a small, well known package with the pip install command and watch what the output tells you. You will then import the package in a Python script and use one of its simple features to confirm that it works. You will learn how to list installed packages with pip list and how to remove one with pip uninstall.
You will also learn good habits. You should choose packages that are widely used and well documented, read the project page before installing and install into a virtual environment so that your experiments stay separate from the rest of your computer. You will see how to create and activate one.
To finish, you will save the installed package names into a requirements file so that your setup can be repeated.
By the end of this lecture you will be able to install and remove packages with pip, use them in scripts and keep projects tidy with virtual environments.
As programs grow, keeping all of the code in one file becomes hard to manage. Python lets you split your code into several files, called modules, and import them just like the built-in ones. In this lecture you will learn how to organise your own code into separate modules.
You will begin by creating a small file that contains a few useful functions, such as ones that calculate an average or format a price. You will save it in the same folder as your main script and give it a clear name. Then you will import it into the main script and call its functions with dot notation.
You will see that every Python file is already a module, and that the file name without the extension becomes the module name. You will also learn why the location of the file matters, and what error appears if Python cannot find it.
Next you will meet the special name check, written as if name equals main. You will learn that it lets a file behave differently when it is run directly and when it is imported, so you can add test code without it running unexpectedly in other programs.
You will also discuss good organisation: grouping related functions together, using descriptive file names and keeping each module focused on one job.
By the end of this lecture you will be able to create your own modules, import them into other files, use the main check and structure larger programs in a clean way.
This course contains the use of artificial intelligence.
Are you ready to learn Python programming from scratch and build a strong foundation in one of the world's most popular programming languages? Whether you are a complete beginner, an aspiring software developer, or a professional looking to upgrade your technical skills, this Complete Python Bootcamp provides a structured, step-by-step learning experience to help you become a confident Python programmer.
This comprehensive Python course for beginners features 100 hands-on coding lessons across 12 carefully designed modules. You will progress from writing your first Python program to developing a complete real-world Python application. No previous programming experience is required.
What Will You Learn?
Start with Python fundamentals, including installing Python, configuring your development environment, writing Python scripts, printing output, performing mathematical operations, and understanding common programming errors.
Explore Python variables, data types, operators, integers, floating-point numbers, strings, and type conversion. Learn how to store, manipulate, and process information using essential programming techniques.
Develop your Python string manipulation skills through string indexing, slicing, string methods, text processing, string formatting, and f-strings.
Master Python control flow using Boolean expressions, comparison operators, conditional statements, logical operators, and nested decision-making structures. Learn to automate repetitive tasks using for loops, while loops, nested loops, break, and continue statements.
Build a solid understanding of Python data structures, including lists, tuples, dictionaries, and sets. Discover how to organize, access, modify, sort, and process collections of data efficiently.
Learn Python functions, parameters, arguments, return values, variable scope, and reusable programming techniques to create cleaner and more maintainable code.
Explore Python file handling, reading and writing text files, processing CSV files, exception handling, error management, and data persistence.
Work with the Python Standard Library, including math, datetime, collections, and JSON. Understand Python modules, package installation with pip, imports, and modular application development.
Develop essential Object-Oriented Programming (OOP) skills by working with Python classes, objects, constructors, instance attributes, methods, inheritance, method overriding, and special methods.
Learn Python Through Hands-On Coding
This course emphasizes practical Python programming rather than theoretical explanations alone. Each lesson includes a guided coding walkthrough designed to help you understand how Python works through practical examples.
You will develop essential skills in:
Python programming and scripting
Coding fundamentals and problem-solving
Data structures and data manipulation
Python automation and file processing
Object-oriented software development
Debugging and exception handling
JSON and CSV data processing
Python testing and modular programming
Build a Real-World Python Project
Put your knowledge into practice by developing a complete Python Task Tracker application. You will design functions, manage tasks, store and retrieve data using JSON files, implement custom error handling, test functionality using assertions, and generate formatted reports.
Who Should Take This Course?
This course is ideal for absolute beginners, students, aspiring Python developers, software engineers, IT professionals, career changers, and anyone interested in building programming skills for Artificial Intelligence (AI), Machine Learning (ML), Data Science, Data Analytics, Web Development, and Automation.
While these specialized fields are not directly taught in this course, the Python fundamentals you acquire will provide a valuable foundation for pursuing them.
Start your Python programming journey today, build practical coding skills, strengthen your problem-solving abilities, and take your first step toward becoming a confident Python developer.