This Python Examples lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
Each lesson on this page ends with a short program you can edit. Run it, change one value, and run it again.
The example below filters a list and prints the names that passed.
Example 1: Start here
Expected output is a list containing Meera.
rows = [{"name": "Meera", "score": 82}, {"name": "Arun", "score": 64}] # a list; the values stay in this order
print([row["name"] for row in rows if row["score"] >= 70]) # keep the items that pass the test
Example 2: A labeled print
Say what the value means, then print the value.
city = "Chennai" # text
print("City:", city) # a comma prints each value, with a space between
Example 3: A small function
Put the calculation in a function so you can call it with a new number.
def double(n): # define the function; it runs when you call it
return n * 2 # send this value back to the caller
print(double(6))
Example 4: A filter
Keep the scores that pass the test and ignore the rest.
scores = [60, 82, 91] # a list; the values stay in this order
print([score for score in scores if score >= 80]) # keep the items that pass the test
