Fundamentals
|
my_string = "Hello World"
|
my_other_string = 'Hello there'
|
Print to console: print("Hello World!")
|
Collect input (string): my_input = input("Write: ")
|
|
|
|
|
Integer division (floors): 5 \\ 3
|
|
|
|
|
Type conversion: str()
, int()
, float()
, bool()
|
|
Equality of values: a == b
|
Equality of references: a is b
|
Conditional Logic
if (boolean_condition_1):
result_1
elif (boolean_condition_2):
result_2
else:
result_default
|
If one block has been executed, the others cannot be executed, even if their relative condition is True
.
Looping
for i in range(5):
print(i) # Prints 0 to 4
for i in ["Alpha", "Beta"]:
print(i) # Prints "Alpha" and "Beta"
j = 0
while (j < 3):
print(j) # Prints 0 to 3
j = j+1
|
You can loop through an iterable, which can be a range, a list, a tuple, a dictionary using for
or through a condition, using while
.
|
|
List Comprehension
# Squares of even numbers less than 10
[i * i for i in range(10) if i % 2 == 0]
# Multiple conditions (odds become negative)
[i if i % 2 == 0 else -i for i in range(10]
|
List Methods
Add an item to the end: lst.append(item)
|
Add a list of items to the end: lst.extend(list_of_items)
|
Insert an item at an index: lst.insert(index, item)
|
Remove all items: lst.clear()
|
Remove & return an item at an index: lst.pop(index)
|
Remove the first item with given value: lst.remove(val)
|
Removes an item at an index: lst.del(index)
|
Gives the index of a given value: lst.index(val, start, end)
|
Gives the count of a given value: lst.count(val)
|
In-place reverses the list: lst.reverse()
|
In-place sorts the list: lst.sort()
|
String aggregates: sep.join(lst) |
Negative indices start from the end of the list, with my_list[-1]
. Using list()
converts an iterable to a list.
Slicing
lst = [0, 5, 10, 15, 20]
# Generic
collection[start:end:step]
collection[3] # 15
collection[1:] # [5, 10, 15, 20]
collection[:2] # [0, 5]
collection[::2] # [0, 10, 20]
collection[::-1] # [20, 15, 10, 5, 0]
|
Slicing can be applied to ordered collections. The start is inclusive and the end is exclusive.
|
|
|
|
|