these notes accompany this video: A hands-on introduction to Python for beginning programmers
" "
.( )
.[ ]
.==
!=
>
<
<=
>=
"h" in "hello"
would return True
. "z" not in "hello"
would return True
. "z" in "Fantastic"
would return False
.
1sister_age = 15
2brother_age = 12
3
4if sister_age > brother_age:
5 print "sister is older"
6elif sister_age == brother_age:
7 print "same age!"
8else:
9 print "brother is older"
Another example
1temperature = 70
2if temperature > 60 and temperature < 75:
3 print "just Right!"
4else:
5 print "Too extreme"
pass
in 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.
1my_list = ["a", "b", "c"]
Lists are ordered and index starts from zero.
len(my_list)
my_list.append("d")
my_list[0] = "z"
my_list.index("c")
"a" in my_list
To get the first item in the list: my_list[0]
To get the last item in the list: my_list[-1]
To get the second last item in the list: my_list[-2]
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.
1my_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:
1list = ['Hola', 16, True, -.8 ]
.sort()
will sort the list items from A-Z alphabetically and from Low to High numerically.
1names = ['Zelda', 'Ali', 'Ahmed', 'Zyad', 'Nina', 'Bob' ]
2names.sort()
will change the order/sort of the list items like this:
['Ahmed', 'Ali', 'Bob', 'Nina', 'Zelda', 'Zyad']
Numbers can also be sorted:
1numbers = [3, -5, .6, 17000, 7]
2numbers.sort()
3numbers
4[-5, 0.6, 3, 7, 17000]
max(numbers)
will give you 17000.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:
1for variable_name in list_name:
2 # do useful work
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:
1names = ['Ahmed', 'Ali', 'Bob', 'Nina', 'Zelda', 'Zyad']
2
3for name in names:
4 print name
Another for loop with an if statement (condition):
1names = ['Ali', 'Bob', 'Ellen', 'Nina', 'Zelda', 'Zyad']
2
3for name in names:
4 # if the first letter of the name starts with a vowel
5 if name[0] in "AEIOU":
6 print name + " starts with a vowel."
will output:
Ali starts with a vowel.
Ellen starts with a vowel.