Python Syntax
Variable Declaration
I would like to store a value in a variable.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| bool_value1: bool = True
bool_value2: bool = False
int_value: int = 5
string_value: str = "hello"
list_value1: list[str] = []
list_value2: list[int] = [1, 2, 3]
first_item_inside_list2: int = list_value[0] # = 1
second_item_inside_list2: int = list_value[1] # = 2
pair_value: tuple[int, str] = (1, "one")
triple_value: tuple[str, int, bool] = (1, "one")
first_item_inside_triple: int = list_value[0] # = 1
set_value: set[str] = set(["hi", "there", "hi"])
dict_value: dict[str, int] = {"one": 1, "two": 3}
value_inside_dict: int = list_value["two"] # = 3
|
Definite Loops
I would like to loop over a single list.
1
2
3
4
5
6
7
| list_val: list[str] = ["these", "are", "some", "values"]
for item in list_val:
print(item)
for other_name in list_val:
print(other_name)
|
these
are
some
values
these
are
some
values
I would like to loop over a range of numbers.
1
2
3
4
5
6
7
8
9
| # Loops over the numbers: 1, 2, 3
# The left number is INCLUSIVE; the right number is EXCLUSIVE
for i in range(1, 4):
print(i)
# We can "nest" these for loops too to get all the pairs of numbers!
for i in range(3):
for j in range(2):
print((i, j))
|
1
2
3
(0, 0)
(0, 1)
(1, 0)
(1, 1)
(2, 0)
(2, 1)
I would like to loop over two lists at once.
1
2
3
4
5
| list1: list[str] = ["these", "are", "some", "values"]
list2: list[str] = [1, 3, 5, 7]
for i in range(len(list1):
print(str(list2[i] + ": " + list1[i]))
|
1: these
3: are
5: some
7: values
I would like to find the maximum or “best” item in a list.
1
2
3
4
5
6
7
8
| candidates: list[str] = ["these", "are", "some", "values"]
best_so_far: str = candidates[0]
for candidate in candidiates:
if len(best_so_far) < len(candidate)
best_so_far = candidate
print("the longest word in the list was: " + best_so_far)
|
the longest word in the list was: values
Conditional Statements
I would like to only execute code when a list contains a particular item.
1
2
3
| lst: list[str] = ["a", "b", "c"]
if "a" in lst:
print("the list contains a")
|
I would like to only execute code when a list DOES NOT contain a particular item.
1
2
3
4
5
| lst: list[str] = ["a", "b", "c"]
if "a" not in lst:
print("the list DOES NOT contain a")
else:
print("the list DOES contain a")
|
I would like to only execute code when an equality is true.
s1: set[str] = set([“a”, “b”, “c”])
s2: set[str] = set([“a”, “c”])
1
2
3
4
| if s1 == s2:
print("the sets have the same elements!")
else:
print("the sets DO NOT HAVE the same elements!")
|
the sets DO NOT HAVE the same elements!
I would like to only execute code when several conditions are all true.
1
2
3
4
5
6
7
8
9
| s: set[str] = set()
if "a" in s and "b" in s:
print("the set contains a and b!")
elif "a" in s:
print("the set contains a, but not b!")
elif "b" in s:
print("the set contains b, but not a!")
else:
print("the set contains neither a nor b!")
|
the set contains neither a nor b!
I would like to only execute code when any of several conditions is true.
1
2
3
4
5
| i: int = 5
if i < 0 or i > 6:
print("i is small or largeish")
else:
print("i is 0, 1, 2, 3, 4, 5, or 6")
|
i is 0, 1, 2, 3, 4, 5, or 6
I would like to only execute code when all elements of a list have a certain condition.
1
2
3
4
5
6
7
8
9
| letters: list[str] = ["a", "b", "c", "D"]
all_lowercase = True
for x letters:
if x != x.lower():
all_lowercase = False
if all_lowercase:
print("every letter in the list is lower case")
else:
print("at least one letter in the list is not lower case")
|
at least one letter in the list is not lower case
I would like to only execute code when any element of a list has a certain condition.
1
2
3
4
5
6
7
8
9
| letters: list[str] = ["a", "b", "c", "D"]
any_lowercase = True
for x letters:
if x == x.lower():
any_lowercase = True
if all_lowercase:
print("at least one letter in the list is lower case")
else:
print("every letter in the list is not lower case")
|
at least one letter in the list is lower case
Indefinite Loops
I would like to loop forever.
1
2
| while True:
print("hiiiiiii")
|
hiiiiiii
hiiiiiii
hiiiiiii
hiiiiiii
hiiiiiii
...repeatedly, forever
1
2
3
4
| answer: str = ""
while answer.lower() != "exit":
answer = input("Type \"exit\" to exit: ")
print(answer)
|
Python Built-Ins
Strings
s.lower()
Returns a new String
with all characters of s
changed to their lowercase version.
1
2
| s: str = "HEllo"
print(s.lower())
|
s.upper()
Returns a new String
with all characters of s
changed to their uppercase version.
1
2
| s: str = "HEllo"
print(s.upper())
|
s.strip()
Returns a new String
with leading and trailing spaces omitted from s
.
1
2
| s: str = " hello "
print(s.strip())
|
s.startswith(substr)
Returns True
if s
starts with the sub-string substr
, False
otherwise.
1
2
3
| s: str = "Hippopotamus"
print(s.startswith("hip"))
print(s.startswith("Hip"))
|
s.endswith(substr)
Returns True
if s
ends with the sub-string substr
, False
otherwise.
1
2
3
| s: str = "Hippopotamus"
print(s.startswith("tamus"))
print(s.startswith("tamus."))
|
s.replace(substr1, substr2)
Returns a new String
with with all occurrences of substr1
replaced by substr2
.
1
2
| s: str = "hello"
print(s.replace('l',"ll"))
|
s.split(sep)
Returns a list corresponding to s
split based on the separator sep
.
1
2
| s: str = "I love examples!"
print(s.split(' '))
|
['I', 'love', 'examples!']
sep.join(lst)
Returns a new String
corresponding to the elements of lst
joined by the separator sep
.
1
2
| lst1: list[str] = ['I', 'love', 'examples!']
print('X'.join(lst1))
|
s.isdigit()
Returns True
if all characters in s
are digits, False
otherwise.
1
2
| s: str = "01112220"
print(s.isdigit())
|
Lists
I would like to check if a particular item is anywhere in a list.
1
2
3
4
5
| lst: list[tuple[int, int]] = [(0, 0), (1, 1), (2, 2)]
if (0, 1) in lst:
print("(0, 1) is an element of lst")
else:
print("(0, 1) is NOT an element of lst")
|
(0, 1) is NOT an element of lst
I would like to get the number of items in a list.
1
2
3
| lst: list[tuple[int, int]] = [(0, 0), (1, 1), (2, 2)]
number_of_items = len(lst)
print("the number of items in lst is: " + str(number_of_items))
|
the number of items in lst is: 3
I would like to get the first or last element of a list.
1
2
3
4
5
| lst: list[tuple[int, int]] = [(0, 0), (1, 1), (2, 2)]
print(lst[0])
print(lst[1])
print(lst[-2])
print(lst[-1])
|
(0, 0)
(1, 1)
(1, 1)
(2, 2)
I would like to get a “sublist” of a list.
1
2
3
4
5
| lst: list[tuple[int, int]] = [(0, 0), (1, 1), (2, 2)]
print(lst[0:0])
print(lst[0:1])
print(lst[0:-1])
print(lst[1:-1])
|
[]
[(0, 0)]
[(0, 0), (1, 1)]
[(1, 1)]
I would like to put two lists together.
1
2
3
4
| lst1: list[tuple[int, int]] = [(0, 0), (1, 1), (2, 2)]
lst2: list[tuple[int, int]] = [(2, 2), (3, 3), (4, 4)]
combined: list[tuple[int, int]] = lst1 + lst2
print(combined)
|
[(0, 0), (1, 1), (2, 2), (2, 2), (3, 3), (4, 4)]
I would like to add an element to the end of a list.
1
2
3
| lst: list[tuple[int, int]] = [(0, 0), (1, 1), (2, 2)]
lst.append((3, 3))
print(lst)
|
[(0, 0), (1, 1), (2, 2), (3, 3)]
I would like to remove an element at a particular index.
1
2
3
4
5
6
7
8
| lst: list[tuple[int, int]] = [(0, 0), (1, 1), (2, 2)]
print(lst)
a = lst.pop(0)
print(a)
print(lst)
b = lst.pop(-1)
print(b)
print(lst)
|
[(0, 0), (1, 1), (2, 2)]
(0, 0)
[(1, 1), (2, 2)]
(2, 2)
[(1, 1)]
Dictionaries
I would like to check if a particular key is anywhere in a dictionary.
1
2
3
4
5
6
7
8
| d: dict[str, int] = {"this": 4, "is": 2, "an": 2, "example": 7}
if "this" in d:
print("\"this\" is a key in d")
if 4 in d:
print("4 is a key in d")
else:
print("4 is NOT a key in d")
|
"this" is a key in d
4 is NOT a key in d
I would like to add or replace a key-value pair to a dictionary.
1
2
3
4
5
6
7
8
9
| words: list[str] = ["based", "lit", "no cap", "rizz", "no cap", "based", "based"]
d: dict[str, int] = {}
for word in words:
if word in d:
d[word] += 1 # Since word is already in d, increase the count
else:
d[word] = 1 # Otherwise, this is the first time we've seen it
print(d)
|
{'based': 1}
{'based': 1, 'lit': 1}
{'based': 1, 'lit': 1, 'no cap': 1}
{'based': 1, 'lit': 1, 'no cap': 1, 'rizz': 1}
{'based': 1, 'lit': 1, 'no cap': 2, 'rizz': 1}
{'based': 2, 'lit': 1, 'no cap': 2, 'rizz': 1}
{'based': 3, 'lit': 1, 'no cap': 2, 'rizz': 1}
I would like to get the number of key-value pairs in a dictionary.
1
2
3
| d: dict[str, int] = {"this": 4, "is": 2, "an": 2, "example": 7}
number_of_items = len(lst)
print("the number of items in d is: " + str(number_of_items))
|
the number of items in d is: 4
I would like to get or loop over the keys in a dictionary.
1
2
3
4
5
6
7
8
| d: dict[str, int] = {"this": 4, "is": 2, "an": 2, "example": 7}
keys: list[str] = list(d.keys())
print(keys) # Note that this may not be ordered consistently!
for x in d:
print(x + " is a key in d")
print("...but " + str(d[x]) + " is a value in d")
|
["is", "this", "an", "example"]
is is a key in d
...but 2 is a value in d
this is a key in d
...but 4 is a value in d
an is a key in d
...but 2 is a value in d
example is a key in d
...but 7 is a value in d
Libraries
random
random.randint(lo, hi)
Returns a random integer between lo
and hi
, including both lo
and hi
.
1
2
3
4
| print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10))
|
random.choice(choices)
Returns a random element from a non-empty list/set/tuple/string choices
. If choices
is empty, this function will raise
an Exception
.
1
2
3
4
5
6
| fruits = ["banana", "apple", "plum", "orange", "cherry"]
vegetables = ("broccoli", "carrot", "eggplant")
letters = "ABCD"
print(random.choice(fruits))
print(random.choice(vegetables))
print(random.choice(letters))
|
vpython
box(pos, length, height, width, color)
Returns a box of color color centered at pos with length length, height height, and width width.
1
2
| obj = box(pos=vec(1, 1, 1), length=2, height=3, width=4, color=color.cyan)
print(obj.length)
|
cylinder(pos, axis, color)
Returns a cylinder of color color with one circular end centered at pos. The central axis of the cylinder
is axis and points from the end at pos to the other end.
1
2
3
| obj = cylinder(pos=vec(3, 2, 1), axis=vec(5, 4, 6), color=color.red)
print(obj.pos)
print(str(obj.pos.x) + ", " + str(obj.pos.y) + ", " + str(obj.pos.z))
|
sphere(pos, radius, color)
Returns a new box of color color centered at pos with length length, height height, and width width.
1
2
| obj = sphere(pos=vec(0, 1, 0), radius=4, color=color.yellow)
print(obj.radius)
|