On this page we'll keep track of the Python types, functions, and operators that we've covered in class. You can also review the online Python References for more complete coverage, BUT NOTE there is way more python in the there then we will cover! The reference page below is all you should need to complete the exam.
Mathematical Operators | Symbol | Meaning | Example |
---|---|---|
+ | addition | 4 + 5 = 9 |
- | subtraction | 9 - 5 = 4 |
* | multiplication | 3*5 = 15 |
/ and // | division | 6/3 = 2.0 6/4 = 1.5 6//4 = 1 |
% | mod/remainder | 5 % 3 = 2 |
** | exponentiation | 3**2 = 9, 2**3 = 8 |
String Operators | + | concatenation | "ab"+"cd"="abcd" |
* | repeat | "xo"*3 = "xoxoxo" |
Comparison Operators | == | is equal to | 3 == 3 is True |
!= | is not equal to | 3 != 3 is False |
>= | is greater than or equal to | 4 >= 3 is True |
<= | is less than or equal to | 4 <= 3 is False |
> | is strictly greater than | 4 > 3 is True |
< | is strictly less than | 3 < 3 is False |
Boolean Operators | ||
x=5 | not | flips/negates the value of a bool | (not x == 5) is False |
and | returns True only if both parts of it are True | (x > 3 and x < 7) is True (x > 3 and x > 7) is False |
or | returns True if at least one part of it is True | (x < 3 or x > 7) is False (x < 3 or x < 7) is True |
Type Conversion Functions | ||
int(x) | turn x into an integer value | int("123") == 123 |
int can fail, e.g., int("abc") raises an error | ||
float(x) | turn x into an float value | float("2.46") == 2.46 |
float can fail, e.g., float("abc") raises an error | ||
str(x) | turn x into a string value | str(432) == "432" |
type(x) | the type of x | type(1) ==
int type(1.2) == float |
Strings | ||
s="colorful", m="one"" | Example | |
s[x] | index a character | s[0] == 'c' s[-3] == 'f' s[5] == 'f' |
s[x:y] | splice of string, substring from index x up to but not including index y | s[2:5] == 'lor' s[:5] == 'color' s[4:-1] == 'rfu' s[5:] == 'ful' |
Lists | ||
lst =[3, 6, 8, 1, 7] | Example | |
lst[x] | index an element | lst[0] == 3 lst[-1] == 7 |
lst[x:y] | splice of list, sublist from index x up to but not including index y | lst[1:3] == [6, 8] lst[:4] == [3, 6, 8, 1] lst[3:] == [1,7] |
Miscellaneous Functions | ||
help(x) | documentation for module x | |
len(x) | length of sequence x, e.g., String | len("duke") == 4 |
Random Functions (import random) | ||
random.choice(list_of_choices) | returns a random element from list_of_choices. Gives an error if list_of_choices has length 0. | |
random.randint(start, end) | Returns a random integer between start and end. Unlike range() and list slicing, the largest value it can return is end, not end-1. | |
random.random() | Returns a random float between 0 and 1. |