Python for Programmers: A Taste of Python
Welcome to the A Taste of Python lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
This course covers Python, a general purpose programming language most commonly used for web applications and data science. In this introductory lesson, we'll take a quick tour of many of Python's features.
Because this is only "a taste of Python", don't worry about understanding every detail in every example! Our goal is to give you a sense of what Python looks like. The rest of the course will carefully explore each language feature one by one.
This course requires that you've used at least one other programming language. It doesn't matter which one, as long as you're comfortable with variables, functions, conditionals (like
if), and loops (likefor).Python's syntax prioritizes readability and ease of use. For example, Python variable definitions are as simple as they can possibly be:
some_var = some_value.>
user_input = "hunter3"user_inputResult:
Python uses whitespace for control flow instead of {braces} or
do/endmarkers.>
user_input = "hunter3"secret_password = "hunter2"if user_input == secret_password:message = "Access granted"else:message = "Access denied"messageResult:
'Access denied'
Python has many features to help us write self-documenting code. In the next example, note that the function accepts
current_balance, expense, but we pass the arguments in the opposite order:expensethencurrent_balance. This is possible thanks to "keyword arguments", where we pass function arguments by their names, rather than by their positions. We can pass them in any order as long as the names match.>
def new_balance(current_balance, expense):balance = current_balance - expensereturn balancenew_balance(expense=2,current_balance=5,)Result:
Python has familiar collection data types, like arrays (called "lists" in Python). These come with a rich set of convenience functions and methods.
>
measurements = [20, 56, 34, 46, 120, 2]max(measurements)Result:
- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
min(measurements)Result:
2
If your primary language is JavaScript, you'll be happy to hear that Python's
==operator correctly compares lists. In fact,==works with almost any value in Python!>
measurements = [20, 56, 34, 46, 120, 2]# Remove the smallest and largest values.measurements.remove(max(measurements))measurements.remove(min(measurements))measurements.sort()measurements == [20, 34, 46, 56]Result:
Tuples are similar to lists, except they're defined with (parentheses) instead of [square brackets].
>
# This is a tuple, not a list!some_numbers = (1, 2, 3, 4)some_numbers[1]Result:
2
The biggest difference between tuples and lists is that tuples can't be changed after they're created. When you see a tuple, you never have to worry about whether other code will replace some of its elements.
- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
some_numbers[1] = 42Result:
Finally, Python has dictionaries, which are called "maps" or "hashes" in some languages. Dictionaries are also similar to JavaScript's "objects", but they allow any values as keys, not just strings. That turns some awkward problems into straightforward problems.
The next example builds a dictionary. Its keys are 2D x-y coordinates, represented as tuples like
(2, 3). Its values are strings telling us what objects exist at each coordinate. Code like this is often awkward to write in other languages, but it's easy to write in Python!>
treasure_locations = {(2, 3): "gold",(3, 5): "silver",(1, 4): "bronze"}coordinates = (3, 5)# What's at this location?treasure_locations[coordinates]Result:
'silver'
We can do a lot with just the data structures that we've seen so far. The next example loops through a list of tuples using Python's
for ... in ...loop. Note that we assign the individual tuple elements to separate variables right inside theforloop. (This is called "unpacking" in Python.)>
# Quantities to buy for each item.shopping_list = [(3, "banana"),(2, "milk"),(1, "bread"),]prices = {"milk": 3,"bread": 2,"banana": 10,}total = 0for (amount, item_name) in shopping_list:total += prices[item_name] * amounttotalResult:
Python's syntax was designed to feel familiar and straightforward. It also comes with convenience features to solve common problems. For example, we can use a "comprehension" to collapse the
forloop above into a single line!- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
sum(prices[item_name] * amount for (amount, item_name) in shopping_list)Result:
Here's another convenience feature. Sometimes we need to duplicate a string a certain number of times. In most languages, we'd write a loop. In Python, we can multiply the string by a number to repeat it that many times.
>
"ba" + "na" * 2Result:
Let's use that multiplication trick in a larger example. The code below prints a triangle to the console one row at a time. We use the
range(...)function to iterate through the rows, andprint(...)to print each row. To create space inside the triangle, we use the "multiply a string by a number" operator.>
triangle_height = 10# Print the top of the triangle.print("*")for row_num in range(triangle_height):# Print one row of the triangle: a star, some empty spaces, and another star.print("*" + (" " * row_num) + "*")# Print the final row.print((triangle_height + 2) * "*")console outputPython only has one syntax for comments,
#, which comments out the rest of the line. (You might have noticed comments throughout this lesson.) When we need a multi-line comment, we put a#in front of every line.>
# Say hello to Amir.# Amir has a cat, Ms. Fluff.# We'll meet her later.name = "Amir"nameResult:
'Amir'
There are some things that this course won't cover. For example, we won't cover Python's rich ecosystem of third-party libraries, although we'll occasionally refer to them.
We also won't cover asynchronous programming. That's a complex topic that deserves its own course. (However, we do have a course on JavaScript Concurrency. Many core ideas from that course also apply in Python.)
Finally, we won't cover Python's static type annotations, or the type checkers that check them. Type annotations are powerful and useful! But, like asynchronous programming, they're a huge topic that deserves its own separate course.
Now that you've gotten a glimpse at the power of Python, let's begin!