This article is a quick guide that goes over syntax and concepts taught in the Python 2 course.
Last updated - July 22, 2024
Table of Contents
For Loop Conditionals
List Methods
Accessing Items in a List
Integer List Methods
Additional List Methods
While Loops
Functions
Function Declaration
Function Parameters
Dictionaries
Dictionary Declaration
Dictionary Methods
Looping Through Dictionaries
Tuples
Tuple Declaration
Tuple Methods
For Loop Conditionals
Conditionals can be placed inside a for loop to check if a condition is true for each looped item.
student_ages = [14, 17, 12, 18]
for x in student_ages:
if x >= 16:
print("This student is old enough to drive.")
else:
print("This student is not old enough to drive.")
Output: "This student is not old enough to drive."
"This student is old enough to drive."
"This student is not old enough to drive."
"This student is old enough to drive."
For loops can be used to update variables. In this example, all numbers in the list are added to the total variable.
my_list = [2, 5, 8, 10]
total = 0
for x in my_list:
total = total + x
print(total)
Output: 25
Accessing Items in a List
The simplest way to access an item in a list is by using an item's index. Remember, when figuring out an index number, start counting at zero! The first item is index zero, the second is index one, and so on.
shapes = ["circle", "square", "triangle"]
print(shapes[1])
Output: square
You can also access a range of list items using the range syntax. You will input two index numbers. The first is the starting index and the second is the stopping index.
desserts = ["cookies", "brownies", "cake", "pie", "churros"]
print(desserts[1:4])
Output: ['brownies', 'cake', 'pie']
List items can be pulled and used in concatenation.
shapes = ["circle", "square", "triangle"]
print("I just drew a " + shapes[1] + " on my paper!")
Output: I just drew a square on my paper!
Using the in keyword, we can check if an item is in a list.
fruit = ["apple", "banana", "orange", "kiwi"]
if "kiwi" in fruit:
print("Kiwi is a fruit!")
Output: Kiwi is a fruit!
Integer List Methods
round( number, decimal points) |
The round() function rounds a number to the specified amount of decimal points. print(round(1.1111, 2)) |
for x in range( Start, Finish ): |
The range function prints a set of numbers starting at the first inputted number and stopping at the second inputted number. for x in range(0, 5): |
list[ Start: Finish: Step ] |
The step syntax returns a range of list items with a step added to the third value. The step is the number of steps before another item is returned. When the step is 2, every other item within a range is returned. my_list = ["first", "second", "third", |
max( list ) |
The max function returns the largest number in a list. my_list = [1, 2, 3, 4, 5, 6, 7, 88, 9] |
min( list ) |
The min function returns the smallest number in a list. my_list = [1, 2, 3, 4, 5, 6, 7, 88, 9] |
Additional List Methods
list.append() |
The append method adds a value to the end of a list. fruit = ["apple", "kiwi", "orange"] |
list.extend() |
The extend method adds a list to the end of another list. my_list = ["Billy", "Frannie","Leslie", |
list.insert() |
The insert function adds an item to a list at a specific index. dessert = ["pie", "cookies", "cake"] |
list.remove( item ) |
The remove function removes an inputted item from a list. dessert = ["pie", "cookies", "cake"] |
list.pop() |
The pop method returns an item at an inputted index and removes it from the list. my_list = ["first", "second", "third", "fourth"] |
len( list ) |
The len() method returns the number of items in a list. my_list = ["apples", "bananas", "oranges", "kiwis"] |
list.sort() |
The sort method sorts a list of words alphabetically or a list of numbers from smallest to largest. my_nums = [2, 5, 3, 4, 6, 1] |
list.sort(reverse=True) | When the reverse=True is added to the sort method, a list of words is sorted in reverse alphabetical order. A list of numbers will be sorted from largest to smallest. |
While Loops
A while loop is a function that continues running while a specific condition is true. In this example, we change an integer to a string by wrapping it with the str() function.
cookies = 5
while cookies > 0:
print("Cookies: " + str(cookies))
cookies = cookies - 1
Output: Cookies: 5
Cookies: 4
Cookies: 3
Cookies: 2
Cookies: 1
Functions
A function is a reusable block of code that runs when it is called. To define a function, use the def keyword.
def weather():
print("It is raining outside!")
weather()
Output: It is raining outside!
Function Parameters
Function parameters allow data (arguments) to be passed into a function. Below, first_name and last_name are parameters, John and Doe are arguments. In this example, any two strings can be passed into the function as arguments.
def my_name(first_name, last_name):
print("Hello, my name is " + first_name + " " + last_name)
my_name("John", "Doe")
Output: Hello, my name is John Doe
You can include different data types for function arguments!
def cookies(is_true, num):
if (is_true == True):
print("I have " + str(num) + " cookies!")
else:
print("I don't have " + str(num) + " cookies!")
cookies(True, 10)
cookies(False, 12)
Output: I have 10 cookies!
I don't have 12 cookies!
Dictionaries
Dictionaries are collections of data that are ordered, changeable, and indexed. Data is stored in key-value pairs.
pet = {
"is_dog": True,
"name": "Spot",
"age": 6
}
print(pet)
Output: {'is_dog': True, 'name': 'Spot', 'age': 6}
To access an item in the list, type the dictionary name followed by a set of [ ] brackets. Within the brackets, type the name of the key whose value you would like to access.
pet = {
"is_dog": True,
"name": "Spot",
"age": 6
}
print(pet["is_dog"])
Output: True
To update a value, access the item, follow it by an equals sign, and input the new value.
pet = {
"is_dog": True,
"name": "Spot",
"age": 6
}
pet["is_dog"] = False
print(pet["is_dog"])
Output: False
Dictionary Methods
dictionary_name[ new key ] = new value |
To add to a dictionary, type the dictionary name followed by a set of [ ] brackets. Within the brackets, type the name of the key. Add an equals sign and then type in the value. pet = { |
dictionary_name.pop() |
Items can be removed using the pop() method. Type the dictionary name followed by ".pop()." Within the parenthesis, type the key name of the item you would like to remove. pet = { |
len(dictionary_name) |
The len() method can be used to find the length of a dictionary. The dictionary name is placed within the parenthesis. pet = { |
if key in dictionary_name: |
Using the if-in syntax, we can check to see if a key exists in a dictionary. To do this, type if followed by the key name you are checking for. Then type in and follow that with the dictionary name. All together it will look like "if key in dictionary:" pet = { |
if key not in dictionary_name: |
The if not-in syntax checks if a key is not in a dictionary. pet = { |
dict.fromkeys(list_name, value) |
It is possible to convert a list into a dictionary. To do this, use the dict.fromkeys(list name, values) syntax. The first argument is the list name. The second is what you would like the value to be. All keys will have the same value. garden = ["pumpkin", "squash", "corn", |
Looping Through Dictionaries
Both keys and values in a dictionary can be looped through. To loop through the keys, use the for-in loop method.
fruit = {
"apples": 5,
"oranges": 3,
"kiwis": 7
}
for x in fruit:
print(x)
Output: apples
oranges
kiwis
The values can be accessed using the .values() method. Using .values() with the for-in syntax will return the values.
fruit = {
"apples": 5,
"oranges": 3,
"kiwis": 7
}
for x in fruit.values():
print(x)
Output: 5
3
7
To return both the key and value, use the for-in syntax along with the .items() method.
fruit = {
"apples": 5,
"oranges": 3,
"kiwis": 7
}
for x,y in fruit.items():
print(x, y)
Output: apples 5
oranges 3
kiwis 7
Conditional statements can also be used when looping through a dictionary.
fruit = {
"bananas": 6,
"apples": 9,
"oranges": 4
}
for x in fruit:
if x == "apples":
print("I am allergic to apples")
else:
print("I like eating " + x)
Output: I like eating bananas
I am allergic to apples
I like eating oranges
Tuples
Tuples are collections of data that are ordered and unchangeable. They look similar to lists, but instead of using the [ ] brackets, they use parenthesis.
instruments = ("trumpet", "clarinet", "trombone")
print(instruments)
Output:('trumpet', 'clarinet', 'trombone')
Tuple Methods
tuple_name[ index ] |
This syntax is used to access items in a tuple. fruits = ("bananas", "oranges", "apples") |
tuple_name[ negative index ] |
To start counting from the end of the tuple, use negative numbers. -1 is the last item, -2 is the second to last and so on. fruits = ("bananas", "oranges", "apples") |
tuple_name[ starting index, ending index ] |
To return a range of items in a tuple, use the [ : ] syntax. The first number is the starting index. The second number is the ending index. fruits = ("bananas", "oranges", "apples", |
if item in tuple: |
To check if an item exists within a tuple, use the if-in syntax. fruits = ("bananas", "oranges", "apples", |