these notes accompany this video: A hands-on introduction to Python for beginning programmers
- You know it’s a string because of the quotes
- You know it’s a function because of the parenthesis
- You know it’s a list because of the square brackets
- Integers (1, 2, 9, 10)
- Floats (1.89, 2.75, 8.99)
- Boolean (True, False)
- not in
"h" in "hello" would return
"z" not in "hello" would return
"z" in "Fantastic" would return
- The keyword for ‘do nothing’ is
passin Python. If you have an if statement and you want to do nothing you would use the keyword pass.
A list contains comma seperated elements in square brackets.
Lists are ordered and index starts from zero.
- To check the length of a list:
- To append a new item to the end of the list:
- To replace list items:
my_list = "z"
- To get the index (place) of an item:
- To check containment (whether an item exists in the list):
"a" in my_list
Slicing and dicing lists
To get the first item in the list:
To get the last item in the list:
To get the second last item in the list:
To get a range of items:
my_list[0:2] Take 0th upto but not including the 2nd.
my_list[:3] Take everything upto but not including 3rd.
my_list[3:] Start at the 3rd and go till the end.
my_list[:] makes a copy of the whole list. Start at the beginning, go till the end.
Strings are a lot like lists. You can do
len() on a string as well as find index and splice and dice lists.
my_string = "Bonjour la monde!"
my_string[:3] would output ‘Bon’.
my_string[5:] would output
ur la monde!
Lists can have all kinds of data types. For example:
.sort() will sort the list items from A-Z alphabetically and from Low to High numerically.
will change the order/sort of the list items like this:
['Ahmed', 'Ali', 'Bob', 'Nina', 'Zelda', 'Zyad']
Numbers can also be sorted:
- To find the maximum value in a list:
max(numbers)will give you 17000.
- To find the minimum value in a list:
min(numbers)will give you -5.
In general, if you think you can do something to a list of stuff, you probably can in Python. Google for it.
For loops. For loops are when you loop over every element in the list, and do something for each element in the list.
The syntax is:
You get to choose the variable name. It could be ‘x’ or ‘name’ or anything you want. For user friendlyness the variable_name is usually the singular form of the word when the list_name is the plural form of the word.
For example, name in names:
Another for loop with an if statement (condition):
Ali starts with a vowel. Ellen starts with a vowel.