
This course includes our updated coding exercises so you can practice your skills as you learn.
See a demo
This lecture introduces the fundamental purpose of programming: to instruct computers to solve problems by writing sequences of instructions for hardware resources such as the CPU, memory, and disk. The course begins with a practical text analysis task, counting the most common word in a text file, to demonstrate how programming can automate problem-solving.
It emphasizes the contrast between human error correction and computer literal processing, where precise instructions are essential. The course teaches Python programming to enable users to create programs that solve their own problems, starting with simple text analysis tasks.
This lecture covers the fundamental hardware components: central processing unit (CPU), main memory, and secondary storage. Main memory is volatile and loses data when powered off, while secondary storage provides persistent data storage.
The lecture contrasts hardware from the 1960s and 1970s with modern systems such as the Raspberry Pi. It details the evolution of secondary storage from magnetic hard drives to flash memory and explains how high-level programming languages like Python translate code into machine language.
Python was created by Guido Van Rossum approximately 20 years ago and named after Monty Python's Flying Circus, not Harry Potter. The language was designed to be both powerful and easy to learn, balancing simplicity with functionality.
The lecture explains that syntax errors are common in Python and not a reflection of the programmer's worth but rather the computer's attempt to understand the code. The interactive shell, accessed by running the python command in the terminal, allows users to test basic syntax such as variable assignments and print statements.
This lecture covers the introductory concepts of Python programming, including reserved words, assignment statements, and print statements. It explains that a Python program consists of sequential lines of code that execute in order.
The lecture demonstrates how to combine sequential execution, conditional statements, and repeated steps to create a program that counts word frequencies in a file. These fundamental concepts form the basis for more complex programs and are expanded upon in subsequent chapters.
This lecture covers the foundational building blocks of Python: constants, reserved words, and variables. Constants are fixed values that do not change during execution, such as numbers (e.g., 123) and strings (e.g., "hello"). Reserved words are special keywords with predefined meanings in Python, like if and print.
Variables are named memory locations that store data and can be reassigned. Variable names must start with a letter or underscore, followed by letters, numbers, or underscores, and are case-sensitive. The lecture emphasizes the importance of descriptive variable names for code clarity, as Python does not interpret variable names beyond their context.
The lecture covers Python expressions and operators, including arithmetic operators such as addition (+), subtraction (-), multiplication (*), division (/), exponentiation (**), and modulo (%). It explains operator precedence, which dictates the order of evaluation: parentheses first, followed by exponentiation, then multiplication and division (left to right), and finally addition.
The lecture also discusses data types (integers, floating-point numbers, and strings) and type conversion using built-in functions like int and float. It demonstrates the type function for checking data types and introduces input and output operations with input and print, including a simple elevator floor conversion program.
This lecture covers exercise 2.2 from the Python for Everybody course, where the student writes a program that prompts for a user's name using the input function and prints a greeting.
The instructor demonstrates terminal navigation commands such as cd, ls, and pwd, and shows how to save Python files with the .py extension for syntax highlighting and execution.
This lecture demonstrates the process of running Python exercise 2.3 in the terminal. It covers creating a directory structure, writing a script that prompts for hours and rate inputs, and attempting to multiply these values without type conversion.
The script initially fails with a type error due to string multiplication. Converting the inputs to floats resolves the error and enables correct pay calculation.
This lecture introduces Python's if statement, a fundamental construct for conditional execution. The if statement evaluates a boolean condition using comparison operators such as ‹, ‹=, ==, ›, ›=, and !=. If the condition is true, the indented block of code executes; otherwise, it is skipped.
Proper indentation is essential in Python to define the scope of conditional blocks. The lecture covers the else clause for two-branch conditions and demonstrates nested conditionals, where an if statement can be contained within another. Correct indentation ensures that the code structure is unambiguous, as Python relies on indentation rather than braces for block delimitation.
The lecture explains Python's multi-way conditional statements using if-elif-else structures. Conditions are evaluated in order, and only the first true condition executes its block. The absence of an else clause may result in no conditions running.
The lecture introduces Python's try-except mechanism for exception handling. Code that might raise exceptions is wrapped in a try block, and an except block executes when an exception occurs, preventing program crashes and enabling recovery.
This lecture demonstrates a Python exercise that calculates employee pay with overtime. The program reads user input for hours and rate, converts them to floating-point numbers, and uses a conditional statement to compute pay for hours exceeding 40 at one and a half times the hourly rate.
The example shows that 10 hours at $10 per hour results in $100, and 50 hours at $10 per hour results in $550. The lecture highlights debugging challenges such as variable naming errors and the importance of removing extra print statements to pass autograder tests.
This lecture covers Python Exercise 3.2, which enhances error handling from Exercise 3.1 by using try and except blocks to manage conversion errors when converting user input strings to floating-point numbers.
When non-numeric input is provided, such as the string 'TEN', the program crashes without error handling. The solution wraps the conversion code in a try block and includes an except block that prints an error message and quits the program to prevent further execution.
Functions in Python allow code to be stored for reuse to avoid repetition. The `def` keyword creates a named block of code that is not executed during definition, completing the store phase.
Invoking a function executes the stored code, enabling reuse across multiple program sections. The lecture demonstrates built-in functions such as print, max, min, int, and float that return values for further use in expressions.
Python functions are defined using the def keyword, which creates a reusable code block with a name, parameters, and an indented body. The function definition does not execute the code but stores it for later use.
Function invocation requires passing arguments to defined parameters. Return statements provide values to the caller, as illustrated by a language translation function that returns greetings in different languages based on the input parameter.
This lecture demonstrates refactoring an overtime pay calculation exercise from Python programming into a function. The instructor shows how to move the pay computation logic into a function named compute_pay, which takes hours and rate as parameters. The function handles overtime (time and a half for hours over 40) and returns the calculated pay.
The lecture includes step-by-step examples of function definition, parameter passing, and return value usage. It emphasizes the critical need to save the file after each change to avoid runtime errors and the use of print statements for debugging. The implementation correctly calculates pay for 40 hours at $10 per hour and 55 hours at $10 per hour.
The lecture introduces while loops as a mechanism for iterative execution in programming. It details the structure of a while loop, which evaluates a condition, executes a block of code if true, and repeats until the condition becomes false. The example demonstrates a countdown loop using an iteration variable that starts at five and decrements by one each iteration.
The lecture covers loop control statements including break for exiting a loop immediately and continue for skipping the current iteration. It also explains infinite loops, which occur when the loop condition remains true indefinitely, and emphasizes the need for termination conditions to prevent resource exhaustion.
Python for loops iterate through predefined collections like lists, strings, or file lines. The loop automatically manages an iteration variable that takes successive values from the input set, ensuring a finite number of iterations without manual counter handling required in while loops.
The for loop executes a block of code once per element in the collection, assigning the iteration variable to each value sequentially. This approach eliminates the need for separate initialization, condition checks, and increment steps seen in while loop implementations.
The lecture describes loop idioms as reusable patterns for constructing loops to solve specific problems. These patterns typically involve initializing a variable before the loop, updating it during each iteration, and using the final value after the loop completes. The example focuses on finding the largest number in a sequence of integers.
The lecture demonstrates this pattern with the list [9, 41, 12, 3, 74, 15]. A variable named largest so far starts at -1 and is updated to the current number if it is greater than the stored value. After processing all numbers, the variable holds the largest value of 74.
The lecture explains how to implement counting and running totals within loops. It describes initializing a counter variable to zero at the start, incrementing it for each loop iteration, and using it to count the number of executions. It also demonstrates calculating a running total by accumulating values and then computing the average by dividing the total by the count.
The lecture covers boolean variables for value presence checks and techniques for finding the maximum and minimum values in a list. It explains initializing variables with none to handle the first value and using the is operator for identity comparisons.
This lecture demonstrates a worked example from Python for Everybody, Exercise 5.1. The program repeatedly prompts the user for a number until the user enters the word 'done', then prints the total, count, and average of the valid numbers.
The implementation uses an infinite loop with try/except blocks for input validation. It employs an accumulator pattern to maintain the running total and count, breaks when the input is 'done', and skips invalid inputs using the continue statement.
This lecture covers core string operations in Python, including zero-based indexing where each character position starts at index zero. It explains how the len() function returns string length without including the position, and demonstrates basic string manipulation like concatenation and type conversion for input data. The session emphasizes practical string handling techniques used in program development.
The lecture compares while loops and for loops for iterating through strings, highlighting the efficiency and elegance of Python's for loops for character-by-character processing. It provides a concrete example counting 'a' characters in the string "banana" using a loop with conditional checks, illustrating how these techniques enable data extraction and analysis within strings.
This lecture covers string slicing in Python, where substrings are extracted using start and end indices with the colon notation. The end index is exclusive, meaning it does not include the specified character. It also explains string concatenation with the + operator, which does not add spaces automatically, and the in operator for membership testing.
The session details built-in string methods such as lower, upper, replace, and strip for handling white space. It demonstrates extracting email domains through slicing and notes Unicode support in Python 3 as a key improvement for international character sets.
his lecture demonstrates the solution to exercise 6.5 from the Python for Everybody textbook, focusing on string parsing to extract a floating point number. The approach involves using the find method to locate the colon character, then slicing the string from the next character to the end to obtain the numeric string, which is converted to a float.
The techniques taught in this exercise are foundational for processing data from external sources such as files and the internet, which will be covered in subsequent chapters of the course.
This lecture covers the basics of reading files in Python, starting with the open function to create a file handle. The function takes a required file name and an optional mode, returning a handle distinct from the file data.
The lecture explains the newline character (\n), a single character that denotes the end of a line in files. It also covers encoding, noting that UTF-8 is the most common character set and missing files cause tracebacks.
This lecture explains the common method of reading text files in Python using a for loop to iterate over lines. It introduces the concept of a file handle and demonstrates counting lines by initializing a counter and incrementing it for each line processed.
The lecture also covers reading the entire file as a string and stripping newline characters using the rstrip method. It demonstrates handling file errors with try/except blocks and using the quit statement to terminate the program gracefully.
This lecture demonstrates a Python 3 program that reads a text file and converts each line to uppercase. It covers the basics of file handling, including opening a file with the open function, iterating over lines using a for loop, and stripping newline characters with the strip method.
The exercise processes the mbox-short.txt file to output each line in uppercase without trailing newlines. This example illustrates common file manipulation techniques in Python.
Lists are a data structure in Python for storing ordered collections of items. They are mutable, meaning their contents can be changed after creation, and use zero-based indexing starting at index 0.
The len function returns the number of items in a list, and the range function generates sequences of integers for loop iterations. Lists are iterated using for loops, and their mutable nature differs from strings which cannot be altered after creation.
Python list concatenation uses the + operator to merge two lists, and list slicing employs zero-based indexing with an exclusive end index.
The lecture covers common list methods including append, count, extend, index, pop, remove, reverse, and sort, as well as built-in functions such as len, max, min, and sum.
The split function in Python converts a string into a list of substrings using a specified delimiter. By default, it splits on whitespace and treats consecutive whitespace characters as a single delimiter.
The function supports custom delimiters for parsing structured data. For example, email addresses can be processed by first splitting the string on whitespace to isolate the email part and then splitting that part on the '@' character.
This lecture covers debugging a Python program that processes mailbox data to extract the third word from lines beginning with from space. The program fails due to index errors when encountering blank lines, as splitting them produces empty lists.
The solution uses a guardian pattern to check that a line has at least three words before indexing. This pattern prevents index errors and is implemented using short-circuit evaluation to ensure safe processing of mailbox data.
Python dictionaries are a collection data type that stores key-value pairs, allowing for fast lookups by key. They maintain insertion order in Python 3.7 and later versions, which was not the case in earlier versions where the order was randomized.
The underlying implementation of dictionaries in Python uses hash tables, which facilitate quick retrieval of values by key. In contrast, lists require sequential scanning to find an element by position.
This lecture demonstrates the use of Python dictionaries to count the frequency of names, a foundational technique for creating histograms. The process involves iterating through a sequence of names and updating a dictionary where each name maps to its occurrence count.
The lecture shows two approaches: a conditional method that handles new keys and existing keys separately, and a one-liner using the get method with a default value of zero to increment the count by one. This pattern ensures the first occurrence of a name starts at one and prevents traceback errors.
This lecture demonstrates building a word frequency histogram by reading a text file line by line, splitting each line into words, and updating a dictionary count for each word.
The lecture covers iterating through dictionaries using keys, values, and items. It shows how to use items with two iteration variables to process key-value pairs and explains finding the most common word by tracking the highest count during iteration.
This lecture demonstrates a Python program that processes a text file to count word frequencies and find the most common word. The program uses file I/O operations, string splitting, nested loops, and dictionary data structures.
The code reads a file, splits each line into words, and counts each word using a dictionary with the get method to handle missing keys. It then identifies the word with the highest frequency count by iterating through the dictionary.
Tuples in Python are immutable, ordered collections that function similarly to lists but cannot be altered after initialization. They are defined using parentheses and are more memory efficient than lists, making them suitable for temporary data where immutability is required. Tuples maintain the same positional indexing as lists and support index lookup operations, but lack methods for modification.
Tuples are used for simultaneous variable assignment via unpacking and are integral to dictionary operations, where key-value pairs are returned as tuples during iteration. They are also comparable, allowing lexicographical ordering of tuples by comparing elements from left to right until a difference is found, which is useful for sorting collections of tuples.
This lecture explains how to sort Python dictionaries by key and value using tuples. When sorting by key, the sorted function returns a list of tuples sorted in ascending order by key. For sorting by value, the lecture constructs a list of tuples with value first and key second, then sorts this list in descending order.
The example demonstrates counting word frequencies in a file and sorting the resulting dictionary to show the top 10 most common words. The lecture also presents a list comprehension method for generating the sorted list in a single line, though it notes that the two-step process is more straightforward for beginners.
This lecture explains how to sort a Python dictionary by value using tuples to find the top five most frequent words in a text. It begins with a dictionary of word counts and demonstrates the process of creating a list of tuples for sorting.
The code reverses key-value pairs to form tuples (value, key), sorts the list lexicographically, and extracts the top five words. Tuple comparison rules are described, including how ties are resolved by the key (the word) in alphabetical order.
Welcome to Python for Everybody. This course teaches you to program in Python even if you have never written a line of code. You start with the big picture: why people learn to program, how a computer’s CPU, memory, and storage work together, and how Python fits in as a language you can read and write.
From there you build the core skills step by step. You learn variables, expressions, and statements so you can store data and do calculations. You use conditional execution so programs can make decisions, and you practice loops so you can repeat work over data. You learn functions—the “store and reuse” pattern—so you can organize code into pieces you call when you need them.
Then the course moves into text and real data. You work with strings, open and read files, and process lines of text. You learn Python’s main collections for holding many values: lists, dictionaries, and tuples. You use dictionaries to count things (histograms), and tuples to sort data effectively. Finally, you get an introduction to regular expressions so you can search for patterns and extract information from text with the `re` library. You can think of regular expressions as a second (very small) programming language for you to learn.
Along the way, worked-exercise videos walk through sample problems so you can see how the ideas turn into working programs. The tone is practical and beginner-friendly: small examples, clear patterns, and enough detail to help you when Python gives you an error message.
All of the programming can be done in a browser - there is no need to install Python if you do not or cannot install software on your computer. It can be done on a ChromeBook, iPad or even a phone.