1. Home
  2. Explore
  3. Computer Science
  4. Python Programming Basics

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Python Programming Basics

Speaker 1Speaker 2

Python Programming Basics

21:45
0:00-21:45
  1. Corey

    Welcome! This course is about getting started programming in Python. Python is popular, sought after in many jobs, and used for everything from automating everyday tasks to writing scripts and larger projects. One reason people are drawn to it is that its syntax can feel more approachable than languages with lots of rules to memorize.

  2. Anna

    And if you’re intimidated, the goal here is to guide you through the core ideas step by step. We’ll start by getting Python installed, then build up from simple instructions to programs that handle data, make decisions, and interact with users.

  3. Corey

    The installation lesson describes two major versions in use at the time: Python 2 and Python 3. Python 2 was the older, legacy version; Python 3 was the actively maintained direction the course chose to teach. There could be differences in syntax and libraries, but the course recommends Python 3 for beginners.

  4. Anna

    One detail to keep in mind is that the download numbers in the lesson—such as Python 3.6.3 and Python 2.7.14—are examples from when that tutorial was recorded, not timeless version recommendations. The general lesson is to choose the Python 3 version appropriate to your computer and course materials.

  5. Corey

    After installing Python, the course uses PyCharm, an IDE—an integrated development environment. An IDE gives you a place to write and run code, and it can point out errors or offer clues for fixing them. PyCharm has a paid Professional edition and a free, open-source Community edition; the lesson uses Community.

  6. Anna

    When you create a project in PyCharm, select a Python 3 interpreter so your project runs with the version the course teaches. On a Mac, the tutorial notes that a Python 2 interpreter may already be present, so check rather than assuming the right one is selected. Then create a Python file, such as app.py, and you’re ready to try a first program.

  7. Corey

    A classic first program is `print("Hello world")`. The `print` function displays what’s inside its parentheses in the console. Run the file, and seeing that message means you’ve written and executed a Python program.

  8. Anna

    A program is a set of instructions for the computer. Python executes those instructions in order, one line after another, so order matters. The lesson demonstrates this by using several print statements to draw a triangle-like shape: each line prints part of the picture, and moving a line changes where that piece appears.

  9. Corey

    The console is where that output appears. It’s useful not only for showing a finished message or shape, but also for giving you a window into what your program is doing while you develop it.

  10. Anna

    Next comes variables. Think of a variable as a named container for a value. If a story mentions a character’s name and age many times, changing each occurrence by hand is tedious and error-prone. Store those details in variables, then use the variables wherever you need them.

  11. Corey

    For example, you might assign `character_name = "John"` and `character_age = 35`. A variable name can use an underscore to separate words. In a print statement, you can combine text and a string variable with plus signs, taking care to include spaces where you want them.

  12. Anna

    Variables can be reassigned, too. If the character changes names halfway through a story, assign a new value to `character_name`; later references use the updated value. That makes it much easier to manage information across a program.

  13. Corey

    The lesson introduces three common kinds of values: strings, numbers, and Booleans. A string is text in quotation marks, such as a name. Numbers can be whole numbers or decimals, and they don’t use quotation marks. A Boolean is either `True` or `False`, which is useful whenever a program needs to represent a yes-or-no condition.

  14. Anna

    Strings have several useful operations. A backslash followed by `n`, written `\n`, starts a new line; a backslash before a quote lets you include a literal quotation mark instead of ending the string. That backslash is called an escape character, and a doubled backslash can represent a literal backslash.

  15. Corey

    You can join strings with concatenation: for example, add a phrase like `" is cool"` to another string. String methods can change or test text, too. `.lower()` makes a lowercase version, `.upper()` makes an uppercase version, and `.isupper()` returns a Boolean telling you whether the string is entirely uppercase.

  16. Anna

    You can combine methods: apply `.upper()` and then `.isupper()` to check the uppercase result. The built-in `len` function tells you how many characters a string contains. And square brackets let you get one character by its index.

  17. Corey

    Indices start at zero in Python. So the first character is at index zero, the next at one, and so on. The `.index()` method finds where a character or substring first occurs; if it can’t find the requested text, it raises an error. The `.replace()` method takes two arguments: the text to replace and the replacement text.

  18. Anna

    Numbers support basic arithmetic: addition, subtraction, multiplication, and division. Parentheses let you control the order of operations. The percent sign is the modulo operator: `10 % 3`, read as “ten mod three,” gives the remainder, which is one.

  19. Corey

    You can store numbers in variables and convert a number to text with `str()`, for example when combining it with a string for display. Other useful operations include `abs()` for absolute value, `pow()` for raising a number to a power, `max()` and `min()` for choosing the larger or smaller value, and `round()` for rounding.

  20. Anna

    For additional math tools, import from the `math` module. The tutorial shows `floor` to move down to the lower integer, `ceil` to move up to the next integer, and `sqrt` to find a square root. The important idea is that importing a module makes its extra functions available to your program.

  21. Corey

    To get information from a person using your program, call `input()`. You can give it a prompt, such as “Enter your name,” and assign the response to a variable. Then use that value in a message like “Hello,” followed by the name.

  22. Anna

    A basic calculator reveals an important detail: `input()` returns a string, even when someone types digits. If you add two input strings directly, Python concatenates them—so `5` and `8.3` can become `58.3`, not a numerical sum.

  23. Corey

    Convert the input before doing arithmetic. `int()` converts text to a whole-number integer, while `float()` converts it to a number that can include a decimal. The calculator uses floats so it can add values such as 4 and 5.5.

  24. Anna

    A Mad Libs game combines several ideas: collect words with `input()`, store them in variables, and insert them into a story. The example asks for a color, a plural noun, and a celebrity, then uses those responses in a poem. The fun comes from the user supplying unexpected words.

  25. Corey

    For multiple related values, use a list. Create one with square brackets, and separate its elements with commas. A list can hold many values, including strings, numbers, or Booleans; a common pattern is to put related items, such as friends’ names, together.

  26. Anna

    You can print a whole list or access an individual element by its index, again starting from zero. Negative indices count from the end: `-1` refers to the last element. A slice such as `friends[1:]` selects from index one onward, while a range such as `friends[1:3]` includes index one but stops before index three.

  27. Corey

    Lists can also be changed. Assigning a new value to a particular index replaces the old element. Common list methods include `.extend()` to add the contents of another list, `.append()` to add one item at the end, and `.insert(index, value)` to put an item at a chosen position.

  28. Anna

    To remove values, `.remove(value)` removes a matching item, `.clear()` empties the list, and `.pop()` removes the final item. `.index(value)` finds an item’s position, and `.count(value)` tells you how many times it occurs. `.sort()` orders the list, `.reverse()` reverses its order, and `.copy()` makes a copy.

  29. Corey

    A tuple also stores multiple values, but uses parentheses. Like a list, it supports indexing from zero. Its key difference is that it’s immutable: once created, you can’t add, remove, or change its elements.

  30. Anna

    That makes tuples useful for values that aren’t meant to change, such as a coordinate pair. You can also have a list of tuples if you need a collection of fixed coordinate pairs. In the course’s terms, lists are more common for general-purpose collections, while tuples suit certain unchanging data.

  31. Corey

    Functions help organize code into reusable blocks that perform a task. Define one with `def`, followed by a descriptive name, parentheses, and a colon. The function body is indented, and it doesn’t run just because you defined it—you have to call it by name with parentheses.

  32. Anna

    When Python reaches a function call, it runs the function’s body, then returns to the next instruction after the call. Functions can take parameters, which are pieces of information supplied by the caller. A greeting function, for instance, can accept a name and age and use them to personalize its output.

  33. Corey

    A function can also send information back with `return`. The example defines a function that cubes a number by multiplying it by itself three times, then returns that result. You can print the returned value or store it in a variable for later use.

  34. Anna

    A return statement also ends that function call, so code placed after it in the same path won’t execute. Functions can return different kinds of values, and parameters let information flow in while `return` lets a result flow back out.

  35. Corey

    If statements let programs make decisions. An `if` checks a condition, which is true or false; if it’s true, Python runs the indented block. An `else` block handles the alternative. The everyday examples are things like eating breakfast if you’re hungry, or choosing sunglasses if it isn’t cloudy.

  36. Anna

    You can test multiple conditions with `and` and `or`. With `and`, both conditions must be true; with `or`, at least one must be true. `not` reverses a Boolean condition. An `elif`—short for “else if”—lets you check another condition if the earlier one wasn’t true.

  37. Corey

    Comparison operators make conditions more flexible. Use `==` to test equality, `!=` to test inequality, and `>`, `<`, `>=`, or `<=` for numeric comparisons. The maximum-of-three example compares the numbers in turn and returns whichever is largest.

  38. Anna

    The course then applies conditions to a calculator. It reads two numbers and an operator, converts the numbers to floats, and uses `if` and `elif` to select addition, subtraction, division, or multiplication. An `else` handles an unsupported operator with an “invalid operator” message.

  39. Corey

    Dictionaries organize data as key-value pairs. A familiar analogy is a conventional dictionary: the word is the key and the definition is the value. In Python, curly braces hold the pairs, each written as a key, a colon, and its value.

  40. Anna

    The month-conversion example maps abbreviations such as `JAN` to names such as `January`. Keys need to be unique. You can retrieve a value with square brackets or with `.get(key)`. `.get()` can also take a default value to return if the key isn’t found, rather than simply giving you `None`.

  41. Corey

    A while loop repeats an indented block as long as its condition remains true. The example starts a counter at one, prints it, and adds one each time until the counter is no longer less than or equal to ten. Then execution continues after the loop.

  42. Anna

    That update matters: if the condition never becomes false, the loop can continue indefinitely. Python checks the condition before each pass through the body. The shorthand `i += 1` adds one to `i`, just as `i = i + 1` does.

  43. Corey

    A guessing game puts these pieces together. Store a secret word and a guess, then keep asking for input in a while loop until the guess matches the secret. Once it matches, the loop ends and the program can print that the player wins.

  44. Anna

    To limit the number of tries, track a guess count, set a guess limit, and use a Boolean such as `out_of_guesses`. Each guess increases the count. Continue only while the word hasn’t been guessed and the player still has guesses; when the loop ends, check whether they ran out or succeeded.

  45. Corey

    A for loop is useful for going through a collection. In `for letter in "draft Academy"`, the loop variable takes each character in turn. The same pattern works with a list: `for friend in friends` visits each friend, and the loop variable holds the current item on each pass.

  46. Anna

    You can also loop over numbers with `range()`. `range(10)` produces values from zero through nine; `range(3, 10)` produces three through nine. The ending value is excluded. To visit each list element by index, the lesson combines `range()` with `len(list)` and uses the index to retrieve the item.

  47. Corey

    You can put logic inside a loop, too. For instance, an `if` can test whether the index is zero, so you do something different on the first iteration than on later ones. That’s a small example of how loops and conditionals work together.

  48. Anna

    The exponent example builds a function that raises a base to a power using a for loop. Start a result at one, repeat multiplication by the base as many times as the power indicates, then return the result. Python also has a direct exponent operator, but building the function helps show how repetition can implement the operation.

  49. Corey

    A two-dimensional list is a list whose elements are themselves lists. That lets you represent a grid: each inner list can be thought of as a row. To access a particular cell, use two indices—first the row, then the column.

  50. Anna

    To visit every value in that grid, use nested for loops. The outer loop visits each row, and the inner loop visits each item in the current row. This pattern is useful whenever data is arranged in rows and columns.

  51. Corey

    The translator example also combines loops and conditions. It visits each letter in a phrase; if the letter is a vowel, it adds `g` to the translation, and otherwise it adds the original letter. It builds the result one character at a time, then returns it.

  52. Anna

    The example checks vowels in both lowercase and uppercase. One refinement is to test `letter.lower()` against lowercase vowels, so the same membership check works for either case. If you want to preserve capitalization, check whether the original letter is uppercase and add an uppercase `G` when appropriate.

  53. Corey

    Comments are notes for people reading the code; Python ignores them when it runs the program. A `#` starts a single-line comment, and you can use another `#` on each new line. Comments can explain what code does or serve as reminders.

  54. Anna

    You can also comment out code by putting a comment marker in front of it. That temporarily prevents Python from executing the line without deleting it. The tutorial mentions triple quotes as another way to write a block of text, but recommends using `#` on each line for ordinary comments.

  55. Corey

    Errors can stop a program, so it’s useful to handle expected problems. For example, converting user input to an integer fails if the user types a word instead. A `try` block marks code to attempt, and an `except` block handles an error that occurs instead of letting it stop the program.

  56. Anna

    Be specific about the errors you catch. The lesson distinguishes a `ValueError`, such as invalid integer input, from a `ZeroDivisionError`, caused by dividing by zero. Separate `except` blocks can respond differently, and `except ... as err` lets you store and display the error details.

  57. Corey

    External files let a program read or write information beyond its own source code. Use `open()` with a filename and a mode. The lesson introduces `r` for reading, `w` for writing, `a` for appending to the end, and `r+` for reading and writing.

  58. Anna

    Store the opened file in a variable, then close it when you’re done. You can check `.readable()`, read the whole file with `.read()`, read one line with `.readline()`, or get all lines as a list with `.readlines()`. A for loop can then process those lines one by one.

  59. Corey

    Writing needs extra care because changes are saved to the file. In append mode, `.write()` adds content to the end; running the program again can add the same content again. If you need a new line, include the newline escape sequence `\n` where appropriate.

  60. Anna

    Write mode, `w`, replaces the existing file’s contents, so it can erase material you meant to keep. It can also create a new file if the named file doesn’t exist. That means the mode you choose is important: reading, appending, and overwriting do different things.

  61. Corey

    A module is a Python file whose contents you can reuse in another file. Use `import` to bring it in, then refer to its functions or values through the module name. In the example, a useful-tools file contains constants, a list, and functions, including one for rolling a die.

  62. Anna

    Python also comes with built-in and standard-library modules, while third-party modules are created by other developers. To install many third-party packages, the course introduces `pip`, a package manager. You can use a command such as `pip install package-name`, and, when needed, `pip uninstall package-name` to remove a package.

  63. Corey

    The lesson uses Python-docx as an example of a third-party package and notes that installed packages may appear in a `site-packages` folder. The exact import name and installation steps depend on the package, so follow that package’s own documentation and make sure it matches your Python setup.

  64. Anna

    Classes let you define your own kinds of data. A class is a template for a type of object; an object is a particular instance with actual values. That lets you represent real-world concepts that don’t fit neatly into a single string, number, or Boolean.

  65. Corey

    The student example defines a `Student` class with a name, major, GPA, and probation status. Its special `__init__` method runs when you create a student. It receives those values and assigns them to attributes on the object, using `self` to refer to that particular student.

  66. Anna

    Once you create student objects, you can access their attributes with dot notation, such as `student_one.name` or `student_two.gpa`. Each object has its own values, even though both were created from the same class template. That’s the basic distinction between a class and an object.

  67. Corey

    The multiple-choice quiz applies classes by defining a question with a prompt and an answer. It creates a list of question objects, then a function loops through them, asks each prompt, checks the user’s answer, and increases a score for correct responses. At the end, it reports the score out of the total number of questions.

  68. Anna

    Classes can also contain their own functions, often called methods. A student class might include an `on_honor_roll()` method that checks whether the student’s GPA is at least 3.5 and returns `True` or `False`. The method uses `self` to inspect the current object’s GPA.

  69. Corey

    Inheritance lets one class reuse functionality from another. The chef example begins with a general chef class that can make chicken, salad, and a special dish. A Chinese chef can inherit from that class, gaining its methods without copying all their code.

  70. Anna

    The child class can add something new, such as a method for making fried rice, or override an inherited method. If it defines its own special-dish method, that version is used for the Chinese chef, while the general chef keeps its original special dish.

  71. Corey

    Finally, the Python interpreter gives you a quick place to try Python commands. You open a terminal on Mac or a command prompt on Windows, then start the interpreter with the appropriate Python command. You can test expressions, variables, functions, loops, and other code interactively.

  72. Anna

    It’s a handy sandbox for quick experiments, but a text editor or IDE is better for writing and organizing a complete program. The course’s larger message is to practice these building blocks—data, decisions, loops, functions, files, modules, and objects—so you can become more confident writing Python programs and scripts.

  73. Corey

    That’s our path from installing Python and printing a first message to building games, calculators, and reusable code. Take the concepts one at a time, try the examples yourself, and don’t be afraid to experiment.

  74. Anna

    And when something goes wrong, treat it as part of learning: read the error, check the relevant values and conditions, and make a small adjustment. With practice, these pieces start fitting together—and you’ll be ready to create programs that do useful and interesting things.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent