Python Programming Notes
Python Basics
"Hello World" in Python
print "Hello World"
Comments in Python
Single line comments are started with a hash character.
# This is an example of a Python single line comment.
Python Data Types
Use type() to return the data type of an argument.
| type(True) | <type 'bool'> | # Boolean | |
| type(2514) | <type 'int'> | # Integer | |
| type(2.54) | <type 'float'> | # Floating Point Number | |
| type("test") | <type 'str'> | # String | |
| type([1, 6, 8, 56, 4, 24, 57, 6]) | <type 'list'> | # List | |
| type({'a': 'alpha', 'b': 'bravo', 'c': 'charlie'}) | <type 'dict'> | # Dictionary | |
| type(set(['pear', 'apple', 'grape'])) | <type 'set'> | # Set | |
| type((1,2)) | <type 'tuple'> | # Tuple |
Python Operators
Mathematical Operators
Mathematical operators are used for arithmetic calculations.
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| / | Division |
| // | Floor Division |
| % | Modulus |
| ** | Exponent |
Comparison Operators
Comparison operators compare the value of two operands. A boolean 'true' or 'false' is returned based on the results of the comparison.
| == | Equal To. |
| != | NOT equal To. |
| < | Less than. |
| > | Greater than. |
| <= | Less than or equal to. |
| >= | Greater than or equal to. |
Logical Operators
| and | Tests if both operands are true. |
| or | Tests if either operand is true. |
| not | Reverses the logical state of an operand. |
Examples of Comparison and Logical Operator Usage
For the these examples, assume the following: x = 2; y = 3; z = 2;
| x < y | True | x == y or x == z | True | |
| x > y | False | x == y and x == z | False | |
| x == y | False | x + 1 < y | False | |
| x != y | True | x + 1 <= y | True | |
| x == 2 | True | (x == 2 and y == 3 or y == 4) | True | |
| x != 2 | False | (x == 2 or y == 3 and y == 4) | True |
Assignment Operators
| = | a = 2 |
| += | a += 2 is the same as a = a + 2 |
| −= | a −= 2 is the same as a = a − 2 |
| *= | a *= 2 is the same as a = a * 2 |
| /= | a /= 2 is the same as a = a / 2 |
| %= | a %= 2 is the same as a = a % 2 |
| **= | a **= 2 is the same as a = a**2 |
| //= | a //= 2 is the same as a = a//2 |
Math Functions in Python
Math Functions
| pow() | Syntax: pow(base, exponent) | Uses: Raises a number to a power. |
| pow(2,4) | Returns 16 | |
| abs() | Syntax: abs(n) | Uses: Returns the absolute value of a number. |
| abs(7) | Returns 7 | |
| abs(-14) | Returns 14 | |
| bin() | Syntax: bin(n) | Uses: Returns binary value of argument. |
| bin(1) | Returns '0b1' | |
| bin(14) | Returns '0b1110' | |
| round() | Syntax: round(n,decimal places) | Uses: Rounds a number to the specified decimal places. |
| round(3.7864) | Returns 4.0 | |
| round(3.7864,1) | Returns 3.8 | |
| round(3.7864,2) | Returns 3.79 | |
| min() | Syntax: min(iterable, key) | Uses: Finds the smallest value in a string, list, or tuple. An optional key function may applied to the arguments. |
| min([1, -6, -2, 3, 4]) | Returns -6 | |
| min([1, -6, -2, 3, 4], key=abs) | Returns 1 | |
| max() | Syntax: max(iterable, key) | Uses: Finds the largest value in a string, list, or tuple. An optional key function may applied to the arguments. |
| max([1, -6, -2, 3, 4]) | Returns 4 | |
| max([1, -6, -2, 3, 4], key=abs) | Returns -6 | |
Python Math Module Methods
The following examples require the loading of Python's built in math module. Use "import math" to load the module. Type "help (math)" to see a help file for the module.
| math.ceil() | Syntax: math.ceil(number) | Uses: Rounds a number UP to the nearest integer. |
| math.ceil(1.3) | Returns 2.0 | |
| math.ceil(2.74) | Returns 3.0 | |
| math.floor() | Syntax: math.floor(number) | Uses: Rounds number down to nearest integer. |
| math.floor(1.3) | Returns 1.0 | |
| math.floor(2.74) | Returns 2.0 | |
| math.sqrt() | Syntax: math.sqrt(number) | Uses: Returns the square root of a number. Returns an error for a negative number. |
| math.sqrt(9) | Returns 3.0 | |
| math.sqrt(-9) | Returns an error message. | |
| math.pow() | Syntax: math.pow(base, exponent); | Uses: Raises a base to an exponent. |
| math.pow(2, 3) | Returns 8.0 | |
| math.factorial() | Syntax: math.factorial(n) | Uses:Returns the factorial of a number. |
| math.factorial(3) | Returns 6 | |
| math.factorial(6) | Returns 720 | |
| math.fabs() | Syntax:math.fabs(number); | Uses: Returns the absolute value of a number. |
| math.fabs(-15.627) | Returns 15.627 | |
| math.sin() | Syntax: math.sin(angle) | Uses: Returns the sine of an angle. |
| math.cos() | Syntax: math.cos(angle) | Uses: Returns the cosine of an angle. |
| math.tan() | Syntax: math.tan(angle) | Uses: Returns the tangent of an angle. |
| math.asin() | Syntax: math.asin(number) | Uses: Returns the arcsine of number. |
| math.acos() | Syntax: math.acos(number) | Uses: Returns the arccosine of number. |
| math.atan() | Syntax: math.atan(number) | Uses: Returns the arctangent of number. |
| math.degrees() | Syntax: math.degrees(radians) | Uses: Converts an angle from radians to degrees. |
| math.degrees(4.2) | Returns 240.64227395494578 | |
| math.radians() | Syntax: math.radians(degrees) | Uses: Converts an angle from degrees to radians. |
| math.radians(180) | Returns 3.141592653589793 | |
| math.pi | Syntax: math.pi | Uses: Returns the value of Pi. |
Strings in Python
The following sample string is referenced by some of the examples in this section:
sample = "This is the sample string for the following examples."
| .lower() | Syntax: string.lower() | Uses: Returns the string in all lower case. |
| sample.lower() | Returns 'this is the sample string for the following examples.' | |
| .upper() | Syntax: string.upper() | Uses: Returns the string in all upper case. |
| sample.upper() | Returns 'THIS IS THE SAMPLE STRING FOR THE FOLLOWING EXAMPLES.' | |
| string.find() | Syntax: string.find(find, start) | Uses: Returns the index of the first occurrence of a substring. Optional starting index. |
| sample.find("the") | Returns 8 | |
| sample.find("the", 10) | Returns 30 | |
| sample.find("elephant") | Returns -1 # Returns -1 if the value is not found in the string. | |
| .split() | Syntax: string.split() | Uses: Returns a list of the words of a string. Split on each space. |
| sample.split() | Returns ['This', 'is', 'the', 'sample', 'string', 'for', 'the', 'following', 'examples.'] | |
| "Sample Text".split() | Returns ['Sample', 'Text'] | |
| len() | Syntax: len(string) | Uses: Returns the length of the string. |
| len(sample) | Returns 53 | |
| len("Sample Text") | Returns 11 | |
| len(sample.split()) | Returns 9 # Combining len and split to count the words in a string. | |
| len("Sample Text".split()) | Returns 2 | |
Selecting Substrings by Index Location
Use string[start:end] to select a sub-string starting at 'start' index and going to, but not including, 'end' index.
The following sample string is referenced by some of the examples in this section:
sample = "This is the sample string for the following examples."
| sample[2:3] | Returns 'i' | |
| sample[5:18] | Returns 'is the sample' | |
| sample[12:] | Returns 'sample string for the following examples.' | |
| sample[:9] | Returns 'This is t' | |
| "Sample Text"[1:3] | Returns 'am' | |
| "Sample Text"[:3] | Returns 'Sam' | |
| "Sample Text"[2:] | Returns 'mple Text' | |
String Substitution
Each of the following examples produces the same output: "I have 3 computers at home."
print("I have %i %s at %s." % (3, "computers", "home")) # Note 'i' and 's' after '%' to denote integer and string.
print("I have {1} {2} at {3}.".format(3, "computers", "home")) # Using .format method.
print("%s %s %i %s %s %s" % ("I", "have", 3, "computers", "at", "home"))
print("{0} {1} {2} {3} {4} {5}." .format("I", "have", 3, "computers", "at", "home"))
numVal, strVal, strVal2 = 3, "computers", "home"
print("I have {} {} at {}.".format(numVal, strVal, strVal2)) # Using data from string variables.
samDict = {'number': 3, 'item': 'computers', 'location': 'home'}
print("I have %(number)i %(item)s at %(location)s." % samDict) # Using data from a dictionary.
samTuple = (3, 'computers', 'home')
print("I have %i %s at %s." % samTuple) # Using data from a tuple.
print("I have " + str(numVal) + " " + strVal + " at " + strVal2 +".") # The same output using concatenation.
Python Lists
Python lists are enclosed in square brackets and contain one or more items separated by commas.
Examples of Lists
myList = [1, 6, 8, 56, 4, 24, 57, 6]
sample_list = ["elm", "maple", "ash", "oak", "cedar"]
list3 = ["United States", 1776, "North America"]
list_2d = [[3, 5, 7],[6, 8, 4],[6, 8, 8]]
List Functions
Some of these examples use the following sample list: samp = ["elm", "maple", "ash", "oak", "cedar"]
| len() | Syntax: len(list) | Uses: Returns the length of a list. |
| len([6, 4, 1, 3, 7]) | Returns 5 | |
| len(["ace", "king", "queen", "jack"]) | Returns 4 | |
| len(samp) | Returns 5 | |
| min() | Syntax: min(list) | Uses: Returns the largest item in a list. |
| min([6, 4, 1, 3, 7]) | Returns 1 | |
| min(["ace", "king", "queen", "jack"]) | Returns 'ace' | |
| min(samp) | Returns 'ash' | |
| max() | Syntax: max(list) | Uses: Returns the smallest item in a list. |
| max([6, 4, 1, 3, 7]) | Returns 7 | |
| max(["ace", "king", "queen", "jack"]) | Returns 'queen' | |
| max(samp) | Returns 'oak' | |
| sorted() | Syntax: sorted(list) | Uses: Creates a NEW sorted list. |
| sorted(samp) | Returns ['ash', 'cedar', 'elm', 'maple', 'oak'] | |
| sorted(samp, reverse=True) | Returns ['oak', 'maple', 'elm', 'cedar', 'ash'] | |
List Methods
Some of these examples use the following sample list: samp = ["elm", "maple", "ash", "oak", "cedar"]
| .index() | Syntax: .index(search) | Uses: Returns the index of the first occurrence of the search string in a list. |
| samp.index("oak") | Returns 3 | |
| [6, 4, 1, 3, 7].index(3) | Returns 3 | |
| [6, 4, 1, 3, 7].index(4) | Returns 1 | |
| [6, 4, 1, 3, 7].index(8) | Generates an error message. | |
| .sort() | Syntax: .sort() | Uses: Sorts items in a list. |
| .reverse() | Syntax: .reverse() | Uses: Reverses all items in a list. |
| .append() | Syntax: list.append(items) | Uses: Adds items to the end of a list. |
| .extend() | Syntax: list.extend(list2) | Uses: Adds items to the first list from the second list. |
| .pop() | Syntax: list.pop(index) | Uses: Returns the value at a given index and removes it from the list. |
| .remove() | Syntax: list.remove(item) | Uses: Removes a given value from a list. |
| .insert() | Syntax: list.insert(index, item) | Uses: Inserts an item into a list at a specified index. |
| .count() | Syntax: list.count(item) | Uses: Returns the number of times an item occurs in a list. |
| samp.count("oak") | Returns 1 | |
| samp.count("pine") | Returns 0 | |
| [1, 2, 2, 3, 2, 4].count(2) | Returns 3 | |
Populating Lists Using Range()
You can use the range() function to populate a list.
myList = range(10) #Creates "myList" that contains all integers between 0 and 10.Examples of Creating a List with Range().
| range(20) | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] | |
| range(0,10) | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | |
| range(0,10,2) | [0, 2, 4, 6, 8] | |
| range(50,100,10) | [50, 60, 70, 80, 90] | |
| range(2,5) | [2, 3, 4] |
List Comprehensions
A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. List comprehensions can often be used to create a list more efficiently than by using loops.
| [x*x for x in [1,2,3,4,5]] | [1, 4, 9, 16, 25] | # Squares for the numbers 1 - 5. |
| [x**2 for x in range(10)] | [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] | # Squares of all numbers (1-10). |
| [n for n in range(15) if n%2 == 0] | [0, 2, 4, 6, 8] | # Even numbers between 0 and 15. |
| [n for n in range(15) if n%2!= 0] | [1, 3, 5, 7, 9] | # Odd numbers between 0 and 15. |
| [(x, x+1) for x in range(1, 10, 2)] | [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)] | # Creates a list of tuples. |
| [bin(n) for n in range(4)] | ['0b0', '0b1', '0b10', '0b11'] | # Binary numbers for 0 to 3. |
| [(n, bin(n)) for n in range(4)] | [(0, '0b0'), (1, '0b1'), (2, '0b10'), (3, '0b11')] | # Creates tuples of the numbers 0 - 3 and their binary equivelants. |
| [round(math.pi,i) for i in range(1, 6)] | ['3.1', '3.14', '3.142', '3.1416', '3.14159'] | # Values for Pi rounded to increasing places. |
More Examples Using List Comprehensions
The following list comprehensions reference the following lists: letters = ("A", "B", "C", "D"); nums = (1, 2, 3, 4)
| [(x, x.lower()) for x in letters] | [('A', 'a'), ('B', 'b'), ('C', 'c'), ('D', 'd')] | # Creates tuples of uppercase and lowercase letters. |
| [(x, ord(x)) for x in letters] | [('A', 65), ('B', 66), ('C', 67), ('D', 68)] | # Creates tuples of letters and corresponding character codes. |
| [(x, y) for x in nums for y in letters] | [(1, 'A'), (1, 'B'), (1, 'C'), (1, 'D'), (2, 'A'), (2, 'B'), (2, 'C'), (2, 'D'), (3, 'A'), (3, 'B'), (3, 'C'), (3, 'D'), (4, 'A'), (4, 'B'), (4, 'C'), (4, 'D')] | # Creates tuples of all possible combinations of two lists. |
Iterating Through a List and Performing an Operation on Each Item
maple
ash
oak
cedar
Python Dictionaries
Dictionaries contain a series of keys and values. They are enclosed in curly brackets. A colon is placed between each key and its associated value. Key / value pairs are separated from other key / value pairs with commas.
The following sample dictionary is referenced by some of the examples in this section:
sample = {'a': 'alpha', 'b': 'bravo', 'c': 'charlie', 'd': 'delta'}
| .items() | Syntax: dictionary.items() | Uses: Returns the values in the dictionary as a list of tuples |
| sample.items() | Returns [('a', 'alpha'), ('c', 'charlie'), ('b', 'bravo'), ('d', 'delta')] | |
| .keys() | Syntax: dictionary.keys() | Uses: Returns a list of keys in a dictionary. |
| sample.keys() | Returns ['a', 'c', 'b', 'd'] | |
| .values() | Syntax: dictionary.values() | Uses: Returns a list of values from a dictionary. |
| sample.values() | Returns ['alpha', 'charlie', 'bravo', 'delta'] | |
| .pop() | Syntax: dictionary.pop('key') | Uses: Removes a key/value pair from the dictionary. Returns its value. |
| sample.pop('b') | Returns 'bravo' | |
| .clear() | Syntax: dictionary.clear() | Uses: Removes all data from the dictionary. |
| in | Syntax: 'value' in dictionary | Uses: Asking if a value is in a dictionary. Returns True or False |
| 'a' in sample | Returns True | |
| 'x' in sample | Returns False | |
| [] | Syntax: dictionary['key'] | Uses: Retrieves the value associated with a key. Generates error if key is not found. |
| sample['c'] | Returns 'omega' | |
| sample['x'] | Returns error message | |
| sample['omega'] | Returns error message | |
Python Sets
Python sets contain an unordered collections of elements with no duplicates.
The following sets are used in the examples below:
fruit = set(['pear', 'apple', 'grape', 'strawberry'])
trees = set(['walnut', 'apple', 'pear', 'pine'])
nuts = set(['pecan', 'walnut', 'peanut'])
| in | Syntax: 'item' in set | Uses: Asks if an item is in a set. Returns True or False. |
| 'apple' in fruit | Returns True | |
| 'apple' in trees | Returns True | |
| 'apple' in nuts | Returns False | |
| & | Syntax: set1 & set2 | Uses: Returns items that appear in both sets. |
| fruit & trees | Returns set(['pear', 'apple']) | |
| - | Syntax: set1 - set2 | Uses: Returns items that appear in set 1, but not set 2. |
| fruit - trees | Returns set(['strawberry', 'grape']) | |
| | | Syntax: set1 | set2 | Uses: Returns items in set 1 or set 2 |
| fruit | trees | Returns set(['grape', 'apple', 'pear', 'pine', 'walnut', 'strawberry']) | |
| ^ | Syntax: set1 ^ set2 | Uses: Returns items in either set 1 or set 2, but not both. |
| fruit ^ trees | Returns set(['grape', 'strawberry', 'pine', 'walnut']) | |
Simple Python Functions
The following Python functions perform simple mathematical operations.
| def square(n): | # Returns the square of a number. |
| def cube(x): | # Returns the cube of a number. |
| def evenOrOdd(n): | # Returns "Even" or "odd" for a number. |
| def absolute(n): | # Returns the absolute value of a number. |
| def factorial(n): | # Returns the factorial of a number. |
| def sumList(list): | # Returns the sum of a list of numbers. |
| def productList(list): | # Returns the product of a list of numbers. |
| def triangular(n): | # Returns the triangular number of a number. |
| def triangular(n): | # Prints the first 'n' triangular numbers. |
| def fahrenheitToCelsius(n): | # Converts Fahrenheit to Celsius. |
| def celsiusToFahrenheit(n): | # Converts Celsius to Fahrenheit. |
| def perimeterCircle(n): | # Returns the perimeter of a circle of radius 'n'. |
| def areaCircle(n): | # Returns the area of a circle of radius 'n'. |
| def perimeterSquare(n): | # Returns the perimeter of a square of length 'n'. |
| def areaSquare(n): | # Returns the area of a square of length 'n'. |
